### SpamAssassin Configuration: Full Rule Definition Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf This example shows the definition of a 'full' rule in SpamAssassin, which uses a regular expression to match specific patterns in email content. It also includes a description for the rule. ```spamassassin full PARA_A_2_C_OF_1618 /Paragraph .a.{0,10}2.{0,10}C. of S. 1618/i describe PARA_A_2_C_OF_1618 Claims compliance with senate bill 1618 ``` -------------------------------- ### LDAP Search Configuration Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf An example of an LDAP URI for searching SpamAssassin configuration. It specifies the host, port, base DN, search scope, attribute, and a filter that includes a placeholder for the username. ```plaintext ldap://localhost:389/dc=koehntopp,dc=de?spamassassinconfig?uid=__USERNAME__ ``` -------------------------------- ### LDAP Bind DN Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf An example of a Bind DN (Distinguished Name) used for connecting to an LDAP server for SpamAssassin user scores. ```plaintext cn=master,dc=koehntopp,dc=de ``` -------------------------------- ### Conditional Configuration Expression Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Illustrates the use of the 'if' directive for conditional processing of SpamAssassin configuration. It allows for basic arithmetic comparisons using numbers, whitespace, and arithmetic operations. ```plaintext if (conditional perl expression) ``` -------------------------------- ### Instantiate SQLBasedAddrList Factory in Perl Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_SQLBasedAddrList Demonstrates how to create a new instance of the SQLBasedAddrList factory and set it as the persistent address list factory for SpamAssassin. This is the initial setup step for using SQL-based whitelisting. ```perl my $factory = Mail::SpamAssassin::SQLBasedAddrList->new(); $spamtest->set_persistent_addr_list_factory ($factory); ``` -------------------------------- ### SpamAssassin Configuration: Language-Specific Description Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf This snippet demonstrates how to provide a description for a SpamAssassin rule in a specific language (Spanish in this case). This is useful for internationalized configurations. ```spamassassin lang es describe FROM_FORGED_HOTMAIL Forzado From: simula ser de hotmail.com ``` -------------------------------- ### SpamAssassin Plugin Configuration Parsing Example in Perl Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Plugin This Perl code example shows how a SpamAssassin plugin can parse its configuration lines. The 'parse_config' method receives options like 'line', 'key', 'value', and 'conf', allowing the plugin to process specific settings and optionally inhibit further callbacks if the setting is handled. ```perl sub parse_config { my ($self, $opts) = @_; print "MyPlugin: parse_config got " . $opts->{line} . "\n"; } ``` -------------------------------- ### SpamAssassin Configuration: Score Assignment Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf This example shows how to assign a specific score to a SpamAssassin rule. A score of 2.0 is assigned to the 'A_HREF_TO_REMOVE' rule, indicating its spam likelihood. ```spamassassin score A_HREF_TO_REMOVE 2.0 ``` -------------------------------- ### SpamAssassin Configuration: Header Rule Definition Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf This snippet illustrates how to define a 'header' rule in SpamAssassin, which checks specific patterns within email headers. A description is provided for clarity. ```spamassassin header FROM_HAS_MIXED_NUMS From =~ /\d+[a-z]+\d+\S*@/i describe FROM_HAS_MIXED_NUMS From: contains numbers mixed in with letters ``` -------------------------------- ### Compile SpamAssassin Settings Immediately (SpamAssassin) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin Compiles all patterns, loads all configuration files, and loads all possibly-required Perl modules. This function is useful for avoiding lazy evaluation issues when forking processes or starting new threads. It can optionally skip user preferences and manage user state during compilation. ```perl $f->compile_now ($use_user_prefs, $keep_userstate); ``` -------------------------------- ### Get SpamAssassin Test Results (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Provides examples of retrieving specific information about why a message was flagged as spam or not. This includes getting the score, the required score, and lists of triggered tests. ```perl my $score = $status->get_score (); my $required_score = $status->get_required_score (); my $tests_hit = $status->get_names_of_tests_hit (); my $subtests_hit = $status->get_names_of_subtests_hit (); ``` -------------------------------- ### Mail::SpamAssassin::BayesStore Initialization and Configuration Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_BayesStore Methods for creating a new BayesStore instance, reading configuration, and managing database connections. ```APIDOC ## Mail::SpamAssassin::BayesStore Initialization and Configuration ### Description Provides methods for initializing the BayesStore, reading configuration, and managing read-only or writable database connections. ### Methods #### `new(Mail::SpamAssassin::Bayes $bayes)` - **Description**: Creates a new instance of the Mail::SpamAssassin::BayesStore object, requiring an instance of Mail::SpamAssassin::Bayes. - **Type**: `public class` #### `DB_VERSION()` - **Description**: Returns the currently supported database version for the implementation. - **Type**: `public instance (Integer)` #### `read_db_configs()` - **Description**: Reads configuration variables and calls the `Mail::SpamAssassin::Bayes::read_db_configs` method. - **Type**: `public instance` #### `tie_db_readonly()` - **Description**: Opens the database in read-only mode. - **Type**: `public instance (Boolean)` #### `tie_db_writable()` - **Description**: Opens the database in writable mode. Callers must ensure `untie_db()` is called afterwards. - **Type**: `public instance (Boolean)` #### `untie_db()` - **Description**: Unties the database connection. - **Type**: `public instance` ``` -------------------------------- ### Initialize and Learn with Mail::SpamAssassin (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgLearner Demonstrates how to initialize Mail::SpamAssassin, parse an email, and then learn whether it is spam or not. This involves setting up the SpamAssassin object with rule and preference filenames, parsing a mail object, and calling the learn method with the mail, an ID, a spam status, and a forget flag. ```perl my $spamtest = new Mail::SpamAssassin ({ 'rules_filename' => '/etc/spamassassin.rules', 'userprefs_filename' => $ENV{HOME}.'/.spamassassin/user_prefs' }); my $mail = $spamtest->parse(); my $status = $spamtest->learn($mail,$id,$isspam,$forget); my $didlearn = $status->did_learn(); $status->finish(); ``` -------------------------------- ### Initialize SpamAssassin Learner Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin The `init_learner` method initializes the learning process for SpamAssassin. It accepts optional attribute-value pairs to configure behavior such as handling database untieing, forcing expiration, journaling learning data, and waiting for locks. ```perl $f->init_learner ( [ { opt => val, ... } ] ) ``` -------------------------------- ### Perl SpamAssassin Constructor Options Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin Illustrates how to instantiate the Mail::SpamAssassin object with various configuration options. These options allow customization of rule loading, preference files, language settings, and network test behavior. If no configuration is provided, default locations are searched. ```perl # Example with specific options my $spamtest = Mail::SpamAssassin->new({ rules_filename => '/path/to/rules', userprefs_filename => '/path/to/prefs', local_tests_only => 1 }); # Example using config_text to override file loading my $spamtest_config = Mail::SpamAssassin->new({ config_text => "score BAYES_99 10.0 EXPLAIN BayƩs spam probability is 99%", languages_filename => '/path/to/languages.cf' }); ``` -------------------------------- ### Mail::SpamAssassin Constructor Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin Initializes a new Mail::SpamAssassin object. Various options can be passed to configure rule loading, preference files, and testing behavior. ```APIDOC ## Mail::SpamAssassin Constructor ### Description Constructs a new "Mail::SpamAssassin" object. You may pass attribute-value pairs to configure its behavior, such as rule filenames, preference files, and testing options. ### Method `new` ### Parameters #### Constructor Options - **rules_filename** (string) - Optional - The filename to load spam-identifying rules from. - **site_rules_filename** (string) - Optional - The directory to load site-specific spam-identifying rules from. - **userprefs_filename** (string) - Optional - The filename to load preferences from. - **userstate_dir** (string) - Optional - The directory user state is stored in. - **config_text** (string) - Optional - The text of all rules and preferences. Overrides file-based settings. - **languages_filename** (string) - Optional - Path to the languages file, required if using `config_text` and language guessing. - **local_tests_only** (boolean) - Optional - If true (1), disables tests requiring internet access. Defaults to 0. - **dont_copy_prefs** (boolean) - Optional - If true (1), the user preferences file will not be created if it doesn't exist. Defaults to 0. - **save_pattern_hits** (boolean) - Optional - If true (1), patterns hit can be retrieved from the `Mail::SpamAssassin::PerMsgStatus` object for debugging. - **home_dir_for_helpers** (string) - Optional - Sets the HOME environment variable for helper applications like Razor, Pyzor, and DCC. - **username** (string) - Optional - Sets the current user's name. Defaults to the process's effective UID. ### Request Example ```perl my $spamtest = Mail::SpamAssassin->new({ rules_filename => '/path/to/rules.cf', local_tests_only => 1 }); ``` ### Response #### Success Response A new `Mail::SpamAssassin` object is returned. #### Response Example ```perl # Returns an object instance ``` ``` -------------------------------- ### Initialize SQL Bayesian Storage (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_BayesStore_SQL Creates a new instance of the Mail::SpamAssassin::BayesStore::SQL object. It requires an existing Mail::SpamAssassin::Bayes object and sets up the database connection and user for queries. ```perl public class (Mail::SpamAssassin::BayesStore::SQL) new (Mail::Spamassassin::Bayes $bayes) ``` -------------------------------- ### SpamAssassin Configuration: Rewrite Header Example Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf This snippet demonstrates how to rewrite the Subject header of emails identified as spam. It's a basic configuration directive used to flag spam messages. ```spamassassin rewrite_header Subject *****SPAM***** ``` -------------------------------- ### Loading and Checking Plugins in SpamAssassin Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Loads a SpamAssassin plugin and checks if it is successfully loaded. If loaded, subsequent rules are applied. ```spamassassin loadplugin MyPlugin plugintest.pm if plugin (MyPlugin) header MY_PLUGIN_FOO eval:check_for_foo() score MY_PLUGIN_FOO 0.1 endif ``` -------------------------------- ### Learn Single Message without Sync Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/sa-learn This command is used to learn from a single email message without immediately synchronizing the database. It defers the time-consuming database update process until the `--sync` option is explicitly used. This is useful for integrating with mail user agents for quick learning. ```bash sa-learn --ham --no-sync mailmessage ``` -------------------------------- ### Get Original Message Object from Spam Status (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Shows how to retrieve the original message object that was processed by SpamAssassin from the status object. This can be useful for further manipulation or inspection of the message. ```perl my $message_object = $status->get_message(); ``` -------------------------------- ### Get SpamAssassin Autolearn Status (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Explains how to retrieve the autolearning status of a message after it has been checked. The method returns a string indicating whether the message was auto-learned as ham, spam, or if learning was disabled or failed. ```perl my $autolearn_status = $status->get_autolearn_status (); ``` -------------------------------- ### SpamAssassin: Copy Configuration with Mail::SpamAssassin Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin Demonstrates how to use the copy_config method to backup and restore the configuration of a Mail::SpamAssassin object. This is useful for daemons that need to maintain a persistent object's configuration when switching between users. ```perl my $spamtest = Mail::SpamAssassin->new( ... ); my %conf_backup = (); $spamtest->copy_config(undef, %conf_backup) || die "error returned from copy_config!\n"; ... do stuff, perhaps modify the config, etc ... $spamtest->copy_config(\%conf_backup, undef) || die "error returned from copy_config!\n"; ``` -------------------------------- ### SpamAssassin Plugin Callback: check_post_dnsbl Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Plugin Called after DNSBL results have been harvested. This is an ideal place for plugins to harvest their own asynchronously started network lookups. It provides the 'Mail::SpamAssassin::PerMsgStatus' context object. ```perl $plugin->check_post_dnsbl ( { options ... } ) ``` -------------------------------- ### Get URI List (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Returns an array of all unique URIs found in the message, including both raw and slightly processed versions. It also populates $status->{uri_domain_count} and $status->{uri_list} with the domain count and the URI array, respectively. ```perl $status->get_uri_list () ``` -------------------------------- ### Default SQL Table Structure for Auto-Whitelist Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_SQLBasedAddrList Provides the default SQL `CREATE TABLE` statement for storing auto-whitelist information. This structure includes columns for username, email, IP, count, and total score, with a composite primary key. ```sql CREATE TABLE awl ( username VARCHAR NOT NULL, email VARCHAR NOT NULL, ip VARCHAR NOT NULL, count INT NOT NULL, totscore FLOAT NOT NULL, PRIMARY KEY (username, email, ip) ) ``` -------------------------------- ### Define Meta Rule (SpamAssassin) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Defines a boolean expression test based on the results of other tests. This allows for creating complex rules by combining simpler tests using logical operators like AND and OR. Sub-rules starting with '__' are ignored for scoring. ```spamassassin meta SYMBOLIC_TEST_NAME boolean expression ``` ```spamassassin meta META1 TEST1 && !(TEST2 || TEST3) ``` -------------------------------- ### Learn Spam and Ham with sa-learn Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/sa-learn This command trains SpamAssassin's Bayesian filter by processing directories of spam or ham emails. It requires the path to the respective folders. The tool analyzes messages and updates the internal database with 'interesting tokens'. ```bash sa-learn --spam /path/to/spam/folder sa-learn --ham /path/to/ham/folder ``` -------------------------------- ### Get Current Eval Rule Name (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Retrieves the name of the currently executing evaluation rule within SpamAssassin. Returns 'undef' if no rule is active. Useful for plugins to identify the current rule during eval test function calls. ```perl $name = $status->get_current_eval_rule_name() ``` -------------------------------- ### Load SpamAssassin Plugin Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Syntax for loading a SpamAssassin plugin module. It requires the Perl module name and optionally the path to the module file. If the path is omitted, Perl's default search path is used. ```perl loadplugin PluginModuleName [/path/to/module.pm] ``` -------------------------------- ### Get Message Header (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_PerMsgStatus Retrieves a specific message header, pseudo-header, or address. Supports raw decoding, extracting only the email address or display name, and accessing special pseudo-headers like 'ALL', 'ToCc', 'EnvelopeFrom', 'MESSAGEID', 'X-Spam-Relays-Untrusted', and 'X-Spam-Relays-Trusted'. ```perl $status->get (header_name [, default_value]) ``` -------------------------------- ### Custom SQL Query for User Scores Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Demonstrates how to define a custom SQL query to retrieve user scores and preferences. The query can utilize variables like _TABLE_, _USERNAME_, _MAILBOX_, and _DOMAIN_ which are substituted before execution. The query must be on a single line. ```sql SELECT preference, value FROM _TABLE_ WHERE username = _USERNAME_ OR username = '@GLOBAL' ORDER BY username ASC ``` ```sql SELECT preference, value FROM _TABLE_ WHERE username = _USERNAME_ OR username = '@GLOBAL' OR username = '@~'||_DOMAIN_ ORDER BY username ASC ``` ```sql SELECT preference, value FROM _TABLE_ WHERE username = _USERNAME_ OR username = '@GLOBAL' ORDER BY username DESC ``` -------------------------------- ### Retrieve Address Entry from SQL Database in Perl Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_SQLBasedAddrList Illustrates the get_addr_entry method, which takes an email address and optionally an IP address, performs a lookup in the SQL database, and returns the corresponding entry. If no entry is found, a blank entry hash is created. ```perl $entry = $addrlist->get_addr_entry ($addr, $origip); ``` -------------------------------- ### Load URIDNSBL Plugin and Configure Rule (SpamAssassin Config) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Plugin_URIDNSBL This snippet shows how to load the URIDNSBL plugin and configure a basic rule for checking URLs against a DNS blocklist zone. It specifies the rule name, the DNSBL zone to query, and the lookup type (TXT). A corresponding body-eval rule is also defined to trigger the check. ```spamassassin loadplugin Mail::SpamAssassin::Plugin::URIDNSBL uridnsbl URIBL_SBLXBL sbl-xbl.spamhaus.org. TXT body URIBL_SBLXBL eval:check_uridnsbl('URIBL_SBLXBL') describe URIBL_SBLXBL Contains a URL listed in the SBL/XBL blocklist ``` -------------------------------- ### Dump Database Tokens (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_BayesStore_SQL Iterates over all tokens in the database, calculates their probabilities, and prints them according to a specified template and regex. This method is useful for inspecting the token data. ```perl public instance () dump_db_toks (String $template, String $regex, Array @vars) ``` -------------------------------- ### Manage SQL Database Connection (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_BayesStore_SQL Ensures the SQL database connection is properly set up and working. These methods handle read-only and writable connections, initializing user bayes variables if necessary. 'untie_db' is noted as unused for the SQL implementation. ```perl public instance (Boolean) tie_db_readonly (); ``` ```perl public instance (Boolean) tie_db_writable () ``` ```perl public instance () untie_db () ``` -------------------------------- ### Specify Pyzor Path (SpamAssassin) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Specifies the exact path to the 'pyzor' client executable. This is useful when SpamAssassin cannot find 'pyzor' in the system's PATH, especially when running in Perl's taint mode. ```spamassassin pyzor_path STRING ``` -------------------------------- ### Mail::SpamAssassin::Message Public Methods Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Message Documentation for the public methods available in the Mail::SpamAssassin::Message module. ```APIDOC ## Mail::SpamAssassin::Message Public Methods ### Description Provides access to the public methods of the Mail::SpamAssassin::Message class. ### Methods - `new()`: Creates a Mail::SpamAssassin::Message object. - `_do_parse()`: Initiates a MIME part parse (generates a tree). - `find_parts()`: Searches the tree for specific MIME parts. - `get_pristine_header()`: Returns pristine headers of the message. - `get_mbox_separator()`: Returns the mbox separator found in the message. - `get_body()`: Returns an array of the pristine message body. - `get_pristine()`: Returns a scalar of the entire pristine message. - `get_pristine_body()`: Returns a scalar of the pristine message body. - `receive_date()`: Returns a time_t value with the received date of the current message. ### Parameters for `new()` #### Request Body - **message** (scalar | array_ref | glob) - Required - The email message content, which can be a scalar, an array reference of lines, or a file glob. - **parse_now** (boolean) - Optional - Specifies whether to create the MIME tree at object-creation time (default: false). ### Request Example for `new()` ```json { "message": "From: sender@example.com\nSubject: Test\n\nThis is the body.", "parse_now": true } ``` ### Response for `get_pristine_header()` #### Success Response (200) - **headers** (scalar | array) - The message headers. Returns a scalar in scalar context, or an array in array context. ``` -------------------------------- ### Mail::SpamAssassin::SQLBasedAddrList - Constructor Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_SQLBasedAddrList Creates a new instance of the SQLBasedAddrList factory and initializes the parent's PersistentAddrList new method. ```APIDOC ## new ### Description This method creates a new instance of the SQLBasedAddrList factory and calls the parent's (PersistentAddrList) new method. ### Method `public class (Mail::SpamAssassin::SQLBasedAddrList) new () ` ### Parameters None ### Request Example ``` my $factory = Mail::SpamAssassin::SQLBasedAddrList->new(); ``` ### Response #### Success Response (200) - **instance** (Mail::SpamAssassin::SQLBasedAddrList) - A new instance of the SQLBasedAddrList factory. #### Response Example ``` # Returns a blessed copy of the SQLBasedAddrList object ``` ``` -------------------------------- ### Initialize ArchiveIterator and Set Processing Functions (Perl) Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_ArchiveIterator Demonstrates how to create a new Mail::SpamAssassin::ArchiveIterator object with specific options and set the callback functions for message processing and result reporting. This is essential for defining the behavior of the iterator. ```perl my $iter = new Mail::SpamAssassin::ArchiveIterator({ 'opt_j' => 0, 'opt_n' => 1, 'opt_all' => 1, }); $iter->set_functions( &wanted, sub { } ); sub wanted { my($class, $filename, $recv_date, $msg_array) = @_; # Process message here } ``` -------------------------------- ### Specifying Minimum SpamAssassin Version Requirement Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin_Conf Declares a minimum required SpamAssassin version for the configuration file. Older or newer versions will issue a warning and ignore the file. ```spamassassin require_version n.nnnnnn ``` -------------------------------- ### Perl SpamAssassin Basic Usage Source: https://spamassassin.apache.org/full/3.0.x/dist/doc/Mail_SpamAssassin Demonstrates the fundamental workflow of using the Mail::SpamAssassin module to check an email for spam. It involves creating a SpamAssassin object, parsing a message, checking it for spam, and optionally rewriting the mail if it's identified as spam. The status and mail objects need to be finished after use. ```perl my $spamtest = Mail::SpamAssassin->new(); my $mail = $spamtest->parse( $message ); my $status = $spamtest->check( $mail ); if ($status->is_spam()) { $mail = $status->rewrite_mail(); } else { ... } ... $status->finish(); $mail->finish(); ```