1Mail::SpamAssassin(3) User Contributed Perl DocumentationMail::SpamAssassin(3)
2
3
4

NAME

6       Mail::SpamAssassin - Spam detector and markup engine
7

SYNOPSIS

9         my $spamtest = Mail::SpamAssassin->new();
10         my $mail = $spamtest->parse($message);
11         my $status = $spamtest->check($mail);
12
13         if ($status->is_spam()) {
14           $message = $status->rewrite_mail();
15         }
16         else {
17           ...
18         }
19         ...
20
21         $status->finish();
22         $mail->finish();
23         $spamtest->finish();
24

DESCRIPTION

26       Mail::SpamAssassin is a module to identify spam using several methods
27       including text analysis, internet-based realtime blocklists,
28       statistical analysis, and internet-based hashing algorithms.
29
30       Using its rule base, it uses a wide range of heuristic tests on mail
31       headers and body text to identify "spam", also known as unsolicited
32       bulk email.  Once identified as spam, the mail can then be tagged as
33       spam for later filtering using the user's own mail user agent
34       application or at the mail transfer agent.
35
36       If you wish to use a command-line filter tool, try the "spamassassin"
37       or the "spamd"/"spamc" tools provided.
38

METHODS

40       $t = Mail::SpamAssassin->new( { opt => val, ... } )
41           Constructs a new "Mail::SpamAssassin" object.  You may pass a hash
42           reference to the constructor which may contain the following
43           attribute- value pairs.
44
45           debug
46               This is the debug options used to determine logging level.  It
47               exists to allow sections of debug messages (called
48               "facilities") to be enabled or disabled.  If this is a string,
49               it is treated as a comma-delimited list of the debug
50               facilities.  If it's a hash reference, then the keys are
51               treated as the list of debug facilities and if it's a array
52               reference, then the elements are treated as the list of debug
53               facilities.
54
55               There are also two special cases: (1) if the special case of
56               "info" is passed as a debug facility, then all informational
57               messages are enabled; (2) if the special case of "all" is
58               passed as a debug facility, then all debugging facilities are
59               enabled.
60
61           rules_filename
62               The filename/directory to load spam-identifying rules from.
63               (optional)
64
65           site_rules_filename
66               The filename/directory to load site-specific spam-identifying
67               rules from.  (optional)
68
69           userprefs_filename
70               The filename to load preferences from. (optional)
71
72           userstate_dir
73               The directory user state is stored in. (optional)
74
75           config_tree_recurse
76               Set to 1 to recurse through directories when reading
77               configuration files, instead of just reading a single level.
78               (optional, default 0)
79
80           config_text
81               The text of all rules and preferences.  If you prefer not to
82               load the rules from files, read them in yourself and set this
83               instead.  As a result, this will override the settings for
84               "rules_filename", "site_rules_filename", and
85               "userprefs_filename".
86
87           pre_config_text
88               Similar to "config_text", this text is placed before
89               config_text to allow an override of config files.
90
91           post_config_text
92               Similar to "config_text", this text is placed after config_text
93               to allow an override of config files.
94
95           force_ipv4
96               If set to 1, DNS or other network tests will prefer IPv4 and
97               not attempt to use IPv6. Use if the existing tests for IPv6
98               availability produce incorrect results or crashes.
99
100           force_ipv6
101               For symmetry with force_ipv4: if set to 1, DNS or other network
102               tests will prefer IPv6 and not attempt to use IPv4. Some
103               plugins may disregard this setting and use whatever protocol
104               family they are comfortable with.
105
106           require_rules
107               If set to 1, init() will die if no valid rules could be loaded.
108               This is the default behaviour when called by "spamassassin" or
109               "spamd".
110
111           languages_filename
112               If you want to be able to use the language-guessing rule
113               "UNWANTED_LANGUAGE_BODY", and are using "config_text" instead
114               of "rules_filename", "site_rules_filename", and
115               "userprefs_filename", you will need to set this.  It should be
116               the path to the languages file normally found in the
117               SpamAssassin rules directory.
118
119           local_tests_only
120               If set to 1, no tests that require internet access will be
121               performed. (default: 0)
122
123           need_tags
124               The option provides a way to avoid more expensive processing
125               when it is known in advance that some information will not be
126               needed by a caller.
127
128               A value of the option can either be a string (a comma-delimited
129               list of tag names), or a reference to a list of individual tag
130               names. A caller may provide the list in advance, specifying his
131               intention to later collect the information through
132               $pms->get_tag() calls. If a name of a tag starts with a 'NO'
133               (case insensitive), it shows that a caller will not be
134               interested in such tag, although there is no guarantee it would
135               save any resources, nor that a tag value will be empty.
136               Currently no built-in tags start with 'NO'. A later entry
137               overrides previous one, e.g. ASN,NOASN,ASN,TIMING,NOASN is
138               equivalent to TIMING,NOASN.
139
140               For backward compatibility, all tags available as of version
141               3.2.4 will be available by default (unless disabled by NOtag),
142               even if not requested through need_tags option. Future versions
143               may provide new tags conditionally available.
144
145               Currently the only tag that needs to be explicitly requested is
146               'TIMING'.  Not requesting it can save a millisecond or two - it
147               mostly serves to illustrate the usage of need_tags.
148
149               Example:
150                 need_tags =>
151               'TIMING,noLANGUAGES,RELAYCOUNTRY,ASN,noASNCIDR', or:
152                 need_tags => [qw(TIMING noLANGUAGES RELAYCOUNTRY ASN
153               noASNCIDR)],
154
155           ignore_site_cf_files
156               If set to 1, any rule files found in the "site_rules_filename"
157               directory will be ignored.  *.pre files (used for loading
158               plugins) found in the "site_rules_filename" directory will
159               still be used. (default: 0)
160
161           dont_copy_prefs
162               If set to 1, the user preferences file will not be created if
163               it doesn't already exist. (default: 0)
164
165           save_pattern_hits
166               If set to 1, the patterns hit can be retrieved from the
167               "Mail::SpamAssassin::PerMsgStatus" object.  Used for debugging.
168
169           home_dir_for_helpers
170               If set, the HOME environment variable will be set to this value
171               when using test applications that require their configuration
172               data, such as Razor, Pyzor and DCC.
173
174           username
175               If set, the "username" attribute will use this as the current
176               user's name.  Otherwise, the default is taken from the runtime
177               environment (ie. this process' effective UID under UNIX).
178
179           skip_prng_reseeding
180               If skip_prng_reseeding is set to true, the SpamAssassin library
181               will not call srand() to reseed a pseudo-random number
182               generator (PRNG). The srand() Perl function should be called
183               during initialization of each child process, soon after
184               forking.
185
186               Prior to version 3.4.0, calling srand() was handled by the
187               SpamAssassin library.
188
189               This setting requires the caller to decide when to call
190               srand().  This choice may be desired to preserve the entropy of
191               a PRNG.  The default value of skip_prng_reseeding is false to
192               maintain backward compatibility.
193
194               This option should only be set by a caller if it calls srand()
195               upon spawning child processes.  Unless you are certain you need
196               it, leave this setting as false.
197
198               NOTE: The skip_prng_reseeding feature is implemented in spamd
199               as of 3.4.0 which allows spamd to call srand() right after
200               forking a child process.
201
202           If none of "rules_filename", "site_rules_filename",
203           "userprefs_filename", or "config_text" is set, the
204           "Mail::SpamAssassin" module will search for the configuration files
205           in the usual installed locations using the below variable
206           definitions which can be passed in.
207
208           PREFIX
209               Used as the root for certain directory paths such as:
210
211                 '__prefix__/etc/mail/spamassassin'
212                 '__prefix__/etc/spamassassin'
213
214               Defaults to "@@PREFIX@@".
215
216           DEF_RULES_DIR
217               Location where the default rules are installed.  Defaults to
218               "@@DEF_RULES_DIR@@".
219
220           LOCAL_RULES_DIR
221               Location where the local site rules are installed.  Defaults to
222               "@@LOCAL_RULES_DIR@@".
223
224           LOCAL_STATE_DIR
225               Location of the local state directory, mainly used for
226               installing updates via "sa-update" and compiling rulesets to
227               native code.  Defaults to "@@LOCAL_STATE_DIR@@".
228
229       parse($message, $parse_now [, $suppl_attrib])
230           Parse will return a Mail::SpamAssassin::Message object with just
231           the headers parsed.  When calling this function, there are two
232           optional parameters that can be passed in: $message is either undef
233           (which will use STDIN), a scalar - a string containing an entire
234           message, a reference to such string, an array reference of the
235           message with one line per array element, or either a file glob or
236           an IO::File object which holds the entire contents of the message;
237           and $parse_now, which specifies whether or not to create a MIME
238           tree at parse time or later as necessary.
239
240           The $parse_now option, by default, is set to false (0).  This
241           allows SpamAssassin to not have to generate the tree of internal
242           data nodes if the information is not going to be used.  This is
243           handy, for instance, when running "spamassassin -d", which only
244           needs the pristine header and body which is always parsed and
245           stored by this function.
246
247           The optional last argument $suppl_attrib provides a way for a
248           caller to pass additional information about a message to
249           SpamAssassin. It is either undef, or a ref to a hash where each
250           key/value pair provides some supplementary attribute of the
251           message, typically information that cannot be deduced from the
252           message itself, or is hard to do so reliably, or would represent
253           unnecessary work for SpamAssassin to obtain it. The argument will
254           be stored to a Mail::SpamAssassin::Message object as
255           'suppl_attrib', thus made available to the rest of the code as well
256           as to plugins. The exact list of attributes will evolve through
257           time, any unknown attribute should be ignored. Possible examples
258           are: SMTP envelope information, a flag indicating that a message as
259           supplied by a caller was truncated due to size limit, an already
260           verified list of DKIM signature objects, or perhaps a list of rule
261           hits predetermined by a caller, which makes another possible way
262           for a caller to provide meta information (instead of having to
263           insert made-up header fields in order to pass information), or
264           maybe just plain rule hits.
265
266           For more information, please see the "Mail::SpamAssassin::Message"
267           and "Mail::SpamAssassin::Message::Node" POD.
268
269       $status = $f->check ($mail)
270           Check a mail, encapsulated in a "Mail::SpamAssassin::Message"
271           object, to determine if it is spam or not.
272
273           Returns a "Mail::SpamAssassin::PerMsgStatus" object which can be
274           used to test or manipulate the mail message.
275
276           Note that the "Mail::SpamAssassin" object can be re-used for
277           further messages without affecting this check; in OO terminology,
278           the "Mail::SpamAssassin" object is a "factory".   However, if you
279           do this, be sure to call the finish() method on the status objects
280           when you're done with them.
281
282       $status = $f->check_message_text ($mailtext)
283           Check a mail, encapsulated in a plain string $mailtext, to
284           determine if it is spam or not.
285
286           Otherwise identical to check() above.
287
288       $status = $f->learn ($mail, $id, $isspam, $forget)
289           Learn from a mail, encapsulated in a "Mail::SpamAssassin::Message"
290           object.
291
292           If $isspam is set, the mail is assumed to be spam, otherwise it
293           will be learnt as non-spam.
294
295           If $forget is set, the attributes of the mail will be removed from
296           both the non-spam and spam learning databases.
297
298           $id is an optional message-identification string, used internally
299           to tag the message.  If it is "undef", the Message-Id of the
300           message will be used.  It should be unique to that message.
301
302           Returns a "Mail::SpamAssassin::PerMsgLearner" object which can be
303           used to manipulate the learning process for each mail.
304
305           Note that the "Mail::SpamAssassin" object can be re-used for
306           further messages without affecting this check; in OO terminology,
307           the "Mail::SpamAssassin" object is a "factory".   However, if you
308           do this, be sure to call the finish() method on the learner objects
309           when you're done with them.
310
311           learn() and check() can be run using the same factory.
312           init_learner() must be called before using this method.
313
314       $f->init_learner ( [ { opt => val, ... } ] )
315           Initialise learning.  You may pass the following attribute-value
316           pairs to this method.
317
318           caller_will_untie
319               Whether or not the code calling this method will take care of
320               untie'ing from the Bayes databases (by calling
321               finish_learner()) (optional, default 0).
322
323           force_expire
324               Should an expiration run be forced to occur immediately?
325               (optional, default 0).
326
327           learn_to_journal
328               Should learning data be written to the journal, instead of
329               directly to the databases? (optional, default 0).
330
331           wait_for_lock
332               Whether or not to wait a long time for locks to complete
333               (optional, default 0).
334
335           opportunistic_expire_check_only
336               During the opportunistic journal sync and expire check, don't
337               actually do the expire but report back whether or not it should
338               occur (optional, default 0).
339
340           no_relearn
341               If doing a learn operation, and the message has already been
342               learned as the opposite type, don't re-learn the message.
343
344       $f->rebuild_learner_caches ({ opt => val })
345           Rebuild any cache databases; should be called after the learning
346           process.  Options include: "verbose", which will output diagnostics
347           to "stdout" if set to 1.
348
349       $f->finish_learner ()
350           Finish learning.
351
352       $f->dump_bayes_db()
353           Dump the contents of the Bayes DB
354
355       $f->signal_user_changed ( [ { opt => val, ... } ] )
356           Signals that the current user has changed (possibly using
357           "setuid"), meaning that SpamAssassin should close any per-user
358           databases it has open, and re-open using ones appropriate for the
359           new user.
360
361           Note that this should be called after reading any per-user
362           configuration, as that data may override some paths opened in this
363           method.  You may pass the following attribute-value pairs:
364
365           username
366               The username of the user.  This will be used for the "username"
367               attribute.
368
369           user_dir
370               A directory to use as a 'home directory' for the current user's
371               data, overriding the system default.  This directory must be
372               readable and writable by the process.  Note that the resulting
373               "userstate_dir" will be the ".spamassassin" subdirectory of
374               this dir.
375
376           userstate_dir
377               A directory to use as a directory for the current user's data,
378               overriding the system default.  This directory must be readable
379               and writable by the process.  The default is
380               "user_dir/.spamassassin".
381
382       $f->report_as_spam ($mail, $options)
383           Report a mail, encapsulated in a "Mail::SpamAssassin::Message"
384           object, as human-verified spam.  This will submit the mail message
385           to live, collaborative, spam-blocker databases, allowing other
386           users to block this message.
387
388           It will also submit the mail to SpamAssassin's Bayesian learner.
389
390           Options is an optional reference to a hash of options.  Currently
391           these can be:
392
393           dont_report_to_dcc
394               Inhibits reporting of the spam to DCC.
395
396           dont_report_to_pyzor
397               Inhibits reporting of the spam to Pyzor.
398
399           dont_report_to_razor
400               Inhibits reporting of the spam to Razor.
401
402           dont_report_to_spamcop
403               Inhibits reporting of the spam to SpamCop.
404
405       $f->revoke_as_spam ($mail, $options)
406           Revoke a mail, encapsulated in a "Mail::SpamAssassin::Message"
407           object, as human-verified ham (non-spam).  This will revoke the
408           mail message from live, collaborative, spam-blocker databases,
409           allowing other users to block this message.
410
411           It will also submit the mail to SpamAssassin's Bayesian learner as
412           nonspam.
413
414           Options is an optional reference to a hash of options.  Currently
415           these can be:
416
417           dont_report_to_razor
418               Inhibits revoking of the spam to Razor.
419
420       $f->add_address_to_welcomelist ($addr, $cli_p)
421           Previously add_address_to_whitelist which will work interchangeably
422           until 4.1.
423
424           Given a string containing an email address, add it to the automatic
425           welcomelist database.
426
427           If $cli_p is set then underlying plugin may give visual feedback on
428           additions/failures.
429
430       $f->add_all_addresses_to_welcomelist ($mail, $cli_p)
431           Previously add_all_addresses_to_whitelist which will work
432           interchangeably until 4.1.
433
434           Given a mail message, find as many addresses in the usual headers
435           (To, Cc, From etc.), and the message body, and add them to the
436           automatic welcomelist database.
437
438           If $cli_p is set then underlying plugin may give visual feedback on
439           additions/failures.
440
441       $f->remove_address_from_welcomelist ($addr, $cli_p)
442           Previously remove_address_from_whitelist which will work
443           interchangeably until 4.1.
444
445           Given a string containing an email address, remove it from the
446           automatic welcomelist database.
447
448           If $cli_p is set then underlying plugin may give visual feedback on
449           additions/failures.
450
451       $f->remove_all_addresses_from_welcomelist ($mail, $cli_p)
452           Previously remove_all_addresses_from_whitelist which will work
453           interchangeably until 4.1.
454
455           Given a mail message, find as many addresses in the usual headers
456           (To, Cc, From etc.), and the message body, and remove them from the
457           automatic welcomelist database.
458
459           If $cli_p is set then underlying plugin may give visual feedback on
460           additions/failures.
461
462       $f->add_address_to_blocklist ($addr, $cli_p)
463           Previously add_address_to_blacklist which will work interchangeably
464           until 4.1.
465
466           Given a string containing an email address, add it to the automatic
467           welcomelist database with a high score, effectively blocklisting
468           them.
469
470           If $cli_p is set then underlying plugin may give visual feedback on
471           additions/failures.
472
473       $f->add_all_addresses_to_blocklist ($mail, $cli_p)
474           Previously add_all_addresses_to_blacklist which will work
475           interchangeably until 4.1.
476
477           Given a mail message, find addresses in the From headers and add
478           them to the automatic welcomelist database with a high score,
479           effectively blocklisting them.
480
481           Note that To and Cc addresses are not used.
482
483           If $cli_p is set then underlying plugin may give visual feedback on
484           additions/failures.
485
486       $text = $f->remove_spamassassin_markup ($mail)
487           Returns the text of the message, with any SpamAssassin-added text
488           (such as the report, or X-Spam-Status headers) stripped.
489
490           Note that the $mail object is not modified.
491
492           Warning: if the input message in $mail contains a mixture of CR-LF
493           (Windows-style) and LF (UNIX-style) line endings, it will be
494           "canonicalized" to use one or the other consistently throughout.
495
496       $f->read_scoreonly_config ($filename)
497           Read a configuration file and parse user preferences from it.
498
499           User preferences are as defined in the "Mail::SpamAssassin::Conf"
500           manual page.  In other words, they include scoring options, scores,
501           welcomelists and blocklists, and so on, but do not include rule
502           definitions, privileged settings, etc. unless "allow_user_rules" is
503           enabled; and they never include the administrator settings.
504
505       $f->load_scoreonly_sql ($username)
506           Read configuration parameters from SQL database and parse scores
507           from it.  This will only take effect if the perl "DBI" module is
508           installed, and the configuration parameters "user_scores_dsn",
509           "user_scores_sql_username", and "user_scores_sql_password" are set
510           correctly.
511
512           The username in $username will also be used for the "username"
513           attribute of the Mail::SpamAssassin object.
514
515       $f->load_scoreonly_ldap ($username)
516           Read configuration parameters from an LDAP server and parse scores
517           from it.  This will only take effect if the perl "Net::LDAP" and
518           "URI" modules are installed, and the configuration parameters
519           "user_scores_dsn", "user_scores_ldap_username", and
520           "user_scores_ldap_password" are set correctly.
521
522           The username in $username will also be used for the "username"
523           attribute of the Mail::SpamAssassin object.
524
525       $f->set_persistent_address_list_factory ($factoryobj)
526           Set the persistent address list factory, used to create objects for
527           the automatic welcomelist algorithm's persistent-storage back-end.
528           See "Mail::SpamAssassin::PersistentAddrList" for the API these
529           factory objects must implement, and the API the objects they
530           produce must implement.
531
532       $f->compile_now ($use_user_prefs, $keep_userstate)
533           Compile all patterns, load all configuration files, and load all
534           possibly-required Perl modules.
535
536           Normally, Mail::SpamAssassin uses lazy evaluation where possible,
537           but if you plan to fork() or start a new perl interpreter thread to
538           process a message, this is suboptimal, as each process/thread will
539           have to perform these actions.
540
541           Call this function in the master thread or process to perform the
542           actions straight away, so that the sub-processes will not have to.
543
544           If $use_user_prefs is 0, this will initialise the SpamAssassin
545           configuration without reading the per-user configuration file and
546           it will assume that you will call "read_scoreonly_config" at a
547           later point.
548
549           If $keep_userstate is true, compile_now() will revert any
550           configuration options which have a default with __userstate__ in it
551           post-init(), and then re-change the option before returning.  This
552           lets you change $ENV{'HOME'} to a temp directory, have
553           compile_now() and create any files there as necessary without
554           disturbing the actual files as changed by a configuration option.
555           By default, this is disabled.
556
557       $f->debug_diagnostics ()
558           Output some diagnostic information, useful for debugging
559           SpamAssassin problems.
560
561       $failed = $f->lint_rules ()
562           Syntax-check the current set of rules.  Returns the number of
563           syntax errors discovered, or 0 if the configuration is valid.
564
565       $f->finish()
566           Destroy this object, so that it will be garbage-collected once it
567           goes out of scope.  The object will no longer be usable after this
568           method is called.
569
570       $fullpath = $f->find_rule_support_file ($filename)
571           Find a rule-support file, such as "languages" or "triplets.txt", in
572           the system-wide rules directory, and return its full path if it
573           exists, or undef if it doesn't exist.
574
575           (This API was added in SpamAssassin 3.1.1.)
576
577       $f->create_default_prefs ($filename, $username [ , $userdir ] )
578           Copy default preferences file into home directory for later use and
579           modification, if it does not already exist and "dont_copy_prefs" is
580           not set.
581
582       $f->copy_config ( [ $source ], [ $dest ] )
583           Used for daemons to keep a persistent Mail::SpamAssassin object's
584           configuration correct if switching between users.  Pass an
585           associative array reference as either $source or $dest, and set the
586           other to 'undef' so that the object will use its current
587           configuration.  i.e.:
588
589             # create object w/ configuration
590             my $spamtest = Mail::SpamAssassin->new( ... );
591
592             # backup configuration to %conf_backup
593             my %conf_backup;
594             $spamtest->copy_config(undef, \%conf_backup) ||
595               die "config: error returned from copy_config!\n";
596
597             ... do stuff, perhaps modify the config, etc ...
598
599             # reset the configuration back to the original
600             $spamtest->copy_config(\%conf_backup, undef) ||
601               die "config: error returned from copy_config!\n";
602
603           Note that the contents of the associative arrays should be
604           considered opaque by calling code.
605
606       @plugins = $f->get_loaded_plugins_list ( )
607           Return the list of plugins currently loaded by this SpamAssassin
608           object's configuration; each entry in the list is an object of type
609           "Mail::SpamAssassin::Plugin".
610
611           (This API was added in SpamAssassin 3.2.0.)
612

PREREQUISITES

614       "HTML::Parser" "Sys::Syslog"
615

MORE DOCUMENTATION

617       See also <https://spamassassin.apache.org/> and
618       <https://wiki.apache.org/spamassassin/> for more information.
619

SEE ALSO

621       Mail::SpamAssassin::Conf(3) Mail::SpamAssassin::PerMsgStatus(3)
622       spamassassin(1) sa-update(1)
623

BUGS

625       See <https://issues.apache.org/SpamAssassin/>
626

AUTHORS

628       The SpamAssassin(tm) Project <https://spamassassin.apache.org/>
629
631       SpamAssassin is distributed under the Apache License, Version 2.0, as
632       described in the file "LICENSE" included with the distribution.
633

AVAILABILITY

635       The latest version of this library is likely to be available from CPAN
636       as well as:
637
638       <https://spamassassin.apache.org/>
639
640
641
642perl v5.38.0                      2023-07-22             Mail::SpamAssassin(3)
Impressum