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 blacklists,
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
280           objects 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
309           objects 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_whitelist ($addr, $cli_p)
421           Given a string containing an email address, add it to the automatic
422           whitelist database.
423
424           If $cli_p is set then underlying plugin may give visual feedback on
425           additions/failures.
426
427       $f->add_all_addresses_to_whitelist ($mail, $cli_p)
428           Given a mail message, find as many addresses in the usual headers
429           (To, Cc, From etc.), and the message body, and add them to the
430           automatic whitelist database.
431
432           If $cli_p is set then underlying plugin may give visual feedback on
433           additions/failures.
434
435       $f->remove_address_from_whitelist ($addr, $cli_p)
436           Given a string containing an email address, remove it from the
437           automatic whitelist database.
438
439           If $cli_p is set then underlying plugin may give visual feedback on
440           additions/failures.
441
442       $f->remove_all_addresses_from_whitelist ($mail, $cli_p)
443           Given a mail message, find as many addresses in the usual headers
444           (To, Cc, From etc.), and the message body, and remove them from the
445           automatic whitelist database.
446
447           If $cli_p is set then underlying plugin may give visual feedback on
448           additions/failures.
449
450       $f->add_address_to_blacklist ($addr, $cli_p)
451           Given a string containing an email address, add it to the automatic
452           whitelist database with a high score, effectively blacklisting
453           them.
454
455           If $cli_p is set then underlying plugin may give visual feedback on
456           additions/failures.
457
458       $f->add_all_addresses_to_blacklist ($mail, $cli_p)
459           Given a mail message, find addresses in the From headers and add
460           them to the automatic whitelist database with a high score,
461           effectively blacklisting them.
462
463           Note that To and Cc addresses are not used.
464
465           If $cli_p is set then underlying plugin may give visual feedback on
466           additions/failures.
467
468       $text = $f->remove_spamassassin_markup ($mail)
469           Returns the text of the message, with any SpamAssassin-added text
470           (such as the report, or X-Spam-Status headers) stripped.
471
472           Note that the $mail object is not modified.
473
474           Warning: if the input message in $mail contains a mixture of CR-LF
475           (Windows-style) and LF (UNIX-style) line endings, it will be
476           "canonicalized" to use one or the other consistently throughout.
477
478       $f->read_scoreonly_config ($filename)
479           Read a configuration file and parse user preferences from it.
480
481           User preferences are as defined in the "Mail::SpamAssassin::Conf"
482           manual page.  In other words, they include scoring options, scores,
483           whitelists and blacklists, and so on, but do not include rule
484           definitions, privileged settings, etc. unless "allow_user_rules" is
485           enabled; and they never include the administrator settings.
486
487       $f->load_scoreonly_sql ($username)
488           Read configuration parameters from SQL database and parse scores
489           from it.  This will only take effect if the perl "DBI" module is
490           installed, and the configuration parameters "user_scores_dsn",
491           "user_scores_sql_username", and "user_scores_sql_password" are set
492           correctly.
493
494           The username in $username will also be used for the "username"
495           attribute of the Mail::SpamAssassin object.
496
497       $f->load_scoreonly_ldap ($username)
498           Read configuration parameters from an LDAP server and parse scores
499           from it.  This will only take effect if the perl "Net::LDAP" and
500           "URI" modules are installed, and the configuration parameters
501           "user_scores_dsn", "user_scores_ldap_username", and
502           "user_scores_ldap_password" are set correctly.
503
504           The username in $username will also be used for the "username"
505           attribute of the Mail::SpamAssassin object.
506
507       $f->set_persistent_address_list_factory ($factoryobj)
508           Set the persistent address list factory, used to create objects for
509           the automatic whitelist algorithm's persistent-storage back-end.
510           See "Mail::SpamAssassin::PersistentAddrList" for the API these
511           factory objects must implement, and the API the objects they
512           produce must implement.
513
514       $f->compile_now ($use_user_prefs, $keep_userstate)
515           Compile all patterns, load all configuration files, and load all
516           possibly-required Perl modules.
517
518           Normally, Mail::SpamAssassin uses lazy evaluation where possible,
519           but if you plan to fork() or start a new perl interpreter thread to
520           process a message, this is suboptimal, as each process/thread will
521           have to perform these actions.
522
523           Call this function in the master thread or process to perform the
524           actions straight away, so that the sub-processes will not have to.
525
526           If $use_user_prefs is 0, this will initialise the SpamAssassin
527           configuration without reading the per-user configuration file and
528           it will assume that you will call "read_scoreonly_config" at a
529           later point.
530
531           If $keep_userstate is true, compile_now() will revert any
532           configuration options which have a default with __userstate__ in it
533           post-init(), and then re-change the option before returning.  This
534           lets you change $ENV{'HOME'} to a temp directory, have
535           compile_now() and create any files there as necessary without
536           disturbing the actual files as changed by a configuration option.
537           By default, this is disabled.
538
539       $f->debug_diagnostics ()
540           Output some diagnostic information, useful for debugging
541           SpamAssassin problems.
542
543       $failed = $f->lint_rules ()
544           Syntax-check the current set of rules.  Returns the number of
545           syntax errors discovered, or 0 if the configuration is valid.
546
547       $f->finish()
548           Destroy this object, so that it will be garbage-collected once it
549           goes out of scope.  The object will no longer be usable after this
550           method is called.
551
552       $fullpath = $f->find_rule_support_file ($filename)
553           Find a rule-support file, such as "languages" or "triplets.txt", in
554           the system-wide rules directory, and return its full path if it
555           exists, or undef if it doesn't exist.
556
557           (This API was added in SpamAssassin 3.1.1.)
558
559       $f->create_default_prefs ($filename, $username [ , $userdir ] )
560           Copy default preferences file into home directory for later use and
561           modification, if it does not already exist and "dont_copy_prefs" is
562           not set.
563
564       $f->copy_config ( [ $source ], [ $dest ] )
565           Used for daemons to keep a persistent Mail::SpamAssassin object's
566           configuration correct if switching between users.  Pass an
567           associative array reference as either $source or $dest, and set the
568           other to 'undef' so that the object will use its current
569           configuration.  i.e.:
570
571             # create object w/ configuration
572             my $spamtest = Mail::SpamAssassin->new( ... );
573
574             # backup configuration to %conf_backup
575             my %conf_backup;
576             $spamtest->copy_config(undef, \%conf_backup) ||
577               die "config: error returned from copy_config!\n";
578
579             ... do stuff, perhaps modify the config, etc ...
580
581             # reset the configuration back to the original
582             $spamtest->copy_config(\%conf_backup, undef) ||
583               die "config: error returned from copy_config!\n";
584
585           Note that the contents of the associative arrays should be
586           considered opaque by calling code.
587
588       @plugins = $f->get_loaded_plugins_list ( )
589           Return the list of plugins currently loaded by this SpamAssassin
590           object's configuration; each entry in the list is an object of type
591           "Mail::SpamAssassin::Plugin".
592
593           (This API was added in SpamAssassin 3.2.0.)
594

PREREQUISITES

596       "HTML::Parser" "Sys::Syslog"
597

MORE DOCUMENTATION

599       See also <https://spamassassin.apache.org/> and
600       <https://wiki.apache.org/spamassassin/> for more information.
601

SEE ALSO

603       Mail::SpamAssassin::Conf(3) Mail::SpamAssassin::PerMsgStatus(3)
604       spamassassin(1) sa-update(1)
605

BUGS

607       See <https://issues.apache.org/SpamAssassin/>
608

AUTHORS

610       The SpamAssassin(tm) Project <https://spamassassin.apache.org/>
611
613       SpamAssassin is distributed under the Apache License, Version 2.0, as
614       described in the file "LICENSE" included with the distribution.
615

AVAILABILITY

617       The latest version of this library is likely to be available from CPAN
618       as well as:
619
620       <https://spamassassin.apache.org/>
621
622
623
624perl v5.32.1                      2021-03-25             Mail::SpamAssassin(3)
Impressum