E-Mail


Table of Contents


Electronic Mail (E-Mail) is a way to type letters onto a computer and send them to other people. These other people's computers will then use E-Mail to read your letters. It is an electronic version of the Post Office.

Dovecot - Presents E-Mails to Clients

Dovecot [1] provides a way for Mail User Agents (MUA) to manage their E-Mail. Typical MUAs are Thunderbird [2], Evolution [3], and Mutt [4].

Dovecot supports Internet Message Access Protocol (IMAP, port 993) [5] as a server over the network to multiple clients at the same time. It is commonly referred to as a Mail Delivery Agent (MDA) delivering mail from a file repository on some server to the MUA.

The Maildir database sets each E-Mail as a seperate file on the server, arranged into folders as dictated by the MUA. Indexing is automatic.

Postfix [6] is a Mail Transfer Agent (MTA) that receives E-Mail over the Internet using Simple Mail Transfer Protocol (SMTP, port 25 [7]) and delivers it locally to Dovecot. MUA sending is also done by postfix using Submission (ports 587 [8], and 465 for SSL [9]). Message relay from one mail server to another is done by postfix using SMTP too.

sequenceDiagram
    participant Thunderbird
    participant Dovecot
    participant Postfix
    Thunderbird->>Dovecot: Manage Mail (IMAP)
    Postfix->>Dovecot: Receive Mail
    Internet->>Postfix: Receive Mail (SMTP)
    Thunderbird->>Postfix: Send Mail (Submission)
    Postfix->>Internet: Send Mail (SMTP)
  1. https://www.dovecot.org/
  2. https://www.thunderbird.net/en-US/
  3. https://help.gnome.org/users/evolution/stable/
  4. http://www.mutt.org/
  5. https://www.rfc-editor.org/rfc/rfc9051
  6. http://www.postfix.org/
  7. https://www.rfc-editor.org/rfc/rfc5321.html
  8. https://datatracker.ietf.org/doc/html/rfc4409
  9. https://datatracker.ietf.org/doc/html/rfc8314

Installation

Install the four main packages:

  • core - core files
  • imapd - IMAP daemon
  • managesieved - ManageSieve server
  • sieve - Sieve filters support

Debian

$ sudo apt-get install dovecot-core dovecot-imapd dovecot-managesieved dovecot-sieve 

RedHat

$ sudo dnf install dovecot dovecot-pigeonhole

User Settings

Create a symbolic link for the mail location (~/Maildir) to an NFS mount that you created in the NAS page, such as /home/<user>/Maildir. This will provide the extra protection of ZFS for your E-Mail database, should a disk fail.

For instance, for NFS Mount at /media/share and Linux <user>@<domain>.com:

  • Create Linux user for E-Mail bob@example.com, and directory:
$ sudo useradd bob@example.com
$ sudo mkdir /home/bob@example.com
$ sudo chown bob@example.com  /home/bob@example.com
$ sudo mkdir -p /media/share/bob/Maildir
$ sudo chown -R bob@example.com  /media/share/bob
$ ln -s /media/share/bob/Maildir /home/bob@example.com 

Dovecot MUA logins are Linux logins. Multiple MUAs will log into Dovecot using different logins so ~/Maildir will also be different. Data will be stored on the /media/share NFS mount.

UserMaildir
bob/media/share/bob/Maildir -> /home/bob@example.com/Maildir
ted/media/share/ted/Maildir -> /home/ted@example.com/Maildir

Non-Default Settings

Create a configuration file that will override the default setting you want to change. Default settings are in directory: /etc/dovecot/conf.d/

File: /etc/dovecot/local.conf

# Hostname: mail
# Version: 21-Jan-2023
mail_fsync = always
mail_location = maildir:~/Maildir
mail_privileged_group = mail
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date index ihave duplicate mime foreverypart extracttext
mmap_disable = yes
namespace inbox {
  inbox = yes
  location = 
  mailbox Drafts {
    special_use = \Drafts
  }
  mailbox Junk {
    special_use = \Junk
  }
  mailbox Sent {
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
  mailbox Trash {
    special_use = \Trash
  }
  prefix = 
}
passdb {
  driver = pam
}
plugin {
  sieve = file:~/sieve;active=~/.dovecot.sieve
  sieve_default = /var/lib/dovecot/sieve/default.sieve
}
protocols = " imap sieve"
service auth {
  unix_listener /var/spool/postfix/private/auth {
    group = postfix
    mode = 0660
    user = postfix
  }
}
service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
service imap {
  process_limit = 1024
}
ssl_cert = </etc/letsencrypt/live/example.com/fullchain.pem
ssl_client_ca_dir = /etc/ssl/certs
ssl_dh = </etc/dovecot/dh.pem
ssl_key = </etc/letsencrypt/live/example.com/privkey.pem
userdb {
  driver = passwd
}
protocol lda {
  mail_plugins = " sieve"
}
protocol imap {
  mail_max_userip_connections = 1024
}

Update systemd startup service

Change systemd startup After dependencies to wait for the network to be online and NFS filesystem to be mounted.

$ sudo systemctl edit dovecot.service

Add these lines

#After=local-fs.target network-online.target
# Add fs-remote... Don - Jan 2023
[Unit]
After=syslog.target network-online.target local-fs.target remote-fs.target nss-lookup.target

This creates a new file to override the system defaults: /etc/systemd/system/dovecot.service.d/override.conf

Generate a file with Diffie-Hellman parameters

$ sudo openssl dhparam -dsaparam -out /etc/dovecot/dh.pem 2048

Depending on the hardware and entropy on the server, generating Diffie-Hellman parameters with 4096 bits can take several minutes.

Restart systemd and Dovecot to pick up changes:

$ sudo systemctl daemon-reload
$ sudo systemctl restart dovecot

Sieve - filters mail to certain boxes

Edit your rules.

File: /var/lib/dovecot/sieve/default.sieve

$ cat /var/lib/dovecot/sieve/default.sieve
require ["fileinto", "envelope"];
#if header  :contains "X-Spam-Flag" "YES"  {
if header :comparator "i;ascii-casemap" :contains "X-Spam-Flag" "YES"  {
    fileinto "INBOX.Spam";
    stop;
} elsif address :is "to" "bob@example.com" {
 fileinto "INBOX.Bob";
} elsif address :is "from" "logcheck@example.com" {
 fileinto "INBOX.Bob.logcheck";
} elsif header :contains "subject" ["Change to Camera"] {
 fileinto "INBOX.Camera";
} else {
 # The rest goes into INBOX
 # default is "implicit keep", we do it explicitly here
 keep;
}

Compile when done, then restart dovecot to pick up new changes

$ sudo sievec /var/lib/dovecot/sieve/default.sieve
$ sudo systemctl restart dovecot

Reference: https://doc.dovecot.org/configuration_manual/sieve/usage/

Postfix - sends and recieves e-mail over the network

Configuration - main

Create aliases to enable mail to go through from several standard unix accounts

seperate words with the TAB character, not spaces.

File: /etc/aliases

# See man 5 aliases for format
postmaster:    root
mail:	root
nobody:	root
monit:  root
clamav: root
logcheck: root

Update the aliases so postfix can read them

$ sudo newaliases

Unix account uses home_mailbox of ~/Maildir.

Reference: http://www.postfix.org/BASIC_CONFIGURATION_README.html

File: /etc/postfix/main.cf

# See /usr/share/postfix/main.cf.dist for a commented, more complete version
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

# misc
# only hostname
smtpd_banner = $myhostname ESMTP e-mail (Linux)
biff = no
# appending .domain is the MUA's job.
append_dot_mydomain = no
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
readme_directory = no

# alias
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases

# hosts
myhostname = www.example.com
myorigin = /etc/mailname
mydestination = example.com, example, localhost.localdomain, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.0.0/16

# mail box
home_mailbox = Maildir/
mailbox_size_limit = 0
message_size_limit = 52428800
header_size_limit = 4096000
recipient_delimiter = +
inet_interfaces = all
mailbox_command = /usr/lib/dovecot/deliver -c /etc/dovecot/dovecot.conf -m "${EXTENSION}"

# transport
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
compatibility_level = 2
inet_protocols = ipv4

# TLS parameters
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/example.com/fullchain.pem
smtpd_tls_key_file  = /etc/letsencrypt/live/example.com/privkey.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# No-IP - begin
# http://www.noip.com/support/knowledgebase/configure-postfix-work-alternate-port-smtp/
#debug_peer_list = 192.168.1.1
#
# sasl
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd
#
# relay
relayhost = [smtp-auth.no-ip.com]:465
relay_destination_concurrency_limit = 20	
relay_domains = $mydestination
#
# tls
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt
# No-IP - end

# sasl authentication
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_authenticated_header = yes
smtpd_sasl_local_domain = example.com

# Block spammers
smtpd_sender_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unknown_reverse_client_hostname, reject_unknown_client_hostname,
#
smtpd_client_restrictions = 
  check_client_access hash:/etc/postfix/blacklist
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
# block spammers...end

# TLS
smtpd_tls_received_header = yes
smtpd_tls_mandatory_protocols = SSLv3, TLSv1
smtpd_tls_mandatory_ciphers = medium
smtpd_tls_auth_only = yes

# CA
smtp_tls_CAfile = /etc/postfix/cacert.pem
tls_random_source = dev:/dev/urandom

# extra spam protection, 6-April-2019 : begin
smtpd_helo_required = yes
smtpd_helo_restrictions =
    permit_mynetworks
    permit_sasl_authenticated
# extra spam protection, 6-April-2019 : end

# address max connection rate  9-May-2019
smtpd_error_sleep_time = 1s
smtpd_soft_error_limit = 10
smtpd_hard_error_limit = 20

Configuration - Login

Change *'s to real passwords

File: /etc/postfix/sasl/sasl_passwd

[smtp-auth.no-ip.com]:465 example.com@noip-smtp:***************

Use the postmap command whenever you change the /etc/postfix/sasl/sasl_passwd file.

Reference: http://www.postfix.com/SASL_README.html

Create sasl_passwd database for postfix relay to nop-ip

$ sudo postmap /etc/postfix/sasl_passwd

# Protect the source file
$ sudo chown root:root /etc/postfix/sasl /etc/postfix/sasl/sasl_passwd
$ sudo chmod 0600      /etc/postfix/sasl /etc/postfix/sasl/sasl_passwd

# Protect the database file
$ sudo chown root:root /etc/postfix/sasl /etc/postfix/sasl/sasl_passwd.db
$ sudo chmod 0600      /etc/postfix/sasl /etc/postfix/sasl/sasl_passwd.db

Configuration - Master

Reference: http://www.postfix.org/master.5.html

Add smtp, smtps and submission internet services (smtpd) and spamassassin, dovecot local services (pipe) to the default master.cf file.

The -o lines override options in the main.cf file.

File: /etc/postfix/master.cf

# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
#............................................................................
# P O S T F I X
smtp       inet  n       -       y       -       -       smtpd -o content_filter=spamassassin
submission inet  n       -       y       -       -       smtpd
    -o smtpd_tls_security_level=encrypt
    -o smtpd_sasl_auth_enable=yes
    -o smtpd_sasl_type=dovecot
    -o smtpd_sasl_path=private/auth
    -o smtpd_sasl_security_options=noanonymous
    -o smtpd_sasl_local_domain=$myhostname
    -o smtpd_sender_login_maps=hash:/etc/postfix/virtual
smtps      inet  n       -       y       -       -       smtpd
    -o smtpd_tls_wrappermode=yes
    -o smtpd_sasl_auth_enable=yes
    -o milter_macro_daemon_name=ORIGINATING
#............................................................................
# S P A M A S S A S S I N
spamassassin unix -     n       n       -       -       pipe
  user=debian-spamd argv=/usr/bin/spamc -f -e  /usr/sbin/sendmail -oi -f ${sender} ${recipient}
#............................................................................
# D O V E C O T
dovecot   unix  -       n       n       -       -       pipe
 flags=DRhu user=mail:mail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${recipient} -a ${original_recipient}
#............................................................................
# M I S C
pickup     fifo  n       -       y       60      1       pickup
cleanup    unix  n       -       y       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       -       300     1       oqmgr
tlsmgr     unix  -       -       y       1000?   1       tlsmgr
rewrite    unix  -       -       y       -       -       trivial-rewrite
bounce     unix  -       -       y       -       0       bounce
defer      unix  -       -       y       -       0       bounce
trace      unix  -       -       y       -       0       bounce
verify     unix  -       -       y       -       1       verify
flush      unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
relay      unix  -       -       y       -       -       smtp
    -o smtp_fallback_relay=
showq      unix  n       -       y       -       -       showq
error      unix  -       -       y       -       -       error
retry      unix  -       -       y       -       -       error
discard    unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp       unix  -       -       y       -       -       lmtp
anvil      unix  -       -       y       -       1       anvil
#
scache     unix  -       -       y       -       1       scache
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}

Spamassasin - Puts SPAM into a SPAM folder automatically

Configure

Install

  • RedHat
dnf install spamassassin
  • Debian
apt-get install spamassassin spamc

Create a spam user, unless Debian/Ubuntu did this for you.

Check for spam user:

$ grep spam /etc/passwd
debian-spamd:x:135:140::/var/lib/spamassassin:/bin/sh

If no user exists yet, create one

$ adduser spamd --disabled-login

Config file

Be sure to set CRON=1 and allow IPv6.

  • Debian File: /etc/default/spamassassin
# /etc/default/spamassassin
# Duncan Findlay

# WARNING: please read README.spamd before using.
# There may be security risks.

# Prior to version 3.4.2-1, spamd could be enabled by setting
# ENABLED=1 in this file. This is no longer supported. Instead, please
# use the update-rc.d command, invoked for example as "update-rc.d
# spamassassin enable", to enable the spamd service.

# Options
# See man spamd for possible options. The -d option is automatically added.

# SpamAssassin uses a preforking model, so be careful! You need to
# make sure --max-children is not set to anything higher than 5,
# unless you know what you're doing.

#OPTIONS="--create-prefs --max-children 5 --helper-home-dir"
# Don 17-Jan-2022 - fix connection refused on ipv6
OPTIONS="-A 127.0.0.1 -A ::1 --create-prefs --max-children 5 --helper-home-dir"

# Pid file
# Where should spamd write its PID to file? If you use the -u or
# --username option above, this needs to be writable by that user.
# Otherwise, the init script will not be able to shut spamd down.
PIDFILE="/var/run/spamd.pid"

# Set nice level of spamd
#NICE="--nicelevel 15"

# Cronjob
# Set to anything but 0 to enable the cron job to automatically update
# spamassassin's rules on a nightly basis
CRON=1

All local customization happen in the next file.

I like to change the header to add the SPAM_SCORE, modify the original E-Mail with the new header information, and lower the threshold to mark as spam from 5 to 3.

  • RedHat File: /etc/mail/spamassassin/local.cf

  • Debian File: /etc/spamassassin/local.cf

# This is the right place to customize your installation of SpamAssassin.
#
# See 'perldoc Mail::SpamAssassin::Conf' for details of what can be
# tweaked.
#
# Only a small subset of options are listed below
#
###########################################################################

#   Add *****SPAM***** to the Subject header of spam e-mails
#
# rewrite_header Subject *****SPAM*****
# Don - b
rewrite_header Subject ***** SPAM _SCORE_ ***** 
# Don - e


#   Save spam messages as a message/rfc822 MIME attachment instead of
#   modifying the original message (0: off, 2: use text/plain instead)
#
# report_safe 1
# Don - b
report_safe 0
# Don - e


#   Set which networks or hosts are considered 'trusted' by your mail
#   server (i.e. not spammers)
#
# trusted_networks 212.17.35.


#   Set file-locking method (flock is not safe over NFS, but is faster)
#
# lock_method flock


#   Set the threshold at which a message is considered spam (default: 5.0)
#
# required_score 5.0
# Don -b
required_score 3.0
# Don -e


#   Use Bayesian classifier (default: 1)
#
# use_bayes 1
# Don -b
use_bayes 1
# Don -e


#   Bayesian classifier auto-learning (default: 1)
#
# bayes_auto_learn 1
# Don -b
bayes_auto_learn 1
# Don -e


#   Set headers which may provide inappropriate cues to the Bayesian
#   classifier
#
# bayes_ignore_header X-Bogosity
# bayes_ignore_header X-Spam-Flag
# bayes_ignore_header X-Spam-Status


#   Whether to decode non- UTF-8 and non-ASCII textual parts and recode
#   them to UTF-8 before the text is given over to rules processing.
#
# normalize_charset 1

#   Textual body scan limit    (default: 50000)
#
#   Amount of data per email text/* mimepart, that will be run through body
#   rules.  This enables safer and faster scanning of large messages,
#   perhaps having very large textual attachments.  There should be no need
#   to change this well tested default.
#
# body_part_scan_size 50000

#   Textual rawbody data scan limit    (default: 500000)
#
#   Amount of data per email text/* mimepart, that will be run through
#   rawbody rules.
#
# rawbody_part_scan_size 500000

#   Some shortcircuiting, if the plugin is enabled
# 
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
#
#   default: strongly-whitelisted mails are *really* whitelisted now, if the
#   shortcircuiting plugin is active, causing early exit to save CPU load.
#   Uncomment to turn this on
#
#   SpamAssassin tries hard not to launch DNS queries before priority -100. 
#   If you want to shortcircuit without launching unneeded queries, make
#   sure such rule priority is below -100. These examples are already:
#
# shortcircuit USER_IN_WHITELIST       on
# shortcircuit USER_IN_DEF_WHITELIST   on
# shortcircuit USER_IN_ALL_SPAM_TO     on
# shortcircuit SUBJECT_IN_WHITELIST    on

#   the opposite; blacklisted mails can also save CPU
#
# shortcircuit USER_IN_BLACKLIST       on
# shortcircuit USER_IN_BLACKLIST_TO    on
# shortcircuit SUBJECT_IN_BLACKLIST    on

#   if you have taken the time to correctly specify your "trusted_networks",
#   this is another good way to save CPU
#
# shortcircuit ALL_TRUSTED             on

#   and a well-trained bayes DB can save running rules, too
#
# shortcircuit BAYES_99                spam
# shortcircuit BAYES_00                ham

endif # Mail::SpamAssassin::Plugin::Shortcircuit

These next SPAM settings to the /etc/postfix/master.cf were also shown above, so just repeating here for clarity.

File: /etc/postfix/master.cf

=> Then we need to find the following line and add the spamassassin filter:
~
smtp      inet  n       -       -       -       -       smtpd
-o content_filter=spamassassin
~

=> Finally we need to append the following parameters:
~
spamassassin unix -     n       n       -       -       pipe
user=spamd argv=/usr/bin/spamc -f -e
/usr/sbin/sendmail -oi -f ${sender} ${recipient}
~

Start spamassassin and restart postfix

IMPORTANT: Spamassassin must connect to the network to complete initialization, but during reboot the network is not fully up and DNS resolvable, so we need to force a wait in the systemd service script for spamassassin.

Replace 'ExecStartPre' with the bash line below. - and - Replace 'After' to add dependency on network and nslookup working

File: /lib/systemd/system/spamassassin.service

~
[Unit]
# Depend on: online, remote, nss...
After=syslog.target network-online.target remote-fs.target nss-lookup.target
~
[Service]
# Wait for dns resolver
ExecStartPre=/bin/bash -c 'until host google.com; do sleep 1; done'
~

Now restart systemd, spamassassin and postfix to pick up new configuration changes.

$ sudo systemctl daemon-reload
$ sudo systemctl restart spamassassin
$ sudo systemctl restart postfix

Daily update in /etc/cron.daily

This is to update the spam databases from the internet

FYI: Check the file in /etc/cron.daily for the scheduled entry

$ cat /etc/cron.daily/spamassassin
#!/bin/bash
# -v verbose
# -D debug
/bin/sa-update -v -D

Put spam/ham learning into a script

If you find spam in your inbox, move it to the SPAM folder and the sa-learn command will update the local learning. Conversely, if you find good E-Mail in the SPAM folder, move it your your INBOX and the next learning cycle will mark it as good E-Mail (ham).

In the next script, change to your Maildir directory, and add/delete E-Mail folders as required for spam and ham actions.

Reference: https://spamassassin.apache.org/doc.html

File: /home/bob/spam

$ cat spam
HOME=/home/bob
# https://spamassassin.apache.org/full/3.1.x/doc/sa-learn.html
sa-learn -u debian-spamd --backup >/tmp/spam.bkup
sa-learn -u debian-spamd --no-sync --spam $HOME/Maildir/.Junk/{cur,new}
sa-learn -u debian-spamd --no-sync --spam $HOME/Maildir/.Junk\ E-mail/{cur,new}
sa-learn -u debian-spamd --no-sync --ham  $HOME/Maildir/.INBOX.Bob/{cur,new}
sa-learn -u debian-spamd --sync
sa-learn -u debian-spamd --dump magic

Now schedule the spam local learning. Create this script and put in in ```/etc/cron.daily`` so it will run once a day.

File: /etc/cron.daily/spam

#!/bin/bash
DIR=/tmp
RESULT=${DIR}/spam.txt
/home/bob/spam >${RESULT}
if [ ! -s "${RESULT}" ]; then
  rm ${RESULT}
else
  cat ${RESULT} | mail -s "Spam refresh" bob@example.com 2>/dev/null
fi

Mail Readers

Mutt

Mutt [1] is a text only e-mail reader, capable of running over an ssh connection.

mutt_index.gif

Install

$ sudo apt-get install mutt

Configure

Global options are in file /etc/Muttrc. User options are in file: ~/.muttrc

Assuming your local maildir is in /backup/Maildir...

source ~/.mutt/mailboxes
folder-hook Home set from="bob@example.com"
#folder-hook Work set from="youremail@work.com"
set mbox_type=Maildir
set folder="/backup/Maildir/Home"
set mask="!^\\.[^.]"
set mbox="/backup/Maildir/Home"
set record="+.Sent"
set postponed="+.Drafts"
set spoolfile="/backup/Maildir/Home/.INBOX"

If your mail server is over a network, use this configuration

#    Tell mutt to use your IMAP INBOX as your $spoolfile: set spoolfile=imap://hostname/INBOX
#    Set your $folder to your IMAP root: set folder=imap://hostname/
# activate TLS if available on the server
set ssl_starttls=yes
# always use SSL when connecting to a server
set ssl_force_tls=yes

set spoolfile   = imaps://example.org:993/INBOX
set folder      = imaps://example.org:993/
set imap_user   = bob@example.org
set imap_pass   = abcdIfYouSeeMe1234
set spoolfile   = +INBOX
mailboxes       = +INBOX
set smtp_url    = smtps://bob:abcdIfYouSeeMe1234@example.org:25

# Refresh new messages
set mail_check = 3

# Store message headers locally to speed things up.
# If hcache is a folder, Mutt will create sub cache folders for each account which may speeds things
set header_cache = ~/.cache/mutt

# Store messages locally to speed things up, like searching message bodies.
# Can be the same folder as header_cache.
# This will cost important disk usage according to your e-mail amount.
set message_cachedir = "~/.cache/mutt"

# Specify where to save and/or look for postponed messages.
set postponed = +Drafts

# Allow Mutt to open a new IMAP connection automatically.
unset imap_passive

# Keep the IMAP connection alive by polling intermittently (time in seconds).
set imap_keepalive = 300

# How often to check for new mail (time in seconds).
set mail_check = 120
  1. http://www.mutt.org/

Evolution

Evolution [1] is a Graphical User Interface (GUI) mail reader, the best one for Linux desktop.

evolution_window-overview-layers.png
evolution_legend.png

Install

$ sudo apt-get install evolution

Configure

Launch the application and configure the receiving (IMAPS), sending server(SMTP) and options like timezone.

  1. https://help.gnome.org/users/evolution/stable/

Thunderbird

Thunderbird [1] is a GUI mail reader, the best one for MacOS or Windows.

Thunderbird-email.png

Install

$ sudo apt-get install thunderbird

Configure

Launch the application and configure the receiving (IMAPS), sending server(SMTP) and options like timezone.

  1. https://www.thunderbird.net/en-US/

Offlineimap - Makes a backup copy of all email

OfflineIMAP [1] will save a workable entire E-Mail clone in case of total loss on the E-Mail server. You can even run Evolution/Thunderbird/mutt on the new remote server.

Install

$ sudo apt-get install offlineimap

Configure

If you run IMAPS, get your cert_fingerprint using the following on the E-Mail server:

$ grep -v ^- /etc/letsencrypt/live/example.com/cert.pem | base64 -d | sha1sum

Create the .offlineimaprc file in your $HOME directory (~) on the remote host, and change things like localfolders, remotehost, remoteuser, remotepass, and cert_fingerprint.

File: ~/.offlineimaprc

# Sample minimal config file.  Copy this to ~/.offlineimaprc and edit to
# get started fast.
# sha1 fingerprint:
# grep -v ^- cert.pem  | base64 -d | sha1sum

[general]
accounts = Home

[Account Home]
localrepository = LocalHome
remoterepository = RemoteHome

[Repository LocalHome]
type = Maildir
localfolders = /backup/Maildir/Home

# Translate your maildir folder names to the format the remote server expects
# So this reverses the change we make with the remote nametrans setting
nametrans = lambda name: re.sub('^\.', '', name)


[Repository RemoteHome]
type = IMAP
remotehost = example.com
remoteuser = mail
remotepass = *************
# openssl_sha1
cert_fingerprint = *************************************
# Need to exclude '' otherwise it complains about infinite naming loop?
folderfilter = lambda foldername: foldername not in ['']
# For Dovecot to see the folders right I want them starting with a dot,
# and dovecot set to look for .INBOX as the toplevel Maildir
nametrans = lambda name: '.' + name

[mbnames]
enabled = yes
filename = ~/.mutt/mailboxes
header = "mailboxes "
peritem = "+%(accountname)s/%(foldername)s"
sep = " "
footer = "\n"

Reference: https://blog.wikichoon.com/2017/05/configuring-offlineimap-dovecot.html

Create a script to run it on remote host

File: ~/offlineimap.sh

#!/bin/bash
export HOME=/home/bob
LOGFILE=/var/log/offlineimap.log
if [ -d ~/Maildir ]; then
  /usr/bin/date > $LOGFILE
  /usr/bin/offlineimap >> $LOGFILE 2>&1
  /usr/bin/date >> $LOGFILE
fi

Schedule

Schedule the script to run on the remote host

File: /etc/cron.d/offlineimap

# This is a cron file for offlineimap
# 
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
MAILTO="bob@example.com"
# m h  dom mon dow user  command
33  *  *   *   *   bob   /home/bob/offlineimap.sh
  1. http://www.offlineimap.org/

Postfix Log Summary

Pflogsumm is a log analyzer/summarizer for the Postfix MTA. It is designed to provide an over-view of Postfix activity. Pflogsumm generates summaries and, in some cases, detailed reports of mail server traffic volumes, rejected and bounced email, and server warnings, errors and panics.

Install

  • Debian
$ sudo apt-get install pflogsumm
  • RedHat
$ sudo dnf install postfix-perl-scripts

Schedule

Create a script in /etc/cron.daily to run it, like this:

  • Debian
/usr/sbin/pflogsumm -d yesterday /var/log/mail.log --problems-first --rej-add-from --verbose-msg-detail | /usr/bin/mail -s "`uname -n` daily mail stats" me@example.com
  • RedHat
/usr/sbin/pflogsumm -d yesterday /var/log/maillog --problems-first --rej-add-from --verbose-msg-detail | /usr/bin/mail -s "`uname -n` daily mail stats" me@example.com

Alternatives

exim4

Exim (Experimental Internet Mailer) [1] receives and sends mail, referred to as an MTA like postfix. It does not provide POP or IMAP interfaces to read mail. It is available on most Linux distributions as a package install, but was removed from RedHat due to low populatity.

What it does

  • RFC 2821 SMTP and RFC 2033 LMTP email message transport.

  • Incoming (as SMTP server):

    • SMTP over TCP/IP (Exim daemon or inetd);
    • SMTP over the standard input and output (the -bs option);
    • Batched SMTP on the standard input (the -bS option).
  • Exim also supports RFC 5068 Message Submission, as an SMTP server with (for example, encrypted and authenticated connections on port 587).

  • Outgoing email (as SMTP or LMTP client):

    • SMTP over TCP/IP (the smtp transport);
    • LMTP [2] over TCP/IP (the smtp transport with the protocol option set to “lmtp”);
    • LMTP over a pipe to a process running in the local host (the lmtp transport);
    • Batched SMTP to a file or pipe (the appendfile and pipetransports with the use_bsmtp option set).
  • Configuration

    • Access Control Lists - flexible policy controls.
    • Content scanning, including easy integration with and other spam and virus scanners like SpamAssassin and ClamAV.
    • Encrypted SMTP connections using TLS/SSL.
    • Authentication with a variety of front end and back end methods, including PLAIN, LOGIN, sasl, dovecot, spa, cram_md5.
    • Rewrite - rewrite envelope and/or header addresses using regular expressions.
    • Routing controls - use routers to redirect, quarantine, or deliver messages.
    • Transports - use transports to deliver messages by smtp, lmtp, or to files, directories, or other programs.
    • Flexible retry rules for temporary delivery problems.

I usually install it on non-email Debian servers because it is very light weight and works great sending monitoring messages from servers to the main E-Mail server [3].

Pros:

  • Small footprint is able to run on SBC like Rasberry PI
  • Simple configuration on Debian only
  • Extendable

Cons:

  • Only MTA, does not support mailboxes without an MDA like Dovecot
  • Not as well known as postfix, probably not as many people or businesses supporting it
  • Not available on RedHat mainstream, Postfix and Sendmail are the only alternative
  1. https://www.exim.org/docs.html
  2. Local Mail Transfer Protocol
  3. Setup_Server

iRedMail

With iRedMail [1], you can deploy an OPEN SOURCE, FULLY FLEDGED, FULL-FEATURED mail server in several minutes, for free.

It supports all major Linux distributions, has calendar/contact sync,antispam/anitvirus protection, TLS security and webmail locally on your server. This would replace the Dovecot/postfix combination described above.

Read the documentation [2] and decide for yourself. This takes over a host, installing many different products, like database (mySQL/PostgreSQL,LDAP), DKIM, Spam filter, fail2ban, netdata, postfix, Dovecot, webmail, etc. You will need about 4GB of memory and a couple CPUs along with 20GB disk.

Pros:

  • multiple E-Mail domains
  • multiple E-Mail accounts
  • Nice GUI for managing the E-Mail accounts
  • Includes massive system monitor, netdata [3]
  • You can buy support

Cons:

  • Need a bigger, dedicated machine to host it
  • Puts much of the configuration inside a database
  • Not well suited for small setup at home, due to the complexity
  1. https://www.iredmail.org/
  2. https://docs.iredmail.org/index.html
  3. https://www.netdata.cloud/

Mail-in-a-Box

Technically, Mail-in-a-Box [1] turns a fresh cloud computer into a working mail server. But you don’t need to be a technology expert to set it up.

Each Mail-in-a-Box provides webmail and an IMAP/SMTP server for use with mobile devices and desktop mail software. It also includes contacts and calendar synchronization.

This project provides a simple, turn-key solution. There are basically no configuration options and you can’t tweak the machine’s configuration files after installation.

My observation is that this is good for a dedicated mail server machine, and that's all that machine should do. Perhaps it would work well on a Rasberry PI SBC.

Pros:

  • Do not need to know all the technical details of E-Mail to setup and use
  • Small system requirements, runable on a SBC

Cons:

  • Requires dedicated machine, as it takes over
  • Not sure how well support will be, especially for critital systems
  1. https://mailinabox.email/

Citadel

This open source project provides "Email, collaboration, groupware, and content management - up and running in minutes, on your own hardware or in the cloud."

Citadel is groupware with BBS roots, and still offers a traditional text-based BBS front end and chat. If you like old school, this is for you.

To find out more, just read the FAQS [2]. Looks interesting to me, at least one person posted about running it on a Rasberry PI [3].

Pros:

  • Do not need to know all the technical details of E-Mail to setup and use
  • Small system requirements, runable on a SBC

Cons:

  • Does more than E-Mail, you may not need all the features installed
  • Not sure how well support will be, especially for critital systems
  1. https://www.citadel.org/
  2. https://www.citadel.org/faq.html
  3. https://www.ionos.com/digitalguide/server/configuration/set-up-your-own-raspberry-pi-mail-server/

Continue

Now that you have set up E-Mail on your server, you will need a Database for many more things, so now is a good time to install the versatile PostgreSQL database.

Proceed in the order presented, some things are depending on prior setups.

Book Last Updated: 29-March-2024



E-Mail - Linux in the House - https://linux-in-the-house.org Creative Commons License