====== Create Raspberry Pi Email Server ====== ===== Prerequisites ===== * Install Raspberry Pi OS on Pi Board * Ensure SSH access to Pi ===== Implement Postfix and Dovecot ===== sudo apt-get update sudo apt-get install postfix sudo apt-get install dovecot-common dovecot-imapd Select '**Internet Site**' and then set the mail name to your domain name. In this article, I refer to the domain name as **example.com** cd /etc/postfix/ sudo nano /etc/postfix/main.cf Edit the following: myhostname = example.com Add the following: inet_protocols = ipv4 home_mailbox = Maildir/ mailbox_command = smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination smtpd_helo_required = yes smtpd_helo_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname, check_helo_access hash:/etc/postfix/helo_access smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth smtpd_sasl_auth_enable = yes smtpd_tls_auth_only = yes milter_protocol = 2 milter_default_action = accept smtpd_milters = inet:localhost:12301 Ctrl-X to exit, and Y to save. sudo maildirmake.dovecot /etc/skel/Maildir sudo maildirmake.dovecot /etc/skel/Maildir/.Drafts sudo maildirmake.dovecot /etc/skel/Maildir/.Sent sudo maildirmake.dovecot /etc/skel/Maildir/.Spam sudo maildirmake.dovecot /etc/skel/Maildir/.Trash sudo maildirmake.dovecot /etc/skel/Maildir/.Templates sudo maildirmake.dovecot /etc/skel/Maildir/.Junk sudo cp -r /etc/skel/Maildir /home/pi/ sudo chown -R pi:pi /home/pi/Maildir sudo chmod -R 700 /home/pi/Maildir sudo nano /etc/postfix/helo_access Add the following: example.com REJECT Email rejected - cannot verify identity mail.example.com REJECT Email rejected - cannot verify identity Ctrl-X to exit, and Y to save. sudo postmap /etc/postfix/helo_access sudo nano /etc/dovecot/dovecot.conf Edit: listen = * Ctrl-X to exit, and Y to save. sudo nano /etc/dovecot/conf.d/10-mail.conf Edit: mail_location = maildir:~/Maildir Ctrl-X to exit, and Y to save. sudo nano /etc/dovecot/conf.d/10-master.conf Edit: service imap-login { inet_listener imap { port = 143 } inet_listener imaps { port = 993 ssl = yes } } service auth { unix_listener /var/spool/postfix/private/auth { mode = 0660 user = postfix group = postfix } } Ctrl-X to exit, and Y to save. sudo nano /etc/dovecot/conf.d/10-auth.conf Edit: disable_plaintext_auth = no auth_mechanisms = plain login Ctrl-X to exit, and Y to save. sudo nano /etc/dovecot/conf.d/10-ssl.conf Edit: ssl = yes ssl_protocols = !SSLv3 ssl_cert = You will note that rather than building a new SSL certificate, we are leveraging the certificate from Let's Encrypt that was already previously built. Ctrl-X to exit, and Y to save. Now you will need to use the below "adduser" command to add each email address that you wish to set up. For example, to set up [[http://joedoe@example.com/|joedoe@example.com:]] sudo adduser joedoe Open this file: sudo nano /etc/postfix/master.cf Add: -o content_filter=spamassassin Bellow this line: smtp inet n - y - - smtpd Add: -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject Bellow this line: smtps inet n - - - - smtpd So it will look something like this: ... smtp inet n - y - - smtpd -o content_filter=spamassassin #smtp inet n - y - 1 postscreen #smtpd pass - - y - - smtpd ... smtps inet n - - - - smtpd -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject Add this to the end of the file: spamassassin unix - n n - - pipe user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient} Ctrl-X to exit, and Y to save. ===== Add DKIM to stop your emails from being treated as spam ===== sudo apt-get install opendkim opendkim-tools sudo nano /etc/opendkim.conf Add or edit (if exist) as below: AutoRestart Yes AutoRestartRate 10/1h SyslogSuccess Yes LogWhy Yes Canonicalization relaxed/simple ExternalIgnoreList refile:/etc/opendkim/TrustedHosts InternalHosts refile:/etc/opendkim/TrustedHosts KeyTable refile:/etc/opendkim/KeyTable SigningTable refile:/etc/opendkim/SigningTable Mode sv PidFile /var/run/opendkim/opendkim.pid SignatureAlgorithm rsa-sha256 UserID opendkim:opendkim Socket inet:12301@localhost Ctrl-X to exit, and Y to save. sudo nano /etc/default/opendkim Edit: SOCKET="inet:12301@localhost" Ctrl-X to exit, and Y to save. sudo mkdir /etc/opendkim sudo mkdir /etc/opendkim/keys sudo nano /etc/opendkim/TrustedHosts Add: 127.0.0.1 localhost 192.168.0.1/24 *.example.com Also add your pi's local ip address in there. You can find it by this command: ''hostname -I'' Ctrl-X to exit, and Y to save. sudo nano /etc/opendkim/KeyTable Add: mail._domainkey.example.com example.com:mail:/etc/opendkim/keys/example.com/mail.private Ctrl-X to exit, and Y to save. sudo nano /etc/opendkim/SigningTable Add: *@example.com mail._domainkey.example.com Ctrl-X to exit, and Y to save. cd /etc/opendkim/keys sudo mkdir example.com cd example.com sudo opendkim-genkey -s mail -d example.com sudo chown opendkim:opendkim mail.private sudo chmod 777 mail.txt sudo nano -$ mail.txt Go to your domain registrar (e.g., CloudFlare, EuroDNS, GoDaddy, etc.). Use this output to set up a TXT record, with hostname: mail._domainkey and with value: v=DKIM1; k=rsa; p=MIG…. sudo service dovecot reload sudo service dovecot restart sudo service postfix reload sudo service postfix restart sudo service opendkim restart ===== Identify incoming spam email with SpamAssassin ===== sudo apt-get install spamassassin sudo nano /etc/spamassassin/local.cf Edit: rewrite_header Subject [***** SPAM _SCORE_ *****] report_safe 0 required_score 5.0 use_bayes 1 Ctrl-X to exit, and Y to save. sudo nano /etc/default/spamassassin Edit: ENABLED=1 Ctrl-X to exit, and Y to save. sudo service spamassassin start sudo systemctl enable spamassassin sudo service dovecot restart sudo service postfix restart ===== Install Rainloop Webmail ===== If you use Apache and PHP7, then install them on Ubuntu 20.04 with: sudo apt update sudo apt install apache2 php7.4 libapache2-mod-php7.4 And install the following PHP extensions which are required by RainLoop. sudo apt install php7.4-curl php7.4-xml ===== Download and Install RainLoop Webmail on Ubuntu 20.04 ===== First, make a directory for rainloop in the current working directory. mkdir rainloop CD into the directory and download the latest RainLoop community edition with the following commands: cd rainloop curl -s http://repository.rainloop.net/installer.php | php Once that’s done, move this directory to ''/var/www/''. cd .. sudo mv rainloop /var/www/ Now set web server user (''www-data'') as the owner. sudo chown www-data:www-data /var/www/rainloop/ -R ===== Configure a Virtual Host for RainLoop ===== We can use either Apache or Nginx web server. ==== Apache ==== If you like to use Apache web server, then create the virtual host file with the following command: sudo nano /etc/apache2/sites-available/rainloop.conf Put the following text into the file. Replace red text with your actual info. ServerName mail.example.com DocumentRoot "/var/www/rainloop/" ErrorLog "/var/log/apache2/rainloop_error_log" TransferLog "/var/log/apache2/rainloop_access_log" Options +Indexes +FollowSymLinks +ExecCGI AllowOverride All Order deny,allow Allow from all Require all granted Require all denied Save and close the file. Then enable this virtual host. sudo a2ensite rainloop.conf And reload Apache. sudo systemctl reload apache2 ===== Install TLS/SSL Certificate ===== If you want to add HTTPS to webmail, then you can obtain a free TLS/SSL certificate from Let’s Encrypt CA. First Let’s install the ''certbot'' client. sudo apt install certbot If you use **Apache** web server, then you also need to install the Certbot Apache plugin. sudo apt install python3-certbot-apache Then issue the following command to obtain a free TLS/SSL certificate. Replace the red-colored text with your actual email address and domain name. sudo certbot --apache --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d mail.example.com {{https://www.linuxbabe.com/wp-content/uploads/2020/04/ubuntu-20.04-rainloop-https-letsencrypt-certbot.png?nolink&|ubuntu 20.04 rainloop https letsencrypt certbot}} ===== Configure RainLoop Webmail ===== Log into RainLoop admin panel via the following URL. mail.example.com/?admin Default username is ''admin'' and default password is ''12345''. Once you are logged in, it’s recommended to change both your username and password since ''admin'' is an easy target. Click the ''security'' tab on the left pane. Update your password first, then re-login and update your username. {{https://www.linuxbabe.com/wp-content/uploads/2020/04/rainloop-webmail-ubuntu-20.04.png?nolink&895x597|rainloop-webmail-ubuntu-20.04}} To access your emails through RainLoop, you need to configure email server settings in the ''Domains'' tab. By default, 4 email domains are added: ''gmail.com'', ''outlook.com'', ''qq.com'', ''yahoo.com''. {{https://www.linuxbabe.com/wp-content/uploads/2016/11/RainLoop-Webmail-multiple-email-domain.png?nolink&895x565|rainloop webmail multiple email domains}} The SMTP server settings and IMAP server settings for these email domains are configured by RainLoop, but only Gmail is enabled by default. To enable the other 3 email domains, simply tick on the checkboxes. To be able to access [[https://www.linuxbabe.com/mail-server/setup-basic-postfix-mail-sever-ubuntu|your own email server]], click the ''Add Domain'' button and enter the IMAP and SMTP server settings of your own email server. * IMAP: server **mail.example.com**, port **143**, Secure **STARTTLS**. * SMTP: server **mail.example.com**, port **587**, Secure **STARTTLS**. Tick on Use Authentication. {{https://www.linuxbabe.com/wp-content/uploads/2020/04/rainloop-imap-and-smtp-settings.png?nolink&804x533|rainloop imap and smtp settings}} If Rainloop and Postfix/Dovecot are running on the same server, then you can use the following configurations, so your server doesn’t have to look up the domain in DNS and establish TLS connection. * IMAP: server **127.0.0.1**, port **143**, Secure **None**. * SMTP: server **127.0.0.1**, port **25**, Secure **None**. Don’t use authentication on port 25. {{https://www.linuxbabe.com/wp-content/uploads/2020/04/rainloop-postfix-dovecot-on-the-same-server.png?nolink&806x532|rainloop postfix dovecot on the same server}} You also need to enable your own email domain by ticking on the checkbox on the right, or the error ''domain is not allowed'' will appear when logging into your email address. After finishing the configuration, enter your RainLoop webmail domain name in the browser address bar without ''/?admin'' suffix. mail.example.com And log into your email account. {{https://www.linuxbabe.com/wp-content/uploads/2016/11/rainloop-ubuntu.png?nolink&757x504|rainloop ubuntu}} RainLoop webmail {{https://www.linuxbabe.com/wp-content/uploads/2016/11/rainloop-webmail-ubuntu.png?nolink&1116x638|rainloop webmail ubuntu}} If authentication failed, then you may need to enable short login in the IMAP server settings page. That’s all you need to do in order to access your emails on Gmail, outlook mail or your own email domain. If you add multiple email accounts, you can easily switch between them from the user drop-down menu. Very cool indeed! You can also configure other settings and customize your webmail interface. ===== Removing Sensitive Information from Email Headers ===== By default, Rainloop will add a ''X-Mailer'' email header, indicating that you are using Rainloop webmail and the version number. You can tell Postfix to ignore it so recipient can not see it. Run the following command to create a header check file. sudo nano /etc/postfix/smtp_header_checks Put the following lines into the file. /^X-Mailer.*RainLoop/ IGNORE Save and close the file. Then edit the Postfix main configuration file. sudo nano /etc/postfix/main.cf Add the following line at the end of the file. smtp_header_checks = regexp:/etc/postfix/smtp_header_checks Save and close the file. Then run the following command to rebuild hash table. sudo postmap /etc/postfix/smtp_header_checks Reload Postfix for the change to take effect. sudo systemctl reload postfix Now Postfix won’t include ''X-Mailer: Rainloop'' in email headers. ===== Increase Attachment Size Limit ===== If you use PHP-FPM to run PHP scripts, then files such as images, PDF files uploaded to Rainloop can not be larger than 2MB. To increase the upload size limit, edit the PHP configuration file. sudo nano /etc/php/7.4/fpm/php.ini Find the following line (line 846). upload_max_filesize = 2M Change the value like below. Note that this value should not be larger than the attachment size limit set by Postfix SMTP server. upload_max_filesize = 50M Then find the following line (line 694). post_max_size = 8M Change the maximum size of POST data that PHP will accept. post_max_size = 50M Save and close the file. Alternatively, you can run the following two commands to change the value without manually opening the file. sudo sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 50M/g' /etc/php/7.4/fpm/php.ini sudo sed -i 's/post_max_size = 8M/post_max_size = 50M/g' /etc/php/7.4/fpm/php.ini Then restart PHP-FPM. sudo systemctl restart php7.4-fpm Nginx also sets a limit of upload file size. The default maximum upload file size limit set by Nginx is 1MB. If you use Nginx, edit the Nginx configuration file. sudo nano /etc/nginx/conf.d/mail.example.com.conf Add the following line in the SSL virtual host. client_max_body_size 50M; Save and close the file. Then reload Nginx for the changes to take effect. sudo systemctl reload nginx Next, log in to the Rainloop admin panel (''[[https://mail.example.com/?admin|https://mail.example.com/?admin]]'' ) and change the attachment size limit. {{https://www.linuxbabe.com/wp-content/uploads/2020/04/rainloop-attachment-size-limit.png?nolink&688x274|rainloop attachment size limit}} Save the change. You need to log out from your webmail and log back in for the change to take effect. ===== Training Spamassassin ===== Create a simple cron job to train SpamAssassin daily. sudo nano /etc/cron.daily/spamassassin-learn Now copy and paste this into the file #!/bin/bash # redirect errors and output to logfile exec 2>&1>> /var/log/spamassassin.log NOW=$(date +"%Y-%m-%d") # Headers for log echo "" echo "#============== $NOW ==============#" echo "" # learn HAM echo "Learning HAM from Inbox" sa-learn --dbpath /var/lib/spamassassin/.spamassassin/ --no-sync --ham /home/*/Maildir/{cur,new} # learn SPAM echo "Learning SPAM from Spam folder" sa-learn --dbpath /var/lib/spamassassin/.spamassassin/ --no-sync --spam /home/*/Maildir/.Spam/{cur,new} # Synchronize the journal and databases. echo "Syncing" sa-learn --dbpath /var/lib/spamassassin/.spamassassin/ --sync **Important:** The paths use glob (*) to scan ham and spam for all users (this only works if you trust all users to be sensible and move ham/spam to the right folder). It may affect your pi's performance. If you want to run on your username only, edit the paths so that they match your username! Now make the script executable: sudo chmod +x /etc/cron.daily/spamassassin-learn ===== Spam Sorting with LMTP & Sieve ===== sudo apt-get install dovecot-lmtpd Edit ''/etc/dovecot/dovecot.conf'' Append this to enable lmtp: protocols = imap lmtp Edit ''/etc/dovecot/conf.d/20-lmtp.conf'' Add this line: lmtp_save_to_detail_mailbox = yes Now change the lmtp protocol block to look like this: protocol lmtp { mail_plugins = $mail_plugins sieve postmaster_address = postmaster@yourdomain.com } Edit file ''/etc/dovecot/conf.d/10-master.conf'' Now find the service lmtp {… block and then change the line unix_listener lmtp {… to look like this: service lmtp { unix_listener /var/spool/postfix/private/dovecot-lmtp { mode = 0666 } } **Carefull** with the open and close bracket { } Edit file ''/etc/dovecot/conf.d/10-auth.conf'' and change: auth_username_format = %Ln Edit ''/etc/postfix/main.cf'' Comment out: mailbox_command= …and add: mailbox_transport = lmtp:unix:private/dovecot-lmtp ===== Sieve Rules ===== Dovecot's sieve is already installed, you can check by running: sudo apt-get install dovecot-sieve Now we need to change one more parameter in ''/etc/dovecot/conf.d/90-sieve.conf'' Uncomment this line: recipient_delimiter = + We still need to reload/restart Postfix and Dovecot to make that all the changes are loaded: sudo service postfix reload sudo service dovecot reload The default place to put the sieve script is in the user's home folder: ''~/.dovecot.sieve''. **Note:** You may need to repeat steps below for every user by replacing **user** in path for each username. Create it like this: sudo nano /home/user/.dovecot.sieve and add this: require ["fileinto"]; # Move spam to spam folder if header :contains "X-Spam-Flag" "YES" { fileinto "Spam"; # Stop here - if there are other rules, ignore them for spam messages stop; } Now chown the file to the owner of the mailbox, e.g.: sudo chown user:user /home/user/.dovecot.sieve ===== Managesieve ===== sudo apt-get install dovecot-managesieved open ''/etc/dovecot/dovecot.conf'' and add sieve to the protocols line: protocols = imap lmtp sieve and restart Dovecot: sudo service dovecot restart ===== Port forwarding ===== Finally, you must forward all the used ports for this implementation to your Raspberry Pi on your router: * Mail Server: 443 * SMTP Server: 25 * IMAPS Server: 993 * SSMTP Legacy: 465 * Managesieve: 4190 * DKIM: 12301 * And possibly 110, 143, and 995 **Viola!!!** If everything is setup right you should have a fully functional email server at low cost. Enjoy your custom email!