This is the multi-page printable view of this section.
Click here to print.
Return to the regular view of this page.
Email
Email is a commodity service, but critical for many things - so you can get it anywhere, but you better not mess it up.
Your options, in increasing order of complexity, are:
Forwarding
Email sent to [email protected] is simply forwarded to someplace like gmail. It’s free and easy, and you don’t need any infrastructure. Most registrars like GoDaddy, NameCheap, CloudFlare, etc, will handle it.
You can even reply from [email protected] by integrating with SendGrid or a similar provider.
Remote-Hosting
If you want more, Google and Microsoft have full productivity suites. Just edit your DNS records, import your users, and pay them $5 a head per month. You still have to ‘do email’ but it’s a little less work than if you ran the whole stack. In most cases, companies that specialize in email do it better than you can.
Self-Hosting
If you are considering local email, let me paraphrase Kenji López-Alt. The first step is, don’t. The big guys can do it cheaper and better. But if it’s a philosophical, control, or you just don’t have the funding, press on.
A Note About Cost
Most of the cost is user support. Hosting means someone else gets purchase and patch a server farm, but you still have to talk to users. My (anecdotal) observation is that fully hosting saves 10% in overall costs and it soothes out expenses. The more users you have, the more that 10% starts to matter.
1 - Forwarding
This is the best solution for a small number of users. You configure it at your registrar and rely on google (or someone similar) to do all the work for free.
If you want your out-bound emails to come from your domain name (and you do), add an out-bound relay. This is also free for minimal use.
Registrar Configuration
This is different per registrar, but normally involves creating an address and it’s destination
Cloudflare
- (Login - assumes you use cloudflare as your registrar)
- Login and select the domain in question.
- Select Email, then Email Routing.
- Under Routes, select Create address.
Once validated, email will begin arriving at the destination.
The registrars is only forwarding email, not sending it. To get your sent mail to from from your domain, you must integrate with a mail service such as SendGrid
SendGrid
- Create a free account and login
- Authenticate your domain name (via DNS)
- Create an API key (Settings -> API Keys -> Restricted Access, Defaults)
Gmail
- Settings -> Accounts -> Send Mail as
- Add your domain email
- Configure the SMTP server with:
- SMTP server: “smtp.sendgrid.net”
- username: “apikey”
- password: (the key you created above)
After validating the code Gmail sends you, there will be a drop down in the From field of new emails.
2 - Remote Hosting
This is more in the software-as-a-service category. You get an admin dashboard and are responsible for managing users and mail flow. The hosting service provide will help you with basic things, but you’re doing most of the work yourself.
Having manged 100K+ user mail systems and migrated from on-prem sendmail to exchange and then O365 and Google, I can confidently say the infrastructure and even platform amounts to less than 10% of the cost of providing the service.
The main advantage to hosting is that you’re not managing the platform, installing patches and replacing hardware. The main disadvantage is is that you have little control and sometimes things are broken and you can’t do anything about it.
Medium sized organizations benefit most from hosting. You probably need a productivity suite anyways, and email is usually wrapped up in that. It saves you from having to specialize someone in email and the infrastructure associated with it.
But if controlling access to your data is paramount, then be aware that you have lost that and treat email as a public conversation.
3 - Self Hosting
When you self-host, you develop expertise in email itself, arguably a commodity service where such expertise has small return. But, you have full control and your data is your own.
The generally accepted best practice is install Postfix and Dovecot. This is the simplest path and what I cover here. But there are some pretty decent all-in-one packages such as Mailu, Modoboa, etc. These usually wrap Postfix and Dovecot to spare you the details and improve your quality of life, at the cost of not really knowing how they really work.
You’ll also need to configure a relay. Many ISPs block basic mail protocol and many recipient servers are rightly suspicious of random emails from unknown IPs in cable modem land.
- Postfix
- Dovecot
- Relay
3.1 - Postfix
This is the first step - a server that handles and stores email. You’ll be able to check messages locally at the console. (Remote client access such as with Thunderbird comes later.)
Preparation
You need:
- Linux Server
- Firewall Port-Forward
- Public DNS
Server
We use Debian Bookworm (12) in this example but any derivative will be similar. At large scale you’d setup virtual users, but we’ll stick with the default setup and use your system account. Budget about 10M per 100 emails stored.
Port Forwarding
Mail protocol uses port 25. Simply forward that to your internal mail server and you’re done.
DNS
You need an normal ‘A’ record for your server and a special ‘MX’ record for your domain root. That way, mail sent to [email protected] will get routed to the server.
Name |
Type |
Value |
the-server |
A |
20.236.44.162 |
@ |
MX |
the-server |
Mail servers see [email protected] and look for records of type ‘MX’ for ‘your.org’. Seeing that ’the-server’ is listed, they lookup it’s ‘A’ record and connect. A message to [email protected] is handled the same way, though when there is no ‘MX’ record it just delivers it to the ‘A’ record for ’the-server.your.org’. If you have both, the ‘MX’ takes precedence.
Installation
Some configuration is done at install time by the package so you must make sure your hostname is correct. We use the hostname ‘mail’ in this example.
# Correct internal hostnames as needed. 'mail' and 'mail.home.lan' are good suggestions.
cat /etc/hostname /etc/hosts
# Set the external host name and run the package installer. If postfix is already installed, apt remove it first
EXTERNAL="mail.your.org"
sudo debconf-set-selections <<< "postfix postfix/mailname string $EXTERNAL"
sudo debconf-set-selections <<< "postfix postfix/main_mailer_type string 'Internet Site'"
sudo apt install --assume-yes postfix
# Add the main domain to the destinations as well
DOMAIN="your.org"
sudo sed -i "s/^mydestination = \(.*\)/mydestination = $DOMAIN, \1/" /etc/postfix/main.cf
sudo systemctl reload postfix.service
Test with telnet - use your unix system ID for the rcpt address below.
ehlo localhost
mail from: <[email protected]>
rcpt to: <[email protected]>
data
Subject: Wish List
Red Ryder BB Gun
.
quit
Assuming that ‘you’ matches your shell account, Postfix will have accepted the message and used it’s Local Delivery Agent to store it in the local message store. That’s in /var/mail
.
Configuration
Encryption
Postfix will use the untrusted “snakeoil” that comes with debian to opportunistically encrypt communication between it and other mail servers. Surprisingly, most other servers will accept this cert (or fall back to non-encrypted), so lets proceed for now. We’ll generate a trusted one later.
Spam Protection
The default config is secured so that it won’t relay messages, but it will accept message from Santa, and is subject to backscatter and a few other things. Let’s tighten it up.
sudo tee -a /etc/postfix/main.cf << EOF
# Tighten up formatting
smtpd_helo_required = yes
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
# Error codes instead of bounces
invalid_hostname_reject_code = 554
multi_recipient_bounce_reject_code = 554
non_fqdn_reject_code = 554
relay_domains_reject_code = 554
unknown_address_reject_code = 554
unknown_client_reject_code = 554
unknown_hostname_reject_code = 554
unknown_local_recipient_reject_code = 554
unknown_relay_recipient_reject_code = 554
unknown_virtual_alias_reject_code = 554
unknown_virtual_mailbox_reject_code = 554
unverified_recipient_reject_code = 554
unverified_sender_reject_code = 554
EOF
sudo systemctl reload postfix.service
PostFix has some recommendations as well.
sudo tee -a /etc/postfix/main.cf << EOF
# PostFix Suggestions
smtpd_helo_restrictions = reject_unknown_helo_hostname
smtpd_sender_restrictions = reject_unknown_sender_domain
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination,
reject_rbl_client zen.spamhaus.org,
reject_rhsbl_reverse_client dbl.spamhaus.org,
reject_rhsbl_helo dbl.spamhaus.org,
reject_rhsbl_sender dbl.spamhaus.org
smtpd_relay_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination
smtpd_data_restrictions = reject_unauth_pipelining
EOF
sudo systemctl reload postfix.service
If you test a message from Santa now, Postfix will do some checks and realize it’s bogus.
550 5.7.27 [email protected]: Sender address rejected: Domain northpole.org does not accept mail (nullMX)
Postfix will attach a Received: header to outgoing emails that has details of your internal network and mail client. That’s information you don’t need to broadcast. You can remove that with a “cleanup” step as the message is sent.
# Insert a header check after the 'cleanup' line in the smtp section of the master file and create a header_checks file
sudo sed -i '/^cleanup.*/a\\t-o header_checks=regexp:/etc/postfix/header_checks' /etc/postfix/master.cf
echo "/^Received:/ IGNORE" | sudo tee -a /etc/postfix/header_checks
Note - there is some debate on if this triggers a higher spam score. You may want to replace instead.
Testing
Incoming
You can now receive mail to [email protected]
and [email protected]
. Try this to make sure you’re getting messages. Feel free to install mutt
if you’d like a better client at the console.
Outgoing
You usually can’t send mail and there are several reasons why.
Many ISPs block outgoing port 25 to keep a lid on spam bots. This prevents you from sending any messages. You can test that by trying to connect to gmail on port 25 from your server.
nc -zv gmail-smtp-in.l.google.com 25
Also, many mail servers will reverse-lookup your IP to see who it belongs to. That request will go to your ISP (who owns the IPs) and show their DNS name instead of yours. You’re often blocked at this step, though some providers will work with you if you contact them.
Even if you’re not blocked and your ISP has given you a static IP with a matching reverse-lookup, you will suffer from a lower reputation score as you’re not a well-known email provider. This can cause your sent messages to be delayed while being considered for spam.
To solve these issues, relay your email though a email provider. This will improve your reputation score (used to judge spam), ease the additional security layers such as SPF, DKIM, DMARC, and is usually free at small volume.
Postfix even calls this using a ‘Smarthost’
Next Steps
Now that you can get email, let’s make it so you can also send it.
Troubleshooting
When adding Postfix’s anti-spam suggestions, we left off the smtpd_client_restrictions and smtpd_end_of_data_restrictions as they created problems during testing.
You may get a warning from Postfix that one of the settings you’ve added is overriding one of the earlier settings. Simply delete the first instance. These are usually default settings that we’re overriding.
Use ‘@’ to view the logs from all the related services.
If you change your server’s DNS entry, make sure to update mydestination
in your /etc/postfix/main.cf
and sudo systemctl reload [email protected]
.
Misc
Mail Addresses
Postfix only accepts messages for users in the “local recipient table” which is built from the unix password file and the aliases file. You can add aliases for other addresses that will deliver to your shell account, but only shell users can receive mail right now. See virtual mailboxes to add users without shell accounts.
In the alias file, you’ll see “Postmaster” (and possibly others) are aliased to root. Add root as an alias to you at the bottom so that mail gets to your mailbox.
echo "root: $USER" | sudo tee -a /etc/aliases
sudo newaliases
3.2 - Relay
A relay is simply another mail server that you give your outgoing mail to, rather than try to deliver it yourself.
There are many companies that specialize in this. Sign up for a free account and they give you the block of text to add to your postfix config. Some popular ones are:
- SendGrid
- MailGun
- Sendinblue
They allow anywhere between 50 and 300 a day for free.
SendGrid
Relay Setup
SendGrid’s free plan gives you 50 emails a day. Create an account, verify your email address ([email protected]), and follow the instructions. Make sure to sudo apt install libsasl2-modules
https://docs.sendgrid.com/for-developers/sending-email/postfix
Restart Postfix and use mutt to send an email. It works! the only thing you’ll notice is that your message has a “On Behalf Of” notice in the message letting you know it came from SendGrid. Follow the section below to change that.
Domain Integration
To integrate your domain fully, add DNS records for SendGrid using these instructions.
https://docs.sendgrid.com/ui/account-and-settings/how-to-set-up-domain-authentication
This will require you to login and go to:
- Settings -> Sender Authentication -> Domain Authentication
Stick with the defaults that include automatic security and SendGrid will give you three CNAME records. Add those to your DNS and your email will check out.
Technical Notes
DNS
If you’re familiar with email domain-based security, you’ll see that two of the records SendGrid gives you are links to DKIM keys so SendGrid can sign emails as you. The other record (emXXXX) is the host sendgrid will use to send email. The SPF record for that host will include a SendGrid SPF record that includes multiple pools of IPs so that SPF checks will pass. They use CNAMEs on your side so they can rotate keys and pool addresses without changing DNS entries.
If none of this makes sense to you, then that’s really the point. You don’t have to know any of it - they take care of it for you.
Next Steps
Your server can now send email too. All shell users on your sever rejoice!
To actually use your mail server, you’ll want to add some remote client access.
3.3 - Dovecot
Dovecot is an IMAP (Internet Message Access Protocol) server that allows remote clients to access their mail. There are other protocols and servers, but Dovecot has about 75% of the internet and is a good choice.
Installation
sudo apt install dovecot-imapd
sudo apt install dovecot-submissiond
Configuration
Storage
Both Postfix and Dovecot use mbox storage format by default. This is one big file with all your mail in it and doesn’t scale well. Switch to the newer maildir format where your messages are stored as individual files.
# Change where Postfix delivers mail.
sudo postconf -e "home_mailbox = Maildir/"
sudo systemctl reload postfix.service
# Change where Dovecot looks for mail.
sudo sed -i 's/^mail_location.*/mail_location = maildir:~\/Maildir/' /etc/dovecot/conf.d/10-mail.conf
sudo systemctl reload dovecot.service
Encryption
Dovecot comes with it’s own default cert. This isn’t trusted, but Thunderbird will prompt you and you can choose to accept it. This will be fine for now. We’ll generate a valid cert later.
Credentials
Dovecot checks passwords against the local unix system by default and no changes are needed.
Submissions
One potential surprise is that IMAP is only for viewing existing mail. To send mail, you use the SMTP protocol and relay messages to your mail server. But we have relaying turned off, as we don’t want just anyone relaying messages.
The solution is to enable authentication and by convention this is done by a separate port process, called the Submission Server.
We’ve installed Dovecot’s submission server as it’s newer and easier to set up. Postfix even suggests considering it, rather than theirs. The only configuration needed it to set the localhost as the relay.
# Set the relay as localhost where postfix runs
sudo sed -i 's/#submission_relay_host =/submission_relay_host = localhost/' /etc/dovecot/conf.d/20-submission.conf
sudo systemctl reload dovecot.service
Port Forwarding
Forward ports 143 and 587 to your mail server and test that you can connect from both inside and outside your LAN.
nc -zf mail.your.org 143
nc -zf mail.your.org 587
If it’s working from outside your network, but not inside, you may need to enable [reflection] aka hairpin NAT. This will be different per firewall vendor, but in OPNSense it’s:
Firewall -> Settings -> Advanced
# Enable these settings
Reflection for port forwards
Reflection for 1:1
Automatic outbound NAT for Reflection
Clients
Thunderbird and others will successfully discover the correct ports and services when you provide your email address of [email protected]
.
Notes
TLS
Dovecot defaults to port 587 for the submission service which is an older standard for explicit TLS. It’s now recommended by RFC to use implicit TLS on port 465 and you can add a new “submissions” service for that, while leaving the default in place. Clients will pick their fav. Thunderbird defaults to the 465 when both are available.
Note: leaving the default sumbission port commented out just means it will use the default port. Comment out the whole block to disable.
vi /etc/dovecot/conf.d/10-master.conf
# Change the default of
service submission-login {
inet_listener submission {
#port = 587
}
}
to
service submission-login {
inet_listener submission {
#port = 587
}
inet_listener submissions {
port = 465
ssl = yes
}
}
# And reload
sudo systemctl reload dovecot.service
Make sure to port forward 465 at the firewall as well
Next Steps
Now that you’ve got the basics working, let’s secure things a little more
Sources
https://dovecot.org/list/dovecot/2019-July/116661.html
3.4 - Security
Certificates
We should use valid certificates. The best way to do that is with the certbot
utility.
Certbot
Certbot automates the process of getting and renewing certs, and only requires a brief connection to port 80 as proof it’s you. There’s also a DNS based approach, but we use the port method for simplicity. It only runs once every 60 days so there is little risk of exploit.
Forward Port 80
You probably already have a web server and can’t just change where port 80 goes. To integrate certbot, add a name-based virtual host proxy to that web server.
# Here is a caddy example. Add this block to your Caddyfile
http://mail.your.org {
reverse_proxy * mail.internal.lan
}
# You can also use a well-known URL if you're already using that vhost
http://mail.your.org {
handle /.well-known/acme-challenge/ {
reverse_proxy mail.internal.lan
}
}
Install Certbot
Once the port forwarding is in place, you can install certbot and use it to request a certificate. Note the --deploy-hook
argument. This reloads services after a cert is obtained or renewed. Else, they’ll keep using an expired one.
DOMAIN=your.org
sudo apt install certbot
sudo certbot certonly --standalone --domains mail.$DOMAIN --non-interactive --agree-tos -m postmaster@$DOMAIN --deploy-hook "service postfix reload; service dovecot reload"
Once you have a cert, Certbot will keep keep it up-to-date by launching periodically from a cronjob in /etc/cron.d
and scanning for any needed renewals.
Postfix
Tell Postfix about the cert by using the postconf utility. This will warn you about any potential configuration errors.
sudo postconf -e 'smtpd_tls_cert_file = /etc/letsencrypt/live/mail.$DOMAIN/fullchain.pem'
sudo postconf -e 'smtpd_tls_key_file = /etc/letsencrypt/live/mail.$DOMAIN/privkey.pem'
sudo postfix reload
Dovecot
Change the Dovecot to use the cert as well.
sudo sed -i 's/^ssl_cert = .*/ssl_cert = <\/etc\/letsencrypt\/live\/mail.$DOMAIN\/fullchain.pem/' /etc/dovecot/conf.d/10-ssl.conf
sudo sed -i 's/^ssl_key = .*/ssl_key = <\/etc\/letsencrypt\/live\/mail.$DOMAIN\/privkey.pem/' /etc/dovecot/conf.d/10-ssl.conf
sudo dovecot reload
Verifying
You can view the certificates with the commands:
openssl s_client -connect mail.$DOMAIN:143 -starttls imap -servername mail.$DOMAIN
openssl s_client -starttls smtp -showcerts -connect mail.$DOMAIN:587 -servername mail.$DOMAIN
Privacy and Anti-Spam
You can take advantage of Cloudflare (or other) services to accept and inspect your email before forwarding it on to you. As far as the Internet is concerned, Cloudflare is your email server. The rest is private.
Take a look at the Forwarding section, and simply forward your mail to your own server instead of Google’s. That will even allow you to remove your mail server from DNS and drop connections other than CloudFlare if desired.
Intrusion Prevention
In my testing it takes less than an hour before someone discovers and attempts to break into your mail server. You may wish to GeoIP block or otherwise limit connections. You can also use crowdsec.
Crowdsec
Crowdsec is an open-source IPS that monitors your log files and blocks suspicious behavior.
Install as per their instructions.
curl -s https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.deb.sh | sudo bash
sudo apt install -y crowdsec
sudo apt install crowdsec-firewall-bouncer-nftables
sudo cscli collections install crowdsecurity/postfix
Postfix
Most services now log to the system journal rather than a file. You can view them with the journalctl
command
# What is the exact service unit name?
sudo systemctl status | grep postfix
# Anything having to do with that service unit
sudo journalctl --unit [email protected]
# Zooming into just the identifiers smtp and smtpd
sudo journalctl --unit [email protected] -t postfix/smtp -t postfix/smtpd
Crowdsec accesses the system journal by adding a block to it’s log acquisition directives.
sudo tee -a /etc/crowdsec/acquis.yaml << EOF
source: journalctl
journalctl_filter:
- "[email protected]"
labels:
type: syslog
---
EOF
sudo systemctl reload crowdsec
Dovecot
Install the dovecot collection as well.
sudo cscli collections install crowdsecurity/dovecot
sudo tee -a /etc/crowdsec/acquis.yaml << EOF
source: journalctl
journalctl_filter:
- "_SYSTEMD_UNIT=dovecot.service"
labels:
type: syslog
---
EOF
sudo systemctl reload crowdsec
Is it working? You won’t see anything at first unless you’re actively under attack. But after 24 hours you may see some examples of attempts to relay spam.
allen@mail:~$ sudo cscli alerts list
╭────┬────────────────────┬────────────────────────────┬─────────┬──────────────────────────────────────────────┬───────────┬─────────────────────────────────────────╮
│ ID │ value │ reason │ country │ as │ decisions │ created_at │
├────┼────────────────────┼────────────────────────────┼─────────┼──────────────────────────────────────────────┼───────────┼─────────────────────────────────────────┤
│ 60 │ Ip:187.188.233.58 │ crowdsecurity/postfix-spam │ MX │ 17072 TOTAL PLAY TELECOMUNICACIONES SA DE CV │ ban:1 │ 2023-05-24 06:33:10.568681233 +0000 UTC │
│ 54 │ Ip:177.229.147.166 │ crowdsecurity/postfix-spam │ MX │ 13999 Mega Cable, S.A. de C.V. │ ban:1 │ 2023-05-23 20:17:49.912754687 +0000 UTC │
│ 53 │ Ip:177.229.154.70 │ crowdsecurity/postfix-spam │ MX │ 13999 Mega Cable, S.A. de C.V. │ ban:1 │ 2023-05-23 20:15:27.964240044 +0000 UTC │
│ 42 │ Ip:43.156.25.237 │ crowdsecurity/postfix-spam │ SG │ 132203 Tencent Building, Kejizhongyi Avenue │ ban:1 │ 2023-05-23 01:15:43.87577867 +0000 UTC │
│ 12 │ Ip:167.248.133.186 │ crowdsecurity/postfix-spam │ US │ 398722 CENSYS-ARIN-03 │ ban:1 │ 2023-05-20 16:03:15.418409847 +0000 UTC │
╰────┴────────────────────┴────────────────────────────┴─────────┴──────────────────────────────────────────────┴───────────┴─────────────────────────────────────────╯
If you’d like to get into the details, take a look at the Crowdsec page .
Next Steps
Now that your server is secure, let’s take a look at how email is authenticated and how to ensure yours is.
3.5 - Authentication
Email authentication prevents forgery. People can still send unsolicited email, but they can’t fake who it’s from. If you set up a Relay for Postfix, the relayer is doing it for you. But otherwise, proceed onward to prevent your outgoing mail being flagged as spam.
You need three things
- SPF: Server IP addresses - which specific servers have authorization to send email.
- DKIM: Server Secrets - email is signed so you know it’s authentic and unchanged.
- DMARC: Verifies the address in the From: aligns with the domain sending the email, and what to do if not.
SPF
SPF, or Sender Policy Framework, is the oldest component. It’s a DNS TXT record that lists the servers authorized to send email for a domain.
A receiving server looks at a messages’s return path (aka RFC5321.MailFrom header) to see what domain the email purports to be from. It then looks up that domain’s SPF record and if the server that sent the email isn’t included, the email is considered forged.
Note - this doesn’t check the From: header the user sees. Messages can appear (to the user) to be from anywhere. So it’s is mostly a low-level check to prevent spambots.
The DNS record for your Postfix server should look like:
Type: "TXT"
NAME: "@"
Value: "v=spf1 a:mail.your.org -all"
The value above shows the list of authorized servers (a:) contains mail.your.org. Mail from all other servers is considered forged (-all).
To have your Postfix server check SPF for incoming messages add the SPF policy agent.
sudo apt install postfix-policyd-spf-python
sudo tee -a /etc/postfix/master.cf << EOF
policyd-spf unix - n n - 0 spawn
user=policyd-spf argv=/usr/bin/policyd-spf
EOF
sudo tee -a /etc/postfix/main.cf << EOF
policyd-spf_time_limit = 3600
smtpd_recipient_restrictions =
permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination,
check_policy_service unix:private/policyd-spf
EOF
sudo systemctl restart postfix
DKIM
DKIM, or DomainKeys Identified Mail, signs the emails as they are sent ensuring that the email body and From: header (the one you see in your client) hasn’t been changed in transit and is vouched for by the signer.
Receiving servers see the DKIM header that includes who signed it, then use DNS to check it. Unsigned mail simply isn’t checked. (There is no could-but-didn’t in the standard).
Note - There is no connection between the domain that signs the message and what the user sees in the From: header. Messages can have a valid DKIM signature and still appear to be from anywhere. DKIM is mostly to prevent man-in-the-middle attacks from altering the message.
For Postfix, this requires installation of OpenDKIM and a connection as detailed here. Make sure to sign with the domain root.
https://tecadmin.net/setup-dkim-with-postfix-on-ubuntu-debian/
Once you’ve done that, create the following DNS entry.
Type: "TXT"
NAME: "default._domainkey"
Value: "v=DKIM1; h=sha256; k=rsa; p=MIIBIjANBgkq..."
DMARC
Having a DMARC record is the final piece that instructs servers to check the From: header the user sees against the domain return path from the SPF and DKIM checks, and what to do on a fail.
This means mail “From: [email protected]” sent though mail.your.org mail servers will be flagged as spam.
The DNS record should look like:
Type: "TXT"
NAME: "_dmarc"
Value: "v=DMARC1; p=reject; adkim=s; aspf=r;"
- p=reject: Reject messages that fail
- adkim=s: Use strict DKIM alignment
- aspf=r: Use relaxed SPF alignment
Reject (p=reject) indicates that email servers should “reject” emails that fail DKIM or SPF tests, and skip quarantine.
Strict DKIM alignment (=s) means that the SPF Return-Path domain or the DKIM signing domain must be an exact match with the domain in the From: address. A DKIM signature from your.org would exactly match [email protected].
Relaxed SPF alignment (=r) means subdomains of the From: address are acceptable. I.e. the server mail.your.org from the SPF test aligns with an email from: [email protected].
You can also choose quarantine mode (p=quarantine) or report-only mode (p=none) where the email will be accepted and handled as such by the receiving server, and a report sent to you like below.
v=DMARC1; p=none; rua=mailto:[email protected]
DMARC is an or test. In the first example, if either the SPF or DKIM domains pass, then DMARC passes. You can choose to test one, both or none at all (meaning nothing can pass DMARC) as the the second DMARC example.
To implement DMARC checking in Postfix, you can install OpenDMARC and configure a mail filter as described below.
https://www.linuxbabe.com/mail-server/opendmarc-postfix-ubuntu
Next Steps
Now that you are hadnling email securely and authentically, let’s help ease client connections
Autodiscovery
3.6 - Autodiscovery
In most cases you don’t need this. Thunderbird, for example, will use a shotgun approach and may find your sever using ‘common’ server names based on your email address.
But there is an RFC and other clients may need help.
DNS SRV
This takes advantage of the RFC with an entry for IMAP and SMTP Submission
Type |
Name |
Service |
Protocol |
TTL |
Priority |
Weight |
Port |
Target |
SRV |
@ |
_imap |
TCP |
auto |
10 |
5 |
143 |
mail.your.org |
SRV |
@ |
_submission |
TCP |
auto |
10 |
5 |
465 |
mail.your.org |
Web Autoconfig
- Create a DNS entry for autoconfig.your.org
- Create a vhost and web root for that with the file
mail/config-v1.1.xml
- Add the contents below to that file
<?xml version="1.0"?>
<clientConfig version="1.1">
<emailProvider id="your.org">
<domain>your.org</domain>
<displayName>Example Mail</displayName>
<displayShortName>Example</displayShortName>
<incomingServer type="imap">
<hostname>mail.your.org</hostname>
<port>143</port>
<socketType>STARTTLS</socketType>
<username>%EMAILLOCALPART%</username>
<authentication>password-cleartext</authentication>
</incomingServer>
<outgoingServer type="smtp">
<hostname>mail.your.org</hostname>
<port>587</port>
<socketType>STARTTLS</socketType>
<username>%EMAILLOCALPART%</username>
<authentication>password-cleartext</authentication>
<addThisServer>true</addThisServer>
</outgoingServer>
</emailProvider>
<clientConfigUpdate url="https://www.your.org/config/mozilla.xml" />
</clientConfig>
Note
It’s traditional to match server names to protocols and we would have used “imap.your.org” and “smtp.your.org”. But using ‘mail’ is popular now and it simplifies setup at several levels.
Thunderbird will try to guess at your server names, attempting to connect to smtp.your.org for example. But many Postfix configurations have spam prevention that interfere.
Sources
https://cweiske.de/tagebuch/claws-mail-autoconfig.htm
https://www.hardill.me.uk/wordpress/2021/01/24/email-autoconfiguration/