Mail::...sassin(3pm)
π Mail::SpamAssassin β the Mail::...sassin(3pm) page, part 1 π
okay bestie, you found it: Mail::SpamAssassin, straight outta the User Contributed Perl Documentation section (3pm), and it is literally the spam detector AND markup engine. she's serving both looks. let's get into it π
β¨ NAME β¨
Mail::SpamAssassin β spam detector and markup engine. that's the whole vibe, no cap.
π¦ SYNOPSIS π¦
the way you use this thing is genuinely so simple, look:
my $spamtest = Mail::SpamAssassin->new();
my $mail = $spamtest->parse($message);
my $status = $spamtest->check($mail);
if ($status->is_spam()) {
$message = $status->rewrite_mail();
}
else {
...
}
...
$status->finish();
$mail->finish();
$spamtest->finish();
notice how she cleans up after herself at the end? finish() three times, in order, like a queen. π
πΈ DESCRIPTION πΈ
Mail::SpamAssassin is that girl whose entire job is identifying spam, and she does it with several methods: text analysis, internet-based realtime blocklists, statistical analysis, and internet-based hashing algorithms. multi-talented, we love to see it π
using her rule base, she runs a wide range of heuristic tests on mail headers and body text to identify "spam" (aka unsolicited bulk email, the technical name for the annoying stuff π). once something gets identified as spam, the mail can then be tagged as spam for later filtering β either by the user's own mail user agent application, or at the mail transfer agent. either way, sorted. β¨
and if you want a command-line filter tool instead of doing all this Perl by hand, try the spamassassin or the spamd/spamc tools she comes with. they're right there, bestie, go off π«Ά
π METHODS π
π
$t = Mail::SpamAssassin->new( { opt => val, ... } )
constructs a brand new Mail::SpamAssassin object, fresh out the box. you may pass a hash reference to the constructor, and it may contain these attribute-value pairs, and each one of them is lowkey iconic:
debugβ this is the debug options used to determine logging level. it exists so that sections of debug messages (called "facilities", cute) can be enabled or disabled. if this is a string, it's treated as a comma-delimited list of the debug facilities. if it's a hash reference, then the keys are treated as the list of debug facilities. and if it's an array reference, then the elements are treated as the list of debug facilities. flexible fr fr.
there are also two special cases: (1) if the special case of "info" is passed as a debug facility, then all informational messages are enabled; (2) if the special case of "all" is passed as a debug facility, then all debugging facilities are enabled. yes ma'am, chaos mode unlocked. π₯
rules_filenameβ the filename/directory to load spam-identifying rules from. (optional)site_rules_filenameβ the filename/directory to load site-specific spam-identifying rules from. (optional)userprefs_filenameβ the filename to load preferences from. (optional)userstate_dirβ the directory user state is stored in. (optional)config_tree_recurseβ set to 1 to recurse through directories when reading configuration files, instead of just reading a single level. (optional, default 0)config_textβ the text of all rules and preferences. if you prefer not to load the rules from files, read them in yourself and set this instead. as a result, this will override the settings forrules_filename,site_rules_filename, anduserprefs_filename. she said "I'll handle it myself" πpre_config_textβ similar toconfig_text, this text is placed before config_text to allow an override of config files.post_config_textβ similar toconfig_text, this text is placed after config_text to allow an override of config files.force_ipv4β if set to 1, DNS or other network tests will prefer IPv4 and not attempt to use IPv6. use this if the existing tests for IPv6 availability produce incorrect results or crashes. β οΈforce_ipv6β for symmetry with force_ipv4: if set to 1, DNS or other network tests will prefer IPv6 and not attempt to use IPv4. some plugins may disregard this setting and use whatever protocol family they are comfortable with. (rude of them, but okay π)require_rulesβ if set to 1,init()will die if no valid rules could be loaded. this is the default behaviour when called byspamassassinorspamd. dramatic, but valid πlanguages_filenameβ if you want to be able to use the language-guessing ruleUNWANTED_LANGUAGE_BODY, and are usingconfig_textinstead ofrules_filename,site_rules_filename, anduserprefs_filename, you will need to set this. it should be the path to the languages file normally found in the SpamAssassin rules directory.local_tests_onlyβ if set to 1, no tests that require internet access will be performed. (default: 0)need_tagsβ this option provides a way to avoid more expensive processing when it is known in advance that some information will not be needed by a caller.
a value of the option can either be a string (a comma-delimited list of tag names), or a reference to a list of individual tag names. a caller may provide the list in advance, specifying his intention to later collect the information through $pms->get_tag() calls. if a name of a tag starts with a 'NO' (case insensitive), it shows that a caller will not be interested in such tag, although there is no guarantee it would save any resources, nor that a tag value will be empty. currently no built-in tags start with 'NO'. a later entry overrides previous one, e.g. ASN,NOASN,ASN,TIMING,NOASN is equivalent to TIMING,NOASN.
for backward compatibility, all tags available as of version 3.2.4 will be available by default (unless disabled by NOtag), even if not requested through need_tags option. future versions may provide new tags conditionally available.
currently the only tag that needs to be explicitly requested is 'TIMING'. not requesting it can save a millisecond or two β it mostly serves to illustrate the usage of need_tags.
example:
need_tags => 'TIMING,noLANGUAGES,RELAYCOUNTRY,ASN,noASNCIDR', or:
need_tags => [qw(TIMING noLANGUAGES RELAYCOUNTRY ASN noASNCIDR)],
ignore_site_cf_filesβ if set to 1, any rule files found in thesite_rules_filenamedirectory will be ignored.*.prefiles (used for loading plugins) found in thesite_rules_filenamedirectory will still be used. (default: 0)dont_copy_prefsβ if set to 1, the user preferences file will not be created if it doesn't already exist. (default: 0)save_pattern_hitsβ if set to 1, the patterns hit can be retrieved from theMail::SpamAssassin::PerMsgStatusobject. used for debugging.home_dir_for_helpersβ if set, the HOME environment variable will be set to this value when using test applications that require their configuration data, such as Razor, Pyzor and DCC.usernameβ if set, theusernameattribute will use this as the current user's name. otherwise, the default is taken from the runtime environment (ie. this process' effective UID under UNIX).skip_prng_reseedingβ if skip_prng_reseeding is set to true, the SpamAssassin library will not callsrand()to reseed a pseudo-random number generator (PRNG). thesrand()Perl function should be called during initialization of each child process, soon after forking.
prior to version 3.4.0, calling srand() was handled by the SpamAssassin library.
this setting requires the caller to decide when to call srand(). this choice may be desired to preserve the entropy of a PRNG. the default value of skip_prng_reseeding is false to maintain backward compatibility.
this option should only be set by a caller if it calls srand() upon spawning child processes. unless you are certain you need it, leave this setting as false. no cap, do not freestyle this one. π
NOTE: the skip_prng_reseeding feature is implemented in spamd as of 3.4.0 which allows spamd to call srand() right after forking a child process.
if none of rules_filename, site_rules_filename, userprefs_filename, or config_text is set, the Mail::SpamAssassin module will search for the configuration files in the usual installed locations using the below variable definitions which can be passed in. she'll go find them herself, main character energy. π
PREFIXβ used as the root for certain directory paths such as:
'__prefix__/etc/mail/spamassassin'
'__prefix__/etc/spamassassin'
defaults to "@@PREFIX@@".
DEF_RULES_DIRβ location where the default rules are installed. defaults to"@@DEF_RULES_DIR@@".LOCAL_RULES_DIRβ location where the local site rules are installed. defaults to"@@LOCAL_RULES_DIR@@".LOCAL_STATE_DIRβ location of the local state directory, mainly used for installing updates viasa-updateand compiling rulesets to native code. defaults to"@@LOCAL_STATE_DIR@@".
π§ parse($message, $parse_now [, $suppl_attrib])
parse will return a Mail::SpamAssassin::Message object with just the headers parsed. when calling this function, there are two optional parameters that can be passed in: $message is either undef (which will use STDIN), a scalar β a string containing an entire message, a reference to such string, an array reference of the message with one line per array element, or either a file glob or an IO::File object which holds the entire contents of the message; and $parse_now, which specifies whether or not to create a MIME tree at parse time or later as necessary. so many options, she's so accommodating π
the $parse_now option, by default, is set to false (0). this allows SpamAssassin to not have to generate the tree of internal data nodes if the information is not going to be used. this is handy, for instance, when running spamassassin -d, which only needs the pristine header and body which is always parsed and stored by this function. efficient queen. β¨
the optional last argument $suppl_attrib provides a way for a caller to pass additional information about a message to SpamAssassin. it is either undef, or a ref to a hash where each key/value pair provides some supplementary attribute of the message, typically information that cannot be deduced from the message itself, or is hard to do so reliably, or would represent unnecessary work for SpamAssassin to obtain it. the argument will be stored to a Mail::SpamAssassin::Message object as 'suppl_attrib', thus made available to the rest of the code as well as to plugins. possible attributes are:
arc_signaturesβ it's an array ref of ARC signatures, bestie. If you hand this over, SpamAssassin is NOT gonna go verify ARC signatures itself β it'll just use yours, periodt. Perfect for when you already did the verification and don't wanna pay that overhead again, or when the message got truncated before it ever reached SpamAssassin. πbody_sizeβ the original message body size. Slide this in if the message was truncated before it got to SpamAssassin. It gets stashed as$msg->{pristine_body_length}and the eval testcheck_body_lengthuses it. β¨dkim_signaturesβ an array ref of DKIM signatures, and same energy as ARC up there: give it and SpamAssassin won't verify DKIM itself, it'll trust yours. Useful when the caller already did the verification and wants to skip the overhead, or the message was truncated before being passed over. π¦master_deadlineβ this one caps how much time SpamAssassin is allowed to spend before it returns a result. The value is a floating point number = seconds since the epoch. Peep the"time_limit"config option in"MISCELLANEOUS OPTIONS"in Mail::SpamAssassin::Conf for the deets. β°mimepart_digestsβ an array ref of digest codes (like SHA1) for each MIME part. Caller might wanna provide this if the message got truncated before being passed to SpamAssassin.originatingβ a boolean. Is this message from the local system, or from an authenticated roaming user? If you set it true, SpamAssassin treats all relays as trusted. πreturn_pathβ sets the Envelope From address used by the"EnvelopeFrom"pseudo-header and by rules like"welcomelist_from"and SPF checking. Don't provide it and SpamAssassin will try to figure out the Envelope From from the message headers. If you already know it, drop it here to avoid any ambiguity, and if it's wrapped in angle brackets, those get stripped. πrule_hitsβ an array ref of rule hits. Each element is a hash ref with these keys:'rule','area','score','defscore','value','ruletype','tflags','descr'. This one's for when you wanna add extra hits to the message that SpamAssassin's own rules never defined β like hits from external sources, virus scanners, other spam filters, that whole vibe. π₯
Example:
$msg = $sa->parse($message,0, {
body_size => 24284293,
master_deadline => time() + 60,
return_path => 'foo@example.com',
originating => 0,
rule_hits => {
rule => '__TRUNCATED',
score => -0.1,
area => 'RAW: ',
tflags => 'nice',
descr => "Message size truncated to 10485760 B" }
});
And if you pass other attributes? SpamAssassin will silently ignore them, but they'll still be chilling there for plugins inside "$msg->{suppl_attrib}". π
$status = $f->check ($mail)
Checks a mail β wrapped up all cozy in a Mail::SpamAssassin::Message object β to see if it's spam or not.
Returns a Mail::SpamAssassin::PerMsgStatus object, which you can use to test or manipulate the mail message. β¨
Heads up bestie: theMail::SpamAssassinobject can be reused for more messages without messing up this check β in OO speak, theMail::SpamAssassinobject is a "factory". BUT if you do reuse it, you gotta call the finish() method on the status objects when you're done with them. Do not skip that. π€
$status = $f->check_message_text ($mailtext)
Same thing, but the mail is a plain string $mailtext. Does it spam? Find out.
Otherwise identical to check() above. π«Ά
$status = $f->learn ($mail, $id, $isspam, $forget)
Learn from a mail, wrapped in a Mail::SpamAssassin::Message object.
If $isspam is set, the mail is assumed to be spam β otherwise it gets learnt as non-spam.
If $forget is set, the mail's attributes get removed from both the non-spam and spam learning databases.
$id is an optional message-identification string, used internally to tag the message. If it's undef, the Message-Id of the message gets used instead. It should be unique to that message, fr fr.
Returns a Mail::SpamAssassin::PerMsgLearner object you can use to manipulate the learning process for each mail. π§
Also on the factory tip: the Mail::SpamAssassin object can be reused for further messages without affecting this check. But same rule applies β call the finish() method on the learner objects when you're done. No cap.
learn() and check() can both run off the same factory. Just remember init_learner() must be called before using this method. β
$f->init_learner ( [ { opt => val, ... } ] )
Initialise learning. You can pass these attribute-value pairs: π«
caller_will_untieβ whether the code calling this method will handle untie'ing from the Bayes databases itself (by calling finish_learner()). Optional, default0.force_expireβ should an expiration run be forced to happen immediately? Optional, default0.learn_to_journalβ should learning data be written to the journal instead of straight to the databases? Optional, default0.wait_for_lockβ wait a long time for locks to complete, or nah? Optional, default0.opportunistic_expire_check_onlyβ during the opportunistic journal sync and expire check, don't actually do the expire, just report back whether or not it should occur. Optional, default0.no_relearnβ if you're doing a learn operation and the message was already learned as the opposite type, don't re-learn it.
$f->rebuild_learner_caches ({ opt => val })
Rebuild any cache databases β should be called after the learning process. Options include "verbose", which will output diagnostics to "stdout" if set to 1. π οΈ
$f->finish_learner ()
Finish learning. That's it, that's the method. π
$f->dump_bayes_db()
Dump the contents of the Bayes DB. ποΈ
$f->signal_user_changed ( [ { opt => val, ... } ] )
Signals that the current user has changed β possibly via "setuid" β which means SpamAssassin should close any per-user databases it has open and reopen the ones that fit the new user. π
Note this should be called after reading any per-user configuration, because that data may override some paths opened in this method. Iykyk.
You may pass these attribute-value pairs:
usernameβ the username of the user. Gets used for the"username"attribute.user_dirβ a directory to use as a 'home directory' for the current user's data, overriding the system default. This directory must be readable and writable by the process. Note that the resulting"userstate_dir"will be the.spamassassinsubdirectory of this dir.userstate_dirβ a directory to use as the directory for the current user's data, overriding the system default. Must be readable and writable by the process. The default is"user_dir/.spamassassin".
$f->report_as_spam ($mail, $options)
Report a mail β wrapped in a Mail::SpamAssassin::Message object β as human-verified spam. This submits the mail message to live, collaborative, spam-blocker databases so other users can block this message. π¨
It will also submit the mail to SpamAssassin's Bayesian learner.
Options is an optional reference to a hash of options. Currently these can be:
dont_report_to_dccβ inhibits reporting of the spam to DCC.dont_report_to_pyzorβ inhibits reporting of the spam to Pyzor.dont_report_to_razorβ inhibits reporting of the spam to Razor.dont_report_to_spamcopβ inhibits reporting of the spam to SpamCop.
$f->revoke_as_spam ($mail, $options)
Revoke a mail β wrapped in a Mail::SpamAssassin::Message object β as human-verified ham (non-spam, bestie, it's the good stuff). This revokes the mail message from live, collaborative, spam-blocker databases, allowing other users to block this message. π
It will also submit the mail to SpamAssassin's Bayesian learner as nonspam.
Options is an optional reference to a hash of options. Currently these can be:
dont_report_to_razorβ inhibits revoking of the spam to Razor.
$f->add_address_to_welcomelist ($addr, $cli_p)
Previously add_address_to_whitelist, which will work interchangeably until 4.1. π
Given a string containing an email address, add it to the automatic welcomelist database.
If $cli_p is set then the underlying plugin may give visual feedback on additions/failures. β¨
$f->add_all_addresses_to_welcomelist ($mail, $cli_p)
Previously add_all_addresses_to_whitelist, which will work interchangeably until 4.1. π
Given a mail message, find as many addresses as you can in the usual headers (To, Cc, From etc.) and the message body, and add them to the automatic welcomelist database. π
If $cli_p is set then the underlying plugin may give visual feedback on additions/failures.
$f->remove_address_from_welcomelist ($addr, $cli_p)
Previously remove_address_from_whitelist, which will work interchangeably until 4.1. π
Given a string containing an email address, remove it from the automatic welcomelist database. Bye babe. π
If $cli_p is set then the underlying plugin may give visual feedback on additions/failures.
π«Ά $f->remove_all_addresses_from_welcomelist ($mail, $cli_p)
bestie fyi: this one used to be called remove_all_addresses_from_whitelist, and that old name keeps working interchangeably until 4.1. π
You hand it a mail message and it goes on a little scavenger hunt for as many addresses as it can find β the usual headers (To, Cc, From, etc.) and the message body β then it takes those addresses and removes them from the automatic welcomelist database. π§Ήβ¨
If $cli_p is set, the underlying plugin may give visual feedback on additions/failures.
π $f->add_address_to_blocklist ($addr, $cli_p)
Formerly known as add_address_to_blacklist, which still works interchangeably until 4.1.
Give it a string containing an email address and it drops it into the automatic welcomelist database with a high score, which effectively blocklists them. yes, the welcomelist database, with a high score, that's the bit β read it twice if you need to, it's giving sneaky. π
If $cli_p is set, the underlying plugin may give visual feedback on additions/failures.
π₯ $f->add_all_addresses_to_blocklist ($mail, $cli_p)
Third one in the glow-up era: previously add_all_addresses_to_blacklist, and that name works interchangeably until 4.1.
Hand it a whole mail message and it finds the addresses in the From headers and adds them to the automatic welcomelist database with a high score, effectively blocklisting them.
β οΈ note thatToandCcaddresses are not used. onlyFrom. don't argue with it, it's got main character energy and a very specific job. π
If $cli_p is set, the underlying plugin may give visual feedback on additions/failures.
π§ $text = $f->remove_spamassassin_markup ($mail)
Gives you back the text of the message, with any SpamAssassin-added text stripped out β that means the report, or X-Spam-Status headers, all of it, gone. β¨
Note that the $mail object is not modified. it's giving "I made you a copy," not "I redecorated your room."
β οΈ Warning: if the input message in $mail contains a mixture of CR-LF (Windows-style) and LF (UNIX-style) line endings, it will be "canonicalized" to use one or the other consistently throughout. so yeah, your line endings are getting a makeover whether you asked or not π
πΈ $f->read_scoreonly_config ($filename)
Reads a configuration file and parses user preferences out of it. π
Those user preferences are exactly as defined in the Mail::SpamAssassin::Conf manual page. In other words? They include scoring options, scores, welcomelists and blocklists, and so on β but they do not include rule definitions, privileged settings, etc., unless allow_user_rules is enabled. And they never include the administrator settings. periodt. π
π¦ $f->load_scoreonly_sql ($username)
Reads configuration parameters from an SQL database and parses scores from it.
This will only take effect if the perl DBI module is installed, and the configuration parameters user_scores_dsn, user_scores_sql_username, and user_scores_sql_password are set correctly. no DBI, no wrong params, no vibes, no scores. π
The username in $username will also be used for the username attribute of the Mail::SpamAssassin object.
π $f->load_scoreonly_ldap ($username)
Same energy, different backend: reads configuration parameters from an LDAP server and parses scores from it.
This will only take effect if the perl Net::LDAP and URI modules are installed, and the configuration parameters user_scores_dsn, user_scores_ldap_username, and user_scores_ldap_password are set correctly. π
The username in $username will also be used for the username attribute of the Mail::SpamAssassin object.
π $f->set_persistent_address_list_factory ($factoryobj)
Sets the persistent address list factory β the thing used to create objects for the automatic welcomelist algorithm's persistent-storage back-end. ποΈ
See Mail::SpamAssassin::PersistentAddrList for the API these factory objects must implement, and the API the objects they produce must implement. iykyk.
β‘ $f->compile_now ($use_user_prefs, $keep_userstate)
Compiles all patterns, loads all configuration files, and loads all possibly-required Perl modules. all of them. right now. π
Normally, Mail::SpamAssassin uses lazy evaluation where possible, but if you plan to fork() or start a new perl interpreter thread to process a message, that's suboptimal β because each process/thread would have to perform these actions itself. π
Call this function in the master thread or process to perform the actions straight away, so that the sub-processes will not have to. do it early, bestie, your future threads will thank you.
If $use_user_prefs is 0, this will initialise the SpamAssassin configuration without reading the per-user configuration file, and it will assume that you will call read_scoreonly_config at a later point.
If $keep_userstate is true, compile_now() will revert any configuration options which have a default with __userstate__ in it post-init(), and then re-change the option before returning. This lets you change $ENV{'HOME'} to a temp directory, have compile_now() create any files there as necessary without disturbing the actual files as changed by a configuration option. By default, this is disabled.
π $f->debug_diagnostics ()
Outputs some diagnostic information, useful for debugging SpamAssassin problems. it's giving "tell me everything, I'm not judging." π
π§ $failed = $f->lint_rules ()
Syntax-checks the current set of rules. Returns the number of syntax errors discovered, or 0 if the configuration is valid. zero errors? slay. anything else? time to go fix it. π
π«§ $f->finish()
Destroys this object, so that it will be garbage-collected once it goes out of scope.
The object will no longer be usable after this method is called. it's not "on a break," it's gone. π
ποΈ $fullpath = $f->find_rule_support_file ($filename)
Finds a rule-support file β such as languages or triplets.txt β in the system-wide rules directory, and returns its full path if it exists, or undef if it doesn't exist. simple, honest, no drama. πΈ
(This API was added in SpamAssassin 3.1.1.)
π $f->create_default_prefs ($filename, $username [ , $userdir ] )
Copies the default preferences file into the home directory for later use and modification β but only if it does not already exist and dont_copy_prefs is not set. β¨
π $f->copy_config ( [ $source ], [ $dest ] )
Used for daemons to keep a persistent Mail::SpamAssassin object's configuration correct if switching between users. π
Pass an associative array reference as either $source or $dest, and set the other to 'undef' so that the object will use its current configuration. i.e.:
# create object w/ configuration
my $spamtest = Mail::SpamAssassin->new( ... );
# backup configuration to %conf_backup
my %conf_backup;
$spamtest->copy_config(undef, \%conf_backup) ||
die "config: error returned from copy_config!\n";
... do stuff, perhaps modify the config, etc ...
# reset the configuration back to the original
$spamtest->copy_config(\%conf_backup, undef) ||
die "config: error returned from copy_config!\n";
Note that the contents of the associative arrays should be considered opaque by calling code. don't peek inside, don't redecorate, just pass them around. π«Ά
π @plugins = $f->get_loaded_plugins_list ( )
Returns the list of plugins currently loaded by this SpamAssassin object's configuration; each entry in the list is an object of type Mail::SpamAssassin::Plugin. a whole little squad. π
(This API was added in SpamAssassin 3.2.0.)
β¨ PREREQUISITES β¨
You're gonna need these two, no exceptions:
HTML::ParserSys::Syslog
π MORE DOCUMENTATION π
Also check out https://spamassassin.apache.org/ and https://wiki.apache.org/spamassassin/ for more information. (yes bestie, go read the wiki, it's lowkey iconic.)
π SEE ALSO π
π BUGS π
See https://bz.apache.org/SpamAssassin/
π AUTHORS π
The SpamAssassin(tm) Project <https://spamassassin.apache.org/>
Β©οΈ COPYRIGHT Β©οΈ
SpamAssassin is distributed under the Apache License, Version 2.0, as described in the file LICENSE included with the distribution.
π«Ά AVAILABILITY π«Ά
The latest version of this library is likely to be available from CPAN as well as:
https://spamassassin.apache.org/
and that's the whole page, bestie π this was perl v5.40.1, dated 2026-07-23, and you just read the entire thing β not me being proud of you or anything ππ go forth and filter that mail, ok bye πβ¨π¦
π¦ where this page comes from
- ubuntu stonking: spamassassin 4.0.2+svn1935691-1build1
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms