### Install sievelib from Git Source: https://github.com/tonioo/sievelib/blob/master/README.rst Clone the sievelib repository from GitHub and install it locally. ```bash git clone git@github.com:tonioo/sievelib.git cd sievelib python ./setup.py install ``` -------------------------------- ### Install sievelib using pip Source: https://github.com/tonioo/sievelib/blob/master/README.rst Install the sievelib library from PyPI using pip. ```bash pip install sievelib ``` -------------------------------- ### Initialize and connect ManageSieve client Source: https://github.com/tonioo/sievelib/blob/master/README.rst Instantiate the `Client` class for a ManageSieve server and establish a connection using credentials and authentication mechanism. Supports explicit STARTTLS. ```python from sievelib.managesieve import Client c = Client("server.example.com") c.connect("user", "password", starttls=False, authmech="DIGEST-MD5") True ``` -------------------------------- ### ManageSieve Client: Connect and Authenticate Source: https://context7.com/tonioo/sievelib/llms.txt Shows how to connect to a mail server using the ManageSieve client with explicit (STARTTLS) or implicit TLS/SSL, and demonstrates various authentication mechanisms including PLAIN, DIGEST-MD5, LOGIN, OAUTHBEARER, and XOAUTH2. ```python from sievelib.managesieve import Client, Error client = Client("mail.example.com", srvport=4190) try: success = client.connect( login="user@example.com", password="secretpassword", starttls=True, authmech="PLAIN" # or "DIGEST-MD5", "LOGIN", "OAUTHBEARER", "XOAUTH2" ) if success: print("Connected successfully!") print(f"Implementation: {client.get_implementation()}") print(f"SASL mechanisms: {client.get_sasl_mechanisms()}") print(f"Sieve extensions: {client.get_sieve_capabilities()}") print(f"TLS support: {client.has_tls_support()}") else: print(f"Connection failed: {client.errmsg}") except Error as e: print(f"Error: {e}") client_ssl = Client("mail.example.com", srvport=993) client_ssl.connect( login="user@example.com", password="secretpassword", ssl=True # Implicit TLS ) client_oauth = Client("mail.example.com") client_oauth.connect( login="user@example.com", password="oauth_access_token", starttls=True, authmech="OAUTHBEARER" # or "XOAUTH2" for Google ) client.logout() ``` -------------------------------- ### Add 'fileinto' Action with :create Flag Source: https://context7.com/tonioo/sievelib/llms.txt File messages into a folder, creating the folder if it does not exist, using the ':create' flag. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # File with :create flag (creates folder if missing) fs.addfilter("File with create", [("From", ":contains", "@newclient.com")], [("fileinto", ":create", "Clients/New")]) ``` -------------------------------- ### Define Sieve filters with sievelib Source: https://context7.com/tonioo/sievelib/llms.txt Demonstrates creating various email filters including flag management, vacation auto-replies, and complex multi-action rules. ```python fs.addfilter("Flag as seen", [("From", ":contains", "automated")], [("addflag", "\\Seen"), ("fileinto", "Automated")]) fs.addfilter("Mark important", [("Subject", ":contains", "URGENT")], [("addflag", "\\Flagged"), ("keep",)]) # Vacation auto-reply (requires vacation extension) fs.addfilter("Out of office", [("true",)], [("vacation", ":days", 7, ":subject", "Out of Office Auto-Reply", ":from", "user@example.com", "I am currently out of the office and will respond when I return.")]) # Multiple actions fs.addfilter("Complex actions", [("From", ":contains", "@partner.com")], [ ("addflag", "\\Flagged"), ("fileinto", ":copy", "Partners"), ("redirect", "team@company.com") ]) fs.tosieve() ``` -------------------------------- ### Parse and Manage Sieve Filters Source: https://context7.com/tonioo/sievelib/llms.txt Demonstrates parsing an existing Sieve script, loading it into a FiltersSet, and performing operations like checking existence, retrieving details, updating, disabling, enabling, reordering, and removing filters. ```python p = Parser() p.parse('' require ["fileinto"]; # Filter: Old Rule if header :is "From" "old@example.com" { fileinto "Archive"; } '') fs = FiltersSet("existing_filters") fs.from_parser_result(p) if fs.filter_exists("Old Rule"): print("Filter found!") filter_obj = fs.getfilter("Old Rule") conditions = fs.get_filter_conditions("Old Rule") actions = fs.get_filter_actions("Old Rule") matchtype = fs.get_filter_matchtype("Old Rule") print(f"Conditions: {conditions}") # [('From', ':is', 'old@example.com')] print(f"Actions: {actions}") # [('fileinto', 'Archive')] fs.updatefilter( "Old Rule", "Updated Rule", [("From", ":is", "new@example.com")], [("fileinto", "NewFolder")] ) fs.disablefilter("Updated Rule") print(fs.is_filter_disabled("Updated Rule")) # True fs.enablefilter("Updated Rule") fs.movefilter("Updated Rule", "up") # or "down" fs.removefilter("Updated Rule") ``` -------------------------------- ### Add 'fileinto' Action Source: https://context7.com/tonioo/sievelib/llms.txt File messages into a specified folder. This is a common action for organizing emails. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # File into folder fs.addfilter("File to folder", [("From", ":contains", "@newsletter.com")], [("fileinto", "Newsletters")]) ``` -------------------------------- ### Define and Register Custom Sieve Commands Source: https://context7.com/tonioo/sievelib/llms.txt Define custom Sieve action and test commands with their argument definitions and register them with the parser. ```python from sievelib.parser import ActionCommand, TestCommand, Parser from sievelib.parser import add_commands # Define a custom action command class MyCustomActionCommand(ActionCommand): """Custom action that takes a tag and string argument.""" extension = "mycustomext" # Required extension name args_definition = [ { "name": "severity", "type": ["tag"], "values": [":low", ":medium", ":high"], "required": False }, { "name": "message", "type": ["string"], "required": True } ] # Define a custom test command class MyCustomTestCommand(TestCommand): """Custom test with string list argument.""" extension = "mycustomext" args_definition = [ { "name": "values", "type": ["string", "stringlist"], "required": True } ] # Register custom commands with the parser add_commands([MyCustomActionCommand, MyCustomTestCommand]) # Now parse scripts using custom commands p = Parser() script = ''' require ["mycustomext"]; if mycustomtest ["value1", "value2"] { mycustomaction :high "Alert triggered!"; } ''' if p.parse(script): print("Custom script parsed successfully!") p.dump() ``` -------------------------------- ### Parse Sieve script in Python environment Source: https://github.com/tonioo/sievelib/blob/master/README.rst Instantiate the `Parser` class and use its `parse` method to check Sieve syntax. The `error` attribute provides details on parsing failures. ```python from sievelib.parser import Parser p = Parser() p.parse('require ["fileinto"];') True p.dump() require (type: control) ["fileinto"] p.parse('require ["fileinto"]') False p.error 'line 1: parsing error: end of script reached while semicolon expected' ``` -------------------------------- ### Add 'fileinto' Action with :copy Flag Source: https://context7.com/tonioo/sievelib/llms.txt File messages into a folder while keeping a copy in the inbox using the ':copy' flag. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # File with :copy flag (keeps copy in inbox) fs.addfilter("Copy to folder", [("Subject", ":contains", "important")], [("fileinto", ":copy", "Important")]) ``` -------------------------------- ### Commands Module: Extend Parser Source: https://context7.com/tonioo/sievelib/llms.txt Illustrates how to extend the Sieve parser with custom commands by defining new command classes that inherit from ControlCommand, ActionCommand, or TestCommand. ```python import sievelib from sievelib.commands import ActionCommand, TestCommand, add_commands from sievelib.parser import Parser ``` -------------------------------- ### Parse Sieve script from command line Source: https://github.com/tonioo/sievelib/blob/master/README.rst Use the `parser.py` script to check the syntax of a Sieve file from the command line. ```bash $ cd sievelib $ python parser.py test.sieve Syntax OK $ ``` -------------------------------- ### Create Sieve filters using FiltersSet Source: https://github.com/tonioo/sievelib/blob/master/README.rst Utilize the `FiltersSet` class from the `factory` module to easily generate Sieve rules. Add filters with conditions and actions, then convert to Sieve format. ```python from sievelib.factory import FiltersSet fs = FiltersSet("test") fs.addfilter("rule1", [("Sender", ":is", "toto@toto.com"),], [("fileinto", "Toto"),]) fs.tosieve() require ["fileinto"]; # Filter: rule1 if anyof (header :is "Sender" "toto@toto.com") { fileinto "Toto"; } ``` -------------------------------- ### Manage Existing Filters Source: https://context7.com/tonioo/sievelib/llms.txt FiltersSet supports loading, updating, and manipulating existing filter configurations. ```python from sievelib.factory import FiltersSet from sievelib.parser import Parser ``` -------------------------------- ### Extend sievelib parser with custom commands Source: https://github.com/tonioo/sievelib/blob/master/README.rst Define and add a custom Sieve command to the parser. Requires importing the base class and using `add_commands`. ```python import sievelib class MyCommand(sievelib.commands.ActionCommand): args_definition = [ {"name": "testtag", "type": ["tag"], "values": [":testtag"], "extra_arg": {"type": "number", "required": False}, "required": False}, {"name": "recipients", "type": ["string", "stringlist"], "required": True} ] siebelib.commands.add_commands(MyCommand) ``` -------------------------------- ### Add 'reject' Action Source: https://context7.com/tonioo/sievelib/llms.txt Reject incoming messages with a specified reason message. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Reject with message fs.addfilter("Reject spam", [("From", ":contains", "@spammer.com")], [("reject", "Your message has been rejected as spam.")]) ``` -------------------------------- ### ManageSieve Client: List and Manage Scripts Source: https://context7.com/tonioo/sievelib/llms.txt Details how to use the ManageSieve client to list, retrieve, upload, validate, activate, rename, and delete Sieve scripts on a mail server. It also covers checking server space for new scripts. ```python from sievelib.managesieve import Client client = Client("mail.example.com") client.connect("user@example.com", "password", starttls=True) active_script, other_scripts = client.listscripts() print(f"Active script: {active_script}") print(f"Other scripts: {other_scripts}") script_content = client.getscript("main_filter") if script_content: print(script_content) else: print(f"Error: {client.errmsg}") new_script_content = "" script_size = len(new_script_content) if client.havespace("new_script", script_size): print("Space available") new_script = ''' require ["fileinto"]; if header :contains "Subject" "newsletter" { fileinto "Newsletters"; } ''' if client.putscript("newsletter_filter", new_script): print("Script uploaded successfully") else: print(f"Upload failed: {client.errmsg}") try: if client.checkscript(new_script): print("Script syntax is valid") except NotImplementedError: print("Server doesn't support CHECKSCRIPT") if client.setactive("newsletter_filter"): print("Script activated") client.setactive("") if client.renamescript("old_name", "new_name"): print("Script renamed") if client.deletescript("obsolete_script"): print("Script deleted") client.logout() ``` -------------------------------- ### Add 'redirect' Action with :copy Flag Source: https://context7.com/tonioo/sievelib/llms.txt Redirect messages to another address while also keeping a copy in the inbox. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Redirect with copy fs.addfilter("Forward with copy", [("Subject", ":contains", "support")], [("redirect", ":copy", "support@company.com")]) ``` -------------------------------- ### Parse and Validate Sieve Scripts with Parser Source: https://context7.com/tonioo/sievelib/llms.txt Use the Parser class to tokenize and validate Sieve script syntax. The parse method returns a boolean indicating success and builds a command tree. ```python from sievelib.parser import Parser # Create a parser instance p = Parser() # Parse a simple Sieve script script = ''' require ["fileinto", "reject"]; # Filter spam to Junk folder if header :contains "Subject" "SPAM" { fileinto "Junk"; stop; } # Reject messages from blocked sender if header :is "From" "blocked@example.com" { reject "Your message has been rejected"; } ''' # Parse and check for syntax errors if p.parse(script): print("Syntax OK") # Dump the parsing tree p.dump() # Output: # require (type: control) # ["fileinto", "reject"] # if (type: control) # anyof (type: test) # header (type: test) # :contains # "Subject" # "SPAM" # fileinto (type: action) # "Junk" # stop (type: action) # if (type: control) # ... else: print(f"Error: {p.error}") # Error includes line number and description # e.g., "line 5: parsing error: unknown token xyz" ``` -------------------------------- ### Manage Sieve scripts using ManageSieve client Source: https://github.com/tonioo/sievelib/blob/master/README.rst Perform common ManageSieve operations such as listing scripts, setting the active script, and checking available space for new scripts. ```python c.listscripts() ("active_script", ["script1", "script2"]) c.setactive("script1") True c.havespace("script3", 45) True ``` -------------------------------- ### Parse Sieve Scripts from Files Source: https://context7.com/tonioo/sievelib/llms.txt Use parse_file to read and validate Sieve scripts directly from the filesystem. Error details are accessible via the error and error_pos attributes. ```python from sievelib.parser import Parser p = Parser(debug=False) # Parse a script file if p.parse_file("/path/to/myscript.sieve"): print("Script is valid!") # Access the parsed commands for command in p.result: print(f"Command: {command.name}, Type: {command.get_type()}") # Convert back to Sieve syntax command.tosieve() else: # Get detailed error information print(f"Parse error: {p.error}") # p.error_pos contains (line_number, column_number, token_length) line, col, length = p.error_pos print(f"Error at line {line}, column {col}") ``` -------------------------------- ### Add Complex Filter with AND Logic Source: https://context7.com/tonioo/sievelib/llms.txt Combine multiple conditions using 'allof' to ensure all criteria must be met for the filter to apply. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Multiple conditions with AND (allof) fs.addfilter("Complex filter", [ ("From", ":contains", "@company.com"), ("Subject", ":contains", "report"), ("size", ":under", "1M") ], [("fileinto", "Reports")], matchtype="allof") ``` -------------------------------- ### Add 'redirect' Action Source: https://context7.com/tonioo/sievelib/llms.txt Redirect incoming messages to another email address. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Redirect to another address fs.addfilter("Forward emails", [("From", ":is", "vip@company.com")], [("redirect", "assistant@company.com")]) ``` -------------------------------- ### Add Filter with OR Logic Source: https://context7.com/tonioo/sievelib/llms.txt Combine multiple conditions using 'anyof' (default) so that if any criterion is met, the filter applies. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Multiple conditions with OR (anyof - default) fs.addfilter("Any spam indicator", [ ("Subject", ":contains", "SPAM"), ("From", ":contains", "noreply"), ("Header", ":contains", "X-Spam-Flag") ], [("fileinto", "Junk")], matchtype="anyof") # Print generated script print(fs) ``` -------------------------------- ### Filter email by subject header Source: https://github.com/tonioo/sievelib/blob/master/sievelib/tests/files/utf8_sieve.txt Uses the fileinto extension to move matching emails to a Spam folder. Requires the fileinto and reject extensions to be enabled. ```Sieve require ["fileinto", "reject"]; # Filter: UTF8 Test Filter äöüß 汉语/漢語 Hànyǔ if allof (header :contains ["Subject"] ["€ 300"]) { fileinto "Spam"; stop; } ``` -------------------------------- ### Add Header Filter Conditions Source: https://context7.com/tonioo/sievelib/llms.txt Add filters based on header content using different match types like 'contains', 'is', and 'matches'. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Header test with different match types fs.addfilter("Header contains", [("Subject", ":contains", "meeting")], [("fileinto", "Meetings")]) fs.addfilter("Header exact match", [("From", ":is", "boss@company.com")], [("fileinto", "Boss")]) fs.addfilter("Header pattern match", [("Subject", ":matches", "*urgent*")], [("fileinto", "Urgent")]) ``` -------------------------------- ### Add Size-Based Filter Conditions Source: https://context7.com/tonioo/sievelib/llms.txt Filter emails based on their size, using 'over' for larger than and 'under' for smaller than. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Size-based filtering fs.addfilter("Large attachments", [("size", ":over", "5M")], [("fileinto", "LargeEmails")]) fs.addfilter("Small messages", [("size", ":under", "10K")], [("fileinto", "SmallEmails")]) ``` -------------------------------- ### Add Exists Filter Condition Source: https://context7.com/tonioo/sievelib/llms.txt Check for the existence of a specific header using the 'exists' test. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Exists test - check if header exists fs.addfilter("Has priority header", [("exists", "X-Priority")], [("fileinto", "Priority")]) ``` -------------------------------- ### Add Negated Header Filter Source: https://context7.com/tonioo/sievelib/llms.txt Use the 'not' prefix to negate conditions, such as filtering emails not from a specific domain. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Negated conditions (prefix with 'not') fs.addfilter("Not from domain", [("From", ":notcontains", "@spam.com")], [("keep",)]) ``` -------------------------------- ### Add 'discard' Action Source: https://context7.com/tonioo/sievelib/llms.txt Silently discard incoming messages without sending any notification. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Discard silently fs.addfilter("Discard junk", [("Header", ":is", "X-Spam-Flag", "YES")], [("discard",)]) ``` -------------------------------- ### Add 'stop' Action Source: https://context7.com/tonioo/sievelib/llms.txt Stop processing further Sieve rules after this action is executed. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Stop processing fs.addfilter("Stop after match", [("From", ":is", "admin@company.com")], [("fileinto", "Admin"), ("stop",)]) ``` -------------------------------- ### Add Envelope Filter Condition Source: https://context7.com/tonioo/sievelib/llms.txt Filter based on envelope information, such as the recipient address. Requires the 'envelope' extension. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Envelope test (requires 'envelope' extension) fs.addfilter("Envelope check", [("envelope", ":is", ["to"], ["me@example.com"])], [("fileinto", "DirectToMe")]) ``` -------------------------------- ### Add Body Content Filter Condition Source: https://context7.com/tonioo/sievelib/llms.txt Filter emails based on their body content using the ':text' and ':contains' arguments. Requires the 'body' extension. ```python from sievelib.factory import FiltersSet fs = FiltersSet("conditions_demo") # Body content test (requires 'body' extension) fs.addfilter("Body contains keyword", [("body", ":text", ":contains", "confidential")], [("fileinto", "Confidential")]) ``` -------------------------------- ### Add 'keep' Action Source: https://context7.com/tonioo/sievelib/llms.txt Explicitly keep messages in the inbox, preventing them from being acted upon by subsequent rules. ```python from sievelib.factory import FiltersSet fs = FiltersSet("actions_demo") # Keep in inbox (explicit) fs.addfilter("Keep important", [("From", ":contains", "@bank.com")], [("keep",)]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.