====== Mail Server ======

The Synchronet Mail Server is responsible for incoming and outgoing Internet e-mail.

===== Incoming =====

The mail server accepts submissions via the SMTP and ESMTP protocols, by default, on TCP ports 25 and 587.

By default, the mail server does not allow relaying of mail from unauthenticated clients to external mail servers.

The SMTP server supports authentication via the PLAIN, LOGIN, or CRAM-MD5 SMTP-AUTH methods (client chooses).

The SMTP server optionally supports SMTP-TLS sessions.

The SMTP server can service multiple simultaneous incoming sessions and messages, with multiple recipients per message.

The SMTP server also supports the SEND, SAML and SOML commands for delivering instant messages (a.k.a. telegrams) to users of the BBS.

==== Recipients ====
When receiving email messages via SMTP, the Synchronet mail server can match recipient names to a BBS user account by their alias or optionally, their real name. 

=== Special Characters ===
Non-alphanumeric characters are ignored when matching recipient names to BBS user aliases. So for example, the following will all match the user "digital man":
  * ''digital.man''
  * ''digital_man''
  * ''digitalman''
  * ''d-i-g-i-t-a-l-man''

=== Real Names ===
When matching recipient names to BBS real names (if so enabled by the sysop by setting SCFG->Message Options->Receive E-mail by Real Name to "Yes"), spaces and '.' are treated as equivalent. When "Receive E-mail by Real Name" is enabled, receiving e-mail by user's alias is still supported.

=== Special Aliases ===
Recipient names configured in ''[[dir:ctrl]]/[[config:alias.cfg]]'' can be used to match recipient names to specific user account numbers, aliases, external email addresses, or even sub-boards.

==== Special Prefixes ====
Recipient mail addresses can have special prefixes to direct the routing of the incoming mail:

^ Prefix   ^ Syntax              ^ Description ^
| local:   | ''local:<user>''    | Deliver to local mailbox only, do not forward to external mail/netmail address |
| forward: | ''forward:<user>''  | Forward to the destination user's external mail/netmail address |
| sub:     | ''sub:<code>''      | Post email contents as message on message sub-board (specified by internal code) |
| qwk-id!  | ''<qwk-id>!<user>'' | Routes to <user> at QWKnet node with specified QWK-ID (may include a full slash-separated route) |

It is sometimes preferred to use an alias (configured in the ''[[dir:ctrl]]/[[config:alias.cfg]]'' file) to allow the reception of a more "normal" looking email address and route to the Specially-Prefixed address. The following examples allows the reception of email sent to "cnnreport@<yourbbs>" and forwards the message to the message sub-board with the internal code of ''dove-deb'':

  cnnreport    sub:dove-deb
  
==== Special Addresses ====
Some specially formatted destination addresses (''RCPT TO'' addresses) are recognized and treated specially by the Synchronet SMTP server.

=== FidoNet ===
If the system supports [[network:FidoNet]]-style networking (has at least one address configured in [[util:SCFG]]->Networks->FidoNet->Addresses), then incoming FidoNet netmail messages are recognized with one of the following formats:

  * ''//<name>//@f//<node>//.n//<net>//.z//<zone>//.fidonet''
  * ''//<name>//@p//<point>//.f//<node>//.n//<net>//.z//<zone>//.fidonet''

Example: ''rob.swindell@f705.n103.z1.fidonet''

Note: the ''.fidonet'' host suffix is required even if the destination network is an //othernet// (not technically part of FidoNet proper). This is a "virtual" TLD, no DNS lookup is performed by the mailserver for destination hostnames with this suffix.

=== Tags ===

The Synchronet Mail Server recognizes the incoming special address format: ''//<name>//#//<tag>//@//<host>//''

The //<tag>// is extracted from the address and if it is **not** found in the ''data/user/<usernum>.smtpblock'' file, the mail message is
sent to the destination user.  If the tag matches a line in the ''.smtpblock'' file, the email is rejected by the mail server with a "no such user" error.

This feature allows you (the sysop) to easily create and use "temporary" email addresses without requiring additional user accounts.  Once you start receiving spam with a tag, just disable that tag by adding it to your ''.smtpblock'' file.

==== Anti-SPAM ====
The Synchronet SMTP Server contains several anti-SPAM measures:
  * DNS-based blacklist (DNSBL) look-up support with exemptions and multiple possible actions upon positive results
  * Mail server filtering based on IP address/subnet or hostname (''[[dir:ctrl]]/spamblock.cfg''), with exemptions (''[[dir:ctrl]]/spamblock_exempt.cfg'')
  * Email address filtering with wildcard support (''[[dir:text]]/email.can'')
  * Message subject filtering with wildcard support (''[[dir:text]]/subject.can'')
  * Configurable SPAM bait list (''[[dir:ctrl]]/spambait.cfg'') for auto-blocking mail servers based on honey-pot destination email addresses
  * Unlimited number of external mail processors (e.g. ''[[module:spamc]].js'', ''[[module:mailauth]].js'') that can modify (e.g. tag) or reject email messages at will
  * Synchronet's normal host filtering (via ''ip.can'' and ''host.can'') and configurable LoginAttempt tracking/throttling/blocking (in ''[[config:sbbs.ini]]'') is also employed

=== DNSBL ===

DNS-based Blacklists (DNSBL) are 3rd party databases of IP addresses whose hosts are suspected of being habitual spammers or have other security problems which make mail received from these systems highly suspicious. Different DNSBL services/servers have differing criteria for what can get an IP listed or de-listed (removed) from their database. Examine your ''[[dir:ctrl]]/[[config:dns_blacklist.cfg]]'' file to determine what DNSBL services your Synchronet Mail Server is using.

The Synchronet Mail Server can use DNS queries to multiple DNSBL servers (as configured in ''[[dir:ctrl]]/[[config:dns_blacklist.cfg]]'') for each inbound SMTP/ESMTP connection from a prospective mail transfer agent (MTA). If the MTA's IP address is listed by one of the DNSBL servers, then multiple actions may be taken:
  * A Notice-level mail server log entry: ''SMTP BLACKLISTED SERVER on ...'' (always)
  * An entry added to the ''[[dir:data]]/spam.log'' file (always)
  * Mail session refused, if the ''DNSBL_REFUSE'' option is set in the ''[[Mail]]'' section of the ''[[config:sbbs.ini]]'' file
  * SMTP commands and lines of message headers and body text may be throttled at 1 line per second when the ''DNSBL_THROTTLE'' option is set
  * Reject the mail message, if the ''DNSBL_BADUSER'' option is set
  * Message Subject may be 'tagged' with a prepended configurable string (e.g. ''SPAM:''), see ''DNSBlacklistSubject'' ''sbbs.ini'' key
  * Message Header may be 'tagged' with a special header field (e.g. ''X-DNSBL''), see ''DNSBlacklistHeader'' ''sbbs.ini'' key
  * Message may be received and ignored/dropped, if the ''DNSBL_IGNORE'' option is set
  * Message hash stored in a database of SPAM message body hashes (''[[dir:data]]/spam.hash''), if the ''DNSBL_SPAMHASH'' option is set

A mail message's "Received" headers may also be scanned for DNSBL-listed IP addresses (''DNSBL_CHKRECVHDRS'' option) so that any e-mail messages that originate or pass-through a DNSBL-listed will be treated as though it is being delivered directly from a DNSBL-listed MTA.

When a DNSBL service reports an IP address as "black-listed", any additional DNSBL services/servers are not queried.

If you have used zen.spamhaus.org in the past, this will no longer work. You will need to apply for a Spamhaus Data Query Service account at https://www.spamhaus.com/data-access/free-data-query-service/ where you will receive a unique key that is used to query their DNS. 

== Exemptions ==
MTA's whose IP address or hostname is listed in your ''[[dir:ctrl]]/dnsbl_exempt.cfg'' file are never checked against DNSBL servers.

Mail from e-mail addresses that are listed in the ''dnsbl_exempt.cfg'' file are also exempt from DNSBL actions.

The destination addersses of email delivered by the Synchronet Mail Server's //SendMail Thread// are automatically added to your ''dnsbl_exempt.cfg'' file unless the ''NO_AUTO_EXEMPT'' option is set.

=== Synchronet Control Panel ===

Most of the DNSBL-related settings can be found in the [[monitor:sbbsctrl]] Mail Server Configuration tabs:

{{:server:SBBSCTRL.dnsbl.png?400|}}

{{:server:SBBSCTRL.mailsrvr.advanced.png?400|}}

==== Archiving ====

The Synchronet Mail Server (v3.21+) can automatically archive messages received via SMTP as separate ''.eml'' files in sub-directories of ''[[dir:data]]/user/####/'' (where ''####'' is the recipient or relaying user number).

To utilize the mail archive feature, the sysop must set the "Archive Requirements" mail server setting (e.g. in [[util:SCFG]]->Servers->Mail Server) to specify the [[:access:]] requirements of the user or users whose mail should be auto-archived.

Notes:
  * Messages are archived after being processed by any external mail processors which may have modified the message header or body
  * SPAM-tagged messages received for local users are not archived
  * Archived messages are stored in ''.eml'' files, plain text files conforming to the RFC-822 internet message standard format
  * Messages received for relay by users meeting the archive requirements are be stored in their ''[[dir:data]]/user/####/smtp_relay'' directory (i.e. like an "inbox")
  * Messages received for delivery to local users meeting the archive requirements are stored in their ''[[dir:data]]/user/####/smtp_in'' directory (i.e. like an "outbox")
  * There's no limit to the number or size of messages that may be archived, so disk consumption could be a concern



===== SendMail =====

The Synchronet Mail Server's //SendMail Thread// is responsible for delivering Internet email using the SMTP or ESMTP protocols, optionally authenticating using PLAIN, LOGIN, or CRAM-MD5 SMTP-AUTH methods if required by an SMTP relay server.

Both Direct Delivery and Relaying (e.g. through intermediary mail server) is supported.

  * //Direct// looks up recipient MX records and contacts the destination SMTP server, one connection per recipient domain.
  * //Relay// forwards every outgoing message through a single upstream smarthost (e.g. an ISP SMTP server, a local Sendmail/Postfix on the same host, or a transactional-mail provider). Relay mode is typically required when your ISP blocks outbound TCP port 25, or when you want all outgoing mail to appear to originate from a single MTA.

The SendMail Thread currently can service one outgoing SMTP/ESMTP session at a time.

The SendMail Thread will attempt to deliver securely (encrypted via TLS) when possible, though it will fall back to plain text delivery when necessary.

==== DKIM Signing ====

The SendMail Thread can sign outgoing messages with a **DKIM** (DomainKeys Identified Mail) signature: a ''DKIM-Signature'' header that lets receiving mail servers cryptographically verify a message really originated from your domain. Combined with SPF and DMARC, this significantly improves deliverability to providers such as Gmail and Outlook, which increasingly distrust unauthenticated mail.

DKIM signing uses OpenSSL and is supported on both Unix-like and Windows builds of Synchronet. (A build made without OpenSSL support will accept the options below but leave them inactive, sending mail unsigned.)

DKIM uses a public/private key pair. The **private** key stays on your server and signs outgoing mail; the matching **public** key is published in DNS so receivers can verify the signature. Setting it up is a one-time procedure.

**1. Generate a key pair.** Create a 2048-bit RSA private key in your ''[[dir:ctrl]]'' directory, named ''dkim_<selector>.pem'', where //<selector>// is a short label of your choosing (e.g. ''mail''):

  openssl genrsa -out /sbbs/ctrl/dkim_mail.pem 2048
  chmod 600 /sbbs/ctrl/dkim_mail.pem

Keep this file secret.

**2. Publish the public key in DNS.** Extract the public key:

  openssl rsa -in /sbbs/ctrl/dkim_mail.pem -pubout -outform DER | base64 -w0

Create a DNS TXT record named ''<selector>._domainkey.<yourdomain>'' (e.g. ''mail._domainkey.example.com'') with this value:

  v=DKIM1; k=rsa; p=(the base64 public key from above)

A 2048-bit public key is longer than the 255-character limit of a single DNS TXT string, so most DNS editors split it into multiple quoted strings automatically; in a BIND zone file, write it as adjacent quoted strings within parentheses.

**3. Publish a DMARC record (recommended).** A DMARC policy lets your DKIM and SPF results count toward domain authentication at the receiver. Begin in monitor-only mode, which never causes mail to be rejected, as a TXT record named ''_dmarc.<yourdomain>'':

  v=DMARC1; p=none; adkim=r; aspf=r

For a DKIM signature to satisfy DMARC //alignment//, the signing domain (//DKIM Domain//, below) should match, or share the organizational domain of, the domain in your messages' ''From:'' address.

**4. Enable signing.** In SCFG, under //Mail Server//, //SendMail Support//, set //DKIM Signing// to ''Yes'', //DKIM Domain// to your domain (the ''d='' tag, e.g. ''example.com''), and //DKIM Selector// to the label you chose (the ''s='' tag, e.g. ''mail''). The equivalent keys in the ''[Mail]'' section of ''[[config:sbbs.ini]]'' are:

  [Mail]
  DKIMSign = true
  DKIMDomain = example.com
  DKIMSelector = mail

The server reads the private key from ''[[dir:ctrl]]/dkim_<selector>.pem'', so the selector must match both the key filename and the DNS record name. Recycle the Mail Server for the change to take effect; the server log shows ''DKIM signing enabled'' on start-up.

**5. Verify.** Send a message to an account whose headers you can inspect (e.g. Gmail's //Show original//, or an auto-responder such as ''check-auth@verifier.port25.com''). A correctly configured signer shows ''dkim=pass'' in the receiver's //Authentication-Results//. Confirm that the published public key matches your private key before relying on it; a truncated DNS value silently produces ''dkim=fail''.

**Key rotation.** To rotate keys, generate a new key under a //new// selector, publish its DNS record, then change //DKIM Selector// to the new value. Leave the old selector's DNS record in place until mail signed with the old key has been delivered, then remove it.

===== Post Office =====

The mail server also services authenticated "post office" requests from mail clients using the POP3 protocol, by default, on TCP port 110 and POP3S (Secure/encrypted POP3 over TLS) on TCP Port 995.

The POP3 server supports client authentication via the USER or APOP methods.

The POP3 server can service multiple simultaneous incoming sessions.

For IMAP support, see Deuce's [[service:imap|IMAP Service]].

==== Anti-SPAM ====

The Synchronet POP3 server will filter-out SPAM-tagged mail automatically when a POP3 client logs in with ''//<username>//#nospam''. 

Append "#nospam" to your login name/alias and any
SPAM-tagged messages will not be listed/downloaded. This is useful if for
example you use POP3 to download mail to your phone and have limited
storage or sorting options. The SPAM-tagged messages will remain in your
inbox on the BBS so you should use another POP3 or local mail client to
download and delete those messages (which could potentially include
false positives).

===== Configure =====

The Synchronet Mail Server can be configured via [[util:SCFG]]:Servers->Mail Server:

  ╔════════════════════════════════════════════╗
  ║            Mail Server Settings            ║
  ╠════════════════════════════════════════════╣
  ║ │Enabled                       Yes         ║
  ║ │Log Level                     Info        ║
  ║ │SMTP Interfaces               0.0.0.0, :: ║
  ║ │SMTP Support                  Port 25     ║
  ║ │Submission Support            Port 587    ║
  ║ │Submission/TLS Support        Port 465    ║
  ║ │POP3 Interfaces               0.0.0.0, :: ║
  ║ │POP3 Support                  Port 110    ║
  ║ │POP3/TLS Support              Port 995    ║
  ║ │Mark Retrieved Mail as Read   Yes         ║
  ║ │Max Clients                   100         ║
  ║ │Max Inactivity                2 minutes   ║
  ║ │Max Concurrent Connections    Unlimited   ║
  ║ │Max Recipients Per Message    100         ║
  ║ │Max Messages Waiting          100         ║
  ║ │Max Receive Message Size      20M bytes   ║
  ║ │Limit Rate of Requests        <disabled>  ║
  ║ │Post Recipient                            ║
  ║ │Default Recipient                         ║
  ║ │Receive By Sysop Aliases      No          ║
  ║ │Notify Local Recipients       Yes         ║
  ║ │Notify Offline Recipients     Yes         ║
  ║ │Allow Users to Relay Mail     No          ║
  ║ │Lookup Client Hostname        Yes         ║
  ║ │Check Headers against DNSBL   No          ║
  ║ │DNS-Blacklisted Servers       Tag Mail    ║
  ║ │Hash DNS-Blacklisted Msgs     No          ║
  ║ │Kill SPAM When Read           No          ║
  ║ │Spammer IP-Filter Duration    Infinite    ║
  ║ │SendMail Support...           Direct      ║
  ║ │Login Requirements                        ║
  ║ │Archive Requirements                      ║
  ║ │JavaScript Settings...                    ║
  ║ │Failed Login Attempts...                  ║
  ╚════════════════════════════════════════════╝

The Synchronet Mail Server "SendMail Thread" can be configured via [[util:SCFG]]:Servers->Mail Server->SendMail Support:

  ╔══════════════════════════════════════════════════╗
  ║                  SendMail Support                ║
  ╠══════════════════════════════════════════════════╣
  ║ │Enabled                       Yes               ║
  ║ │Rescan Interval               1 hour            ║
  ║ │Connect Timeout               30 seconds        ║
  ║ │Auto-exempt Recipients        Yes               ║
  ║ │Max Delivery Attempts         50                ║
  ║ │Delivery Method               Direct            ║
  ╚══════════════════════════════════════════════════╝

When //Delivery Method// is changed to //Relay//, five additional fields appear:

  ╔══════════════════════════════════════════════════╗
  ║                  SendMail Support                ║
  ╠══════════════════════════════════════════════════╣
  ║ │Enabled                       Yes               ║
  ║ │Rescan Interval               1 hour            ║
  ║ │Connect Timeout               30 seconds        ║
  ║ │Auto-exempt Recipients        Yes               ║
  ║ │Max Delivery Attempts         50                ║
  ║ │Delivery Method               Relay             ║
  ║ │Relay Server Address          smtp.example.com  ║
  ║ │Relay Server TCP Port         587               ║
  ║ │Relay Server Authentication   Plain             ║
  ║ │Relay Server Username         myuser            ║
  ║ │Relay Server Password         ********          ║
  ╚══════════════════════════════════════════════════╝

^ SCFG label                       ^ ini key (in [[#sbbs.ini|''[Mail]'']]) ^
| //Enabled//                        | option ''NO_SENDMAIL'' (off when set) |
| //Rescan Interval//                | ''RescanFrequency'' |
| //Connect Timeout//                | ''ConnectTimeout'' |
| //Auto-exempt Recipients//         | option ''NO_AUTO_EXEMPT'' (off when set) |
| //Max Delivery Attempts//          | ''MaxDeliveryAttempts'' |
| //Delivery Method// = ''Relay''    | option ''RELAY_TX'' |
| //Relay Server Address//           | ''RelayServer'' |
| //Relay Server TCP Port//          | ''RelayPort'' |
| //Relay Server Authentication//    | one of options ''RELAY_AUTH_PLAIN'' / ''RELAY_AUTH_LOGIN'' / ''RELAY_AUTH_CRAM_MD5'' (or none) |
| //Relay Server Username//          | ''RelayUsername'' (only used when an auth option is set) |
| //Relay Server Password//          | ''RelayPassword'' (only used when an auth option is set) |

==== DNS-Blacklisted Servers picker ====

The //DNS-Blacklisted Servers// row in the main Mail Server menu opens a four-choice picker that controls how DNSBL-listed senders are handled. Each picker option corresponds to a particular ''[Mail] Options'' bit:

^ SCFG choice         ^ ini option set    ^ Effect on DNSBL-listed sender ^
| //Refuse Session//  | ''DNSBL_REFUSE''  | Drop the SMTP/ESMTP connection at the greeting; no message accepted. |
| //Silently Ignore// | ''DNSBL_IGNORE''  | Accept the message and discard it. The sending MTA sees a successful delivery but Synchronet drops the mail on the floor. |
| //Refuse Mail//     | ''DNSBL_BADUSER'' | Reject each recipient with "invalid mailbox" — the message body is never accepted. |
| //Tag Mail//        | (none of the above) | Accept and deliver the message but prepend a SPAM tag (//DNSBlacklistSubject//) to the subject and add a //DNSBlacklistHeader// header for downstream filtering. //Tag Mail// is the default when none of the three options is set. |

If //Throttle DNS-Blacklisted Servers// is also set (option ''DNSBL_THROTTLE''), the chosen action is preceded by per-line throttling (1 line/sec) of SMTP commands and message text.

... via [[monitor:SBBSCTRL]]:Mail->Configure:

{{:server:sbbsctrl.3.20.mail.config.png|}}

... or by editing the ''[Mail]'' section fo the ''[[dir:ctrl]]/[[config:sbbs.ini]]'' file.

==== sbbs.ini ====

The ''[mail]'' section of the ''[[dir:ctrl]]/[[config:sbbs.ini]]'' file supports the following configuration settings (''key = value'' lines):

^ Key               ^ Default Value ^ Description ^
| AutoStart         | true          | Automatically start up the server (manual is only supported in [[monitor:sbbsctrl]]) |
| Interface         | [global]      | Comma-separated list of IPv4 and IPv6 network interfaces to listen on for incoming SMTP/SMTPS connections |
| POP3Interface     | Interface     | Comma-separated list of IPv4 and IPv6 network interfaces to listen on for incoming POP3/POP3S connections |
| OutboundInterface | [global]      | IPv4 network interface to use for outgoing SMTP/SMTPS connections (0.0.0.0 = //any interface//) |
| SMTPPort          | 25            | TCP port number to listen on for incoming SMTP mail-delivery connections |
| SubmissionPort    | 587           | TCP port number to listen on for incoming SMTP mail-submission connections |
| TLSSubmissionPort | 465           | TCP port number to listen on for incoming SMTPS (encrypted) mail-submission connections |
| POP3Port          | 110           | TCP port number to listen on for incoming POP3 mail-retrieval connections |
| TLSPOP3Port       | 995           | TCP port number to listen on for incoming POP3S (encrypted) mail-retrieval connections |
| MaxClients        | 10            | Maximum number of simultaneous incoming TCP sessions supported |
| MaxConcurrentConnections | 0      | Maximum number of concurrent connections (without login) from the same IP address (0 = unlimited) |
| MaxInactivity     | 120           | Maximum amount of TCP session inactivity before timeout and disconnection (in seconds) |
| MaxDeliveryAttempts | 50          | Maximum number of outbound mail delivery attempts before mail is bounced back to sender |
| RescanFrequency     | 60M         | Frequency (in seconds) of mail base re-scans for outbound mail to be sent/re-sent |
| SemFileCheckFrequency | 2         | Frequency (in seconds) of checks for semaphore files |
| LinesPerYield         | 10        | Interval (in message body lines) of thread-yields during message receive (0 = none) |
| MaxRecipients         | 100       | Maximum number of mail recipients for a single inbound SMTP mail message |
| MaxMsgSize            | 20MB      | Maximum size of incoming SMTP mail messages, in bytes |
| MaxMsgsWaiting        | 100       | Maximum number of messages allowed in a (non-W-exempt) user's inbox |
| ConnectTimeout        | 30        | Timeout (in seconds) before blocked outbound SMTP/TCP connections are aborted |
| HostName              | [global]  | Hostname of this server |
| TempDirectory         | [global]  | Directory to use for the storage of temporary files |
| RelayServer           |           | Hostname or IP address of SMTP server to relay outbound mail through (requires ''RELAY_TX'' option) |
| RelayPort             | 25        | TCP port number to connect with when relaying mail to RelayServer |
| RelayUsername         |           | Username used to authenticate with RelayServer |
| RelayPassword         |           | Password used to authenticate with RelayServer |
| DNSServer             | <auto>    | IP address of DNS server used to discover mail-exchange servers for outbound mail destinations |
| PostTo                |           | Override the recipient of all SMTP-posted messages (on sub-boards) with this value (e.g. "All") |
| DefaultUser           |           | Default recipient of mail for unrecognized recipient names (blank = none) |
| DefaultCharset        |           | Default MIME Content-Type ''charset'' value when unspecified (e.g. ''IBM437'') |
| DNSBlacklistHeader    | X-DNSBL   | Header value to add to incoming mail messages from DNS-Blacklisted servers |
| DNSBlacklistSubject   | SPAM      | Word to insert into beginning of subject of mail messages from DNS-Blacklisted servers |
| POP3Sound             |           | WAV file to play upon incoming POP3 connections (Windows only) |
| InboundSound          |           | WAV file to play upon incoming SMTP/SMTPS connections (Windows only) |
| OutboundSound         |           | WAV file to play upon outgoing SMTP/SMTPS connections (Windows only) |
| ArchiveRequirements   |           | [[:Access]] Requirements for auto-archiving of non-SPAM mail messages (stored in ''.eml'' format) sent to or from select users |
| JavaScript*           | [global]  | JavaScript-related settings for external mail processing |
| LogLevel              | [global]  | Minimum severity of log messages to be displayed / stored |
| BindRetryCount        | [global]  | Maximum number of TCP port bind attempts before failure |
| BindRetryDelay        | [global]  | Delay (in seconds) between TCP port bind retries |
| LoginAttempt*         | [global]  | Failed login attempt throttling / filtering / banning |
| Options               | ''ALLOW_POP3'' | Mail server option flags (see below for details) |

=== Options ===

The ''Options'' key of the ''[mail]'' section of the ''[[dir:ctrl]]/[[config:sbbs.ini]]'' file supports the following option flags (separated by a ''|'' character):

^ Option              ^ Description ^
| USE_SUBMISSION_PORT | Support mail submissions on the SMTP submission port |
| TLS_SUBMISSION      | Support incoming SMTP Submissions (encrypted) connections |
| ALLOW_POP3          | Support incoming POP3 connections for BBS users to use mail clients to retrieve the mail in their BBS inbox |
| DEBUG_POP3          | Log all POP3 activity (Debug log level) |
| TLS_POP3            | Support incoming POP3S (POP3/TLS) connections |
| NO_READ_POP3        | Do not mark POP3-retrieved mail messages as "Read" |
| DEBUG_TX            | Log all transmissions (Debug log level) | 
| DEBUG_RX_HEADER     | Log headers of all received messages (Debug log level)|
| DEBUG_RX_BODY       | Log body text of all received messages (Debug log level)|
| DEBUG_RX_RSP        | Log all received responses (Debug log level) |
| ALLOW_SYSOP_ALIASES | Allow email to received for various administrative aliases (e.g. "sysop", "postmaster") to be delivered to the sysop |
| NO_NOTIFY           | Do not send telegrams to users notifying them of newly received email |
| NO_HOST_LOOKUP      | Do not resolve/log hostnames of incoming TCP connections |
| USE_TCP_DNS         | Use TCP instead of UDP for MX-record queries using DNS |
| NO_SENDMAIL         | Do not send outbound Internet email |
| ALLOW_RELAY         | Allow authenticated users to relay Internet email through this server |
| SMTP_AUTH_VIA_IP    | Authenticate users via IP address when supported |
| DNSBL_REFUSE        | Actively refuse all mail sessions from DNS-blacklisted servers |
| DNSBL_IGNORE        | Ignore (silently-discard) mail from DNS-blacklisted servers |
| DNSBL_BADUSER       | Block (report "invalid mailbox") mail from DNS-blacklisted servers |
| DNSBL_CHKRECVHDRS   | Check "Received" headers in mail messages for DNS-blacklisted servers |
| DNSBL_THROTTLE      | Throttle mail sessions from DNS-blacklisted servers |
| DNSBL_SPAMHASH      | Store hashes of confirmed SPAM messages for later comparison |
| SEND_INTRANSIT      | Send mail that is marked 'in-transit' (not recommended) |
| RELAY_TX            | Relay outbound SMTP mail through an intermediary SMTP RelayServer |
| RELAY_AUTH_PLAIN    | When relaying mail to a RelayServer, use SMTP-PLAIN AUTH |
| RELAY_AUTH_LOGIN    | When relaying mail to a RelayServer, use SMTP-LOGIN AUTH |
| RELAY_AUTH_CRAM_MD5 | When relaying mail to a RelayServer, use SMTP-CRAM_MD5 AUTH |	
| NO_AUTO_EXEMPT      | Do not automatically exempt outbound mail recipients in ''dnsbl_exempt.cfg'' |
| NO_RECYCLE          | Do not allow this server to be automatically recycled by external event |
| KILL_READ_SPAM      | Mark received SPAM messages for "Kill after read" |


===== External Mail Processors =====

In-bound e-mail (received via SMTP) can be intercepted and modified via one or more external mail processors.

An external mail processor needs to create, remove or modify one or more files to have its impact
on the SMTP mail receive process. These files (created in the mail server's temporary file directory) are:

^ Name                   ^ Example Filename    ^ Format   ^ Description ^
| **message_text**       | ''SBBS_SMTP.*.msg'' | [[https://www.rfc-editor.org/rfc/rfc5322|RFC-822]]   | Complete message header and body as received via SMTP |
| **new_message_text**   | ''SBBS_SMTP.*.new'' | [[https://www.rfc-editor.org/rfc/rfc5322|RFC-822]]   | New (replacement) message header and body (optional) |
| **recipient_list**     | ''SBBS_SMTP.*.lst'' | ''[[config:ini_files|.ini]]'' |List of all SMTP recipients for this message (see below for details) |
| **processing_error**   | ''SBBS_SMTP.*.err'' | US-ASCII | File that if created will reject this message with an SMTP error  |
| **log_text**           | ''SBBS_SMTP.*.log'' | US-ASCII | If created will include debug output from the external mail processor to be logged |

Since the file **names** contain SMTP-session specific information (e.g. numbers), the filenames must be passed from the Mail Server to external mail processors via command-line or JavaScript properties.

=== Message Text ===

An external mail processor may either modify the **message_text** file in-place or create a **new_message_text** file that will be used in its place.

=== Recipient List ===

SMTP envelop information is stored in the **recipient_list** file. 

The recipient list file has a ''.ini'' [section] for each recipient. Though the section name is an increasing decimal integer value (0, 1, etc.), there's no strict requirement that the recipient sections are so named, as long as they are uniquely named.

An external mail processor may add, remove, or modify recipients in the recipient list file.

An example recipient list file for 4 recipients (3 remote/forward, 1 local):

<file ini>
[0]
To=jack.ryan@vert.synchro.net
ToExt=636
ToNetType=5
ToNetAddr=ryan.jack@gmail.com
[1]
To=steven.tyler@vert.synchro.net
ToExt=1080
ToNetType=5
ToNetAddr=someone@gmail.com
[2]
To=ricky.bobby@vert.synchro.net
ToExt=190
[3]
To=austin.powers@vert.synchro.net
ToExt=418
ToNetType=5
ToNetAddr=another@yahoo.com
</file>

  * The ''To'' value contains the recipients "name"
  * The ''ToNetAddr'' value contains the recipients full email address
  * The ''ToNetType'' value corresponds with SMB network types (0=None, 2=Fido, 4=QWKnet, 5=Internet)
  * The ''ToExt'' value contains the recipient's user number on the BBS, when relevant

==== Configure ====

The mail processors are configured in the ''[[dir:ctrl]]/[[config:mailproc.ini]]'' file.

Each mail processor is specified in a separate "section", comprised of the
mail processor name (or command-line) enclosed in square brackets ("[]"), 
followed by a list of optional "key = value" pairs.

Supported ''[[dir:ctrl]]/[[config:mailproc.ini]]'' keys (for each mail processor) with default values:

^ Key                    ^ Default      ^ Description ^
| ''Disabled''           | ''false''    | Set to true to disable |
| ''PassThru''           | ''true''     | A mail message should "pass-through" to a BBS user's inbox |
| ''Native''             | ''false''    | The mail process is a native (not JavaScript) program |
| ''IgnoreOnError''      | ''false''    | If there's an error reported, ignore it |
| ''To''                 | //none//     | Comma-separate list of possible recipient matches (name or name@address, filter wildcards and ''!'' logic negation supported) |
| ''From''               | //none//     | Comma-separate list of required sender names (filter wildcards and ''!'' logic negation supported) |
| ''AccessRequirements'' | //none//     | Optional access requirements for the processor to run |
| ''ProcessSPAM'''       | ''true''     | Set to ''false'' to not process SPAM-tagged messages |
| ''ProcessDNSBL''       | ''true''     | Set to ''false'' to not process mail from DNS-blacklisted clients |
| ''Command''            | //section//  | The command or script name to invoke |
| ''Eval''               | //none//     | The JavaScript expression to invoke |

If no ''Eval'' or ''Command'' key value is specified, the mail processor name
will be used as the command-line to execute.

Non-JavaScript mail processors (i.e. native executables), must have the 
''native'' key set to ''true''.

For a mail processor to only process mail received for specific name(s),
it must have a ''To'' key with a comma-separated list of destination names.

Example: ''To = listserver, listserv'' would cause a mail processor to only
process mail received for either ''listserver'' or ''listserv''.

If no ''To'' value is specified, then the mail processor will process **all**
incoming (SMTP) e-mail messages.

The ''From'' key is similar to the ''To'' key:
a list of zero or more strings to be used to determine which 
sender addresses the mail processor should be executed for.

The strings in the to/from lists may use the Synchronet ''.can'' style comparison patterns.

== Pass-through ==

If a ''To'' value is specified, but is not a valid user name, then the 
''PassThru'' key must be set to ''false'' or the mail may be rejected or
forwarded (depending on the system configuration).

=== JavaScript Variables ===

The filenames referenced below may all be modified or created by the mail processor.

Additional (read-only) variables available to JavaScript mail processors:

^ Variable                      ^ Description ^
| ''message_text_filename''	| filename contains complete message header and body |
| ''new_message_text_filename'' | completely new message header and body (optional) |
| ''recipient_list_filename''	| list of all SMTP recipients for this message (.ini format) |
| ''processing_error_filename''	| a filename that if created will reject this message with an SMTP error |
| ''log_text_filename''         | an optional filename that if created will include debug log output |
| ''hello_name''		| the "HELO" name specified by the sender during the SMTP session |
| ''sender_name''		| the name of the sender, possibly the same as the sender_address |
| ''sender_address''		| sender's email address (e.g. "user@domain.com") |
| ''reverse_path''		| sender's SMTP reverse-path from SMTP envelope (e.g. "<user@domain.com>") |
| ''recipient_address''		| last specified recipient in SMTP session (e.g. "you@your.host.com") |

* See ''[[dir:exec]]/mailproc_util.js'' and ''[[dir:exec]]/listserver.js'' for example uses.

JavaScript mail processors may be implemented as either a single "Eval"
string or an external JavaScript file (e.g. ''*.js'').

External JavaScript mail processors (''.js'' files) are loaded from the ''[[dir:mods]]''
or ''[[dir:exec]]'' directory if no path is specified on the command-line. 
If no file extension is specified on the command-line, ''.js'' is assumed.

=== Command-line Specifiers ===

Command-line specifiers (variables) are available for use in external mail processor command-lines:

^ Specifier ^ Description ^
| ''%m''    | mail message (header and body text) path/filename |
| ''%n''    | new message (header and body text) path/filename, in case you can't modify the original |
| ''%l''    | recipient list path/filename |
| ''%e''    | processing error path/filename (put error text in this file) |
| ''%d''    | processing debug log output path/filename |
| ''%h''    | sender's host name |
| ''%i''    | sender's IP address |
| ''%s''    | sender's name |
| ''%a''    | sender's address |
| ''%u''    | sender's user number (0 if unauthenticated) |
| ''%r''    | reverse path (of SMTP "envelope") |
| ''%t''    | recipient's address (from SMTP "envelope") |
| ''%!''    | exec dir |
| ''%g''    | temp dir |
| ''%j''    | data dir |
| ''%k''    | ctrl dir |
| ''%z''    | text dir |
| ''%o''    | sysop name | 
| ''%q''    | system QWK-ID |
| ''%v''    | Synchronet version |
| ''%?''    | platform |
| ''%%''    | percent symbol |

===== See Also =====
  * [[:faq:TCPIP|TCP/IP FAQ]]
  * [[:config:sbbs.ini]]
  * [[:config:domains.cfg]]
  * [[:config:mailproc.ini]]
  * [[:config:dns_blacklist.cfg]]
  * [[:config:dnsbl_exempt.cfg]]
  * [[:config:spambait.cfg]]
  * [[:config:spamblock.cfg]]
  * [[:config:spamblock_exempt.cfg]]
  * [[:config:twitlist.cfg]] 
  * [[:config:relay.cfg]]
  * [[:module:mailproc example|Example External Mail Processor (JavaScript)]]
  * [[:module:ListServer]]
  * [[:module:ListGate]]
  * [[:module:spamc]] 
  * [[:server:index|Servers]]

{{indexmenu_n>2}}

{{tag>email}}