-
Notifications
You must be signed in to change notification settings - Fork 0
Email Server on Raspberry Pi
Journey to set-up Email Server on Raspberry Pi.
Most of the information is reference from https://samhobbs.co.uk
Flash the Raspberry Pi with the latest Raspbian version. Raspbian Stretch (Release data: 2018-06-27).
Use rasp-config
to set up keyboard and wifi country.
The configuration for the network can be done in the following file:
/etc/network/interface
Inside the file, interface, add the following lines. eth0 is the local connection and wlan0 is the wireless connection:
auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-ssid "yourSSID"
wpa-psk "yourWIFIpassword"
auto eth0
iface eth0 inet static
address 192.168.1.50
netmask 255.255.255.0
Once the configuration for the network is done, do a reboot. Use ifconfig
to check if a ip address is assigned to wlan0.
To update the Raspberry Pi, use apt-get update
and thereafter apt-get upgrade
.
If there is any error message during apt-get update
, such as E: Failed to fetch http://103.1.138.146... Hash Sum mismatch
. This error might be caused by the ISP, M1.
Check the repository list, /etc/apt/sources.list.d/raspi.list
, if the link is "http://..." change to "https://"..
Firstly, you need to purchase a domain for your own mail server. You can get it at godaddy.com There's a few configuration on your domain. Go to your DNS Management for the following settings. Set Type 'A', Host '@', Points to 'YOURPUBLICIP'. This is to set your domain to your public ip. Note: Most ISP public ip address is dynamic. Thus, you would need to set public ip address on your domain when the public ip address changes.
Create a Type 'MX', Host '@', Points to '@', Priority '10'. This is to set up a mail exchange on your domain.
Optional: Use dnsutils to check on the domain setting. apt-get install dnsutils
.
Use command dig yourdomain.com
to check your domain ip address etc and dig yourdomain.com mx
to check the mail exchange on your domain.
Postfix is an application for sending and receiving of email using Simple Mail Transfer Protocol (SMTP).
To install Postfix, use the following command:
apt-get install postfix
On the first prompt, select "Internet Site" and key in your own domain.
The configuration on postfix can be found at /etc/postfix/main.cf
Edit the main.cf file by using either vim /etc/postfix/main.cf
or nano /etc/postfix/main.cf
change the inet_protocols = all
to inet_protocols = ipv4
to allowing ipv4 only.
Add the following lines at the bottom of main.cf:
home_mailbox = Maildir/
mailbox_command =
This will set the Maildir as the configuration of the mailbox. Maildir create one file for each email.
The following lines are added to restrict who are allowed to send emails to external mail server:
smtpd_recipient_restrictions =
permit_sasl_authenticated, #permit user that has SASL authenticated to send email to any destination
permit_mynetworks, #allow user to send email if user has connected to IP address defined within mynetwork
reject_unauth_destination #reject email if none of the above conditions have met
The following lines are added to restrict incoming spam mails to the mail server:
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
Once all the above added, restart postfix:
service postfix restart or /etc/init.d/postfix restart
Install telnet to test Postfix configuration
apt-get install telnet
Use the following lines to test the configuration:
root@raspberry:/etc/postfix# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 raspberry ESMTP Postfix (Debian/GNU)
Telnet will output as shown above. Steps to use telnet:
-
ehlo raspclouds.com
to let the server know who you are. -
mail from: pi
this indicates who is sending the email -
rcpt to: recipient@domain.com
this indicates who are you sending to -
data
to initialise your email content - End the content with a empty line with
.
to end the email content - type
quit
to exit
Check the recipient email if the email has been sent out. Check Spam mail for the email.
You can now send email out to external mail server!
Dovecot allow SASL authentication and IMAP.
apt-get install dovecot-core dovecot-imapd
Key in the commands below to create the templates files which will be created when a new user is created:
maildirmake.dovecot /etc/skel/Maildir
maildirmake.dovecot /etc/skel/Maildir/.Drafts
maildirmake.dovecot /etc/skel/Maildir/.Sent
maildirmake.dovecot /etc/skel/Maildir/.Spam
maildirmake.dovecot /etc/skel/Maildir/.Trash
maildirmake.dovecot /etc/skel/Maildir/.Templates
Key in the commands below to copy the Maildir files to an existing user. In this case, we will do it to user: pi:
cp -r /etc/skel/Maildir /home/pi/
chown -R pi:pi /home/pi/Maildir
chmod -R 700 /home/pi/Maildir
Edit /etc/dovecot/dovecot.conf
to allow IPv4 addresses only.
look for listen = *, ::
and change to listen = *
Direct Dovecot to indicate where the mailbox is located.
open /etc/dovecot/conf.d/10-mail.conf
and look for mail_location = mbox:~/mail:INBOX=/var/mail/%u
. Change the line to mail_location = maildir:~/Maildir
Add the following lines to /etc/postfix/main.cf
to let Postfix to use Dovecot SASL authentication.
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
Go into /etc/dovecot/conf.d/10-master.conf
and let Dovecot to listen for SASL authentication.
Locate the unix listener /var/spool/postfix/private/auth and change to the lines below.
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0666
user = postfix
group = postfix
}
}
Now going into /etc/dovecot/conf.d/10-auth.conf
to allow plain text login. locate and change disable_plaintext_auth = yes
to disable_plaintext_auth = no
. locate auth_mechanisms = plain
and change to auth_mechanisms = plain login
Restart both postfix and dovecot once the above steps are done.
service postfix restart
service dovecot restart
Now create a new user to test SASL.
adduser testmail
Use the password: test1234
Now the server requires a base64 encoded version of the username and password.
The base64 of user: testmail and password: test1234 can be found by using this command:
perl -MMIME::Base64 -e 'print encode_base64("\0testmail\0test1234");'
The output should be AHRlc3RtYWlsAHRlc3QxMjM0
Now test out the new setting with SASL with telnet localhost 25
root@raspberry:~# telnet localhost 25
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 raspberry ESMTP Postfix (Debian/GNU)
ehlo raspclouds.com
250-raspberry
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
**250-AUTH PLAIN LOGIN**
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
Type AUTH PLAIN AHRlc3RtYWlsAHRlc3QxMjM0
for the authentication. 235 2.7.0 Authentication successful
will be shown once the authentication is completed.
Thereafter, try to send an email out using the same methods when using telnet to send out an email.
Configure postfix to allow Port: 465 (SMTPS)
In /etc/postfix/master.cf
edit/uncomment the following lines:
smtps inet n - y - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
Run /etc/init.d/postfix restart
to restart postfix service. Postfix is now configured with SMTPS
There are 2 common protocols used for fetching emails, POP & IMAP. In this configuration, IMAP will be used.
Use telnet to test the IMAP telnet localhost 143
root@raspberrypi:/etc/postfix# telnet localhost 143
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
Type a login "testmail" "test1234"
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS BINARY MOVE SPECIAL-USE] Logged in
Type b select inbox
* FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
* OK [PERMANENTFLAGS (\Answered \Flagged \Deleted \Seen \Draft \*)] Flags permitted.
* 0 EXISTS
* 0 RECENT
* OK [UIDVALIDITY 1537680538] UIDs valid
* OK [UIDNEXT 1] Predicted next UID
b OK [READ-WRITE] Select completed (0.000 + 0.000 secs).
To quit, type c logout
* BYE Logging out
c OK Logout completed (0.000 + 0.000 secs).
Connection closed by foreign host.
IMAP is working.
We need to enable IMAPS (IMAP SSL/TLS), Port: 993
Edit /etc/dovecot/conf.f/10-master.conf
service imap-login {
inet_listener imap {
port = 143
}
inet_listener imaps {
port = 993
ssl = yes
}
}
Next, edit /etc/dovecot/conf.d/10-ssl.conf
. Before editing 10-ssl.conf
, generate a self-signed certificate and thereafter input the directory into the 10-ssl.conf
file.
To generate a self-signed certificate, go to /usr/share/dovecot
. Run the script ./mkcert.sh
.
The script will start and show something as followed:
Generating a 2048 bit RSA private key
...
writing new private key to '/etc/dovecot/private/dovecot.pem'
Your self-signed certificate is now generated.
Go to /etc/dovecot/conf.d/10-ssl.conf
and edit/uncomment the following:
ssl=yes
...
ssl_cert = </etc/dovecot/dovecot.pem
ssl_key = </etc/dovecot/private/dovecot.pem
...
ssl_protocols = !SSLv3
Run /etc/init.d/dovecot restart
to restart the dovecot service.
Use this command to test out your IMAPS configuration.
openssl s_client -connect localhost:993 -quiet
root@raspberry:/etc/dovecot/conf.d# openssl s_client -connect localhost:993 -quiet
depth=0 O = Dovecot mail server, OU = @commonName@, CN = @commonName@, emailAddress = @emailAddress@
verify error:num=18:self signed certificate
verify return:1
depth=0 O = Dovecot mail server, OU = @commonName@, CN = @commonName@, emailAddress = @emailAddress@
verify return:1
* OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE AUTH=PLAIN AUTH=LOGIN] Dovecot ready.
If the configuration is done correctly, you should have the output as shown above. SSL/TLS is working on Port: 993.
You will need to do port forward on your router to route the ports to Raspberry Pi ip address. Port forward these following ports:
- SMTP Port: 25
- SMTPS Port: 465
- IMAPS Port: 993
- HTTP Port: 80 (Required for webserver)
Set the Protocols as Both for all the above ports.
Thunderbird will be used as the mail client to connect with the mail server. Install Thunderbird and during the first launch, Thunderbird will prompt you to add an existing email.
Key in the email address, user@yourdomain.com. Use the domain which you bought and used during the postfix configuration. The password is the same as what you used to login in your Raspberry Pi. After that, Click 'Done'.
The following prompt below will be shown after you clicked 'Done'
Check 'I understand the risk' and click 'Done'.
The picture below will be shown. Click 'Manual Configure'
The following prompt will be shown as below.
Following the configuration as shown in the picture above to set up the SSL/TLS ports etc. Click 'Done' once the configuration is done.
When there's a prompt on 'Add Security Exception' for yourdomain.com:993 and yourdomain:465, Click 'Confirm Secruity Exception'. The example of the prompts are shown below.
Once the configuration above are done correctly, if you are adding additional user from your Raspberry Pi mail server, when you click on the 'Re-test' during 'Set up an Existing Email Account', there should not be any error. The 'Add Security Exception' prompt should not occur again.
On the left panel of Thunderbird, you should see your email address added to Thunderbird now.
Your Thunderbird mail client is ready to send and receive emails. Try it!
To set up a web mail server, we need to set up a web server such as apache or nginx. In this configuration, nginx will be used. To install both ngnix and php which needs to be used, apt-get install nginx php7.0 php7.0-fpm
.
Once the installation is completed, open a browser and type in your ip address. The picture below will be shown and your webserver is now ready. To edit the html file, its located at /var/www/html
. The default html from nginx which is see below are named as index.nginx-debian.html
To link your domain to nginx, nano /etc/nginx/sites-enabled/default
and follow the commands below:
server {
listen 80;
root /var/www/html/;
index index.php index.html index.htm;
server_name yourdomain.com;
location / { try_files $uri $uri/ =404; }
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
Run /etc/init.d/nginx restart
to restart nginx service.
Roundcube Web Mail will be used for this configuration. Firstly, download the roundcube mail from https://roundcube.net/download/
or download using command on the Raspberry Pi by using wget https://github.com/roundcube/roundcubemail/releases/download/1.3.7/roundcubemail-1.3.7-complete.tar.gz
. move the zip file to /var/www/html
.
apt-get install roundcube
to install the packages on the Raspberry Pi too. There will be a prompt to key in password for mysql during the installation, password 'test1234' is used for this configuration.
Decompress the file by using tar xzpvf roundcubemail-1.3.7-complete.tar.gz
. After decompressing, move all the files from the folder roundcubemail-1.3.7
to /var/www/html
by using mv roundcubemail-1.3.7/* /var/www/html/
.
Database is required for the web server and this can be done with mysql.
apt-get install mysql-server
Prompt to set your root password will occurred during the installing of mysql if your root password is not set.
Once the installation is done, type mysql -u root -p
on your terminal. Key in your root password. Thereafter follow the steps below to configure a database for Roundcube Mail
root@raspberry:/var/www/html# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> CREATE DATABASE roundcubemail;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost IDENTIFIED BY 'test1234';
Query OK, 0 rows affected (0.01 sec)
MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)
MariaDB [(none)]> quit
Bye
mysql for roundcube mail is now set up.
Open a browser and type yourdomain.com/installer
. If nginx, php and roundcube are all installed and set up correctly, you should see the picture as shown below. Scroll down and Click 'Next'.
Upon the next page, there's 3 category to edit, mysql, IMAP and SMTP. The configurations are shown below. For mysql, input the database password which was created during the roundcube installation and during mysql set up as 'IDENTIFIED BY 'databasepassword'' For IMAP setting, change the port to 993 and add ssl:// infront of your own domain. For SMTP setting, change the port to 465 and add ssl:// infront of your own domain.
.
Once done, scroll down and click 'UPDATE CONFIG'. A config file will be generated. Copy the configure lines or download the config.inc.php
file. Put/create the config.inc.php
file into /var/www/html/mail/config
.
Once config.inc.php
is inside /var/www/html/mail
, click 'Continue' and the picture below shows the next page.
First, let use resolve the issue on the folder that needs to be writeable. cd /var/www/html/mail
and locate logs and temp folders. Enter the following commands to change the ownership of the 2 folders
chown -R www-data:mail logs
chown -R www-data:mail temp
Refer the page and the status will now change to OK! Next click 'initialise Database' and once done, it should show OK for all the status. Optional: Use the webpage to check the SMTP and IMAP setting.
Now enter the link yourdomain.com/mail and you should be seeing the RoundCube Mail interface as shown belown.
Try to login with a user in your Raspberry Pi. Username: youruseraccount Password: youruserpassword.
There probably be a error stating 'connection to storage server failed'. Check the /var/logs/mail.log
for the details of the error.
Error stated: ...TLS handshaking: SSL_accept() failed: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca: SSL alert number 48...
This can be resolved by editing the `/var/www/html/mail/config/defaults.inc.php' Editing and comment out the following:
...
$config['imap_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
// Note: These can be also specified as an array of options indexed by hostname
#config['imap_conn_options'] = null;
...
$config['smtp_conn_options'] = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
),
);
// Note: These can be also specified as an array of options indexed by hostname
#$config['smtp_conn_options'] = null;
You can now logon to the Roundcube Web Mail!
However, there's an error when you try to send the email out. Check the mail.log
again for the error.
3 different issues might occur at this stage, which is 'Recipient address rejected', 'Client host rejected' and 'Relay access denied'.
This can be resolved by editing /etc/postfix/master.cf
Edit/uncomment the following lines:
...
submission inet n - n - - smtpd
...
Run /etc/init.d/postfix restart
to restart the postfix server. Try to send email from Roundcube mail and the mail can be successfully send out!
The Thunderbird mail client and Roundcube Web Mail Client are now ready!
Take away from this configuration: Always check the mail.log to identify the details on the issue. Always restart the service after editing the configuration files.