Raspberry Pi Email Server

Powered by Drupal

raspberry-pi-email-server.png

The RasPi’s small size and low power consumption make it an ideal choice for use as a home email server. After trying a couple of different pieces of software, I finally found an excellent combination: Postfix with Dovecot and Squirrelmail, plus Spamasssassin and Sieve for spam filtering. There are many, many tutorials out there for the first trilogy of programs, but since the configuration is slightly different for each distribution I kept coming unstuck when setting mine up on the Pi. Having finally got mine configured properly, I’ve put together a set of 5 tutorials, which will take you from a vanilla Raspbian image to a fully functioning email server in no time. When writing the tutorial I made an effort to explain what each setting does instead of just dumping commands. With a bit of luck at the end of the process you’ll not only have a working server, you’ll understand how it works… without having to wade through reams of documentation like I did! If you follow the tutorials from start to finish, here’s what you’ll end up with:

  1. An email server that you can run 24/7/365 for under £5 of electricity per year
  2. Personalised email address like you@yourdomain.com (requires you to have registered a domain name with a registrar like namecheap.com - see my DNS basics tutorial)
  3. The ability to connect from anywhere, and read & send email, using a secure IMAP connection on your phone, tablet or computer
  4. Log in to webmail using any web browser on a secure HTTPS connection, read & send email
  5. Complete control over your personal communication. Your emails are stored on YOUR server, and nobody is scanning them to sell you adverts.
  6. Smart spam filtering with Spamassassin
  7. Customisable mail sorting with Sieve rules

Postfix, the Mail Transfer Agent

Postfix Logo

Postfix is the program that lets you send and receive email using Simple Mail Transfer Protocol (SMTP). Whilst you, the user, may connect to your email server using IMAP (on port 143 or 993), or POP (on port 110 or 995), email servers talk to each other using SMTP on port 25. So, this is the basic core of the server. Without it, you wouldn’t be able to send or receive any emails! I’ve covered the setup here: Raspberry Pi Email Server Part 1: Postfix

Dovecot, the POP/IMAP Server

dovecotLogo-300x130_0.png

Dovecot is used for two things:

  1. It provides you with IMAP functionality
  2. It checks that you are who you say you are using Simple Authentication and Security Layer (SASL) before you send or fetch mail

If you’re not interested in connecting with IMAP on your devices, you still need Dovecot. Not only is it doing SASL for you, but Squirrelmail connects using IMAP in order to provide you with webmail. I’ve covered Dovecot installation and configuration here: Raspberry Pi Email Server Part 2: Dovecot

Squirrelmail, for Webmail

Squirrelmail Logo

Squirrelmail is handy because it allows you to check your email in any browser, from anywhere. Of the first three, it’s probably the easiest to configure. I’ve covered it here: Raspberry Pi Email Server Part 3: Squirrelmail

Spamassassin, for Marking Spam

Spamassassin Logo

Spamassassin is the program that we will use to audit incoming mail and decide whether or not it’s spam. Spamassassin doesn’t actually sort the mail into the spam folder, it only changes information in the headers based on the results of the scan. I’ve covered it here: Raspberry Pi Email Server Part 4: Spam Detection with Spamassassin.

LMTP & Sieve for Spam Sorting & Mailbox Organisation

After Spamassassin has checked incoming mail to see if it’s spam or not, we need another program to sort it into the right mail folder. This final step will be done with Dovecot’s Local Mail Transfer Protocol (LMTP) daemon and a Sieve plugin. Sieve is a simple programming language that allows users to define what to do with incoming email based on a predefined set of rules – think “if the header contains this flag, put it in the spam folder” kind of thing and you’ll get the gist. Aside from spam filtering, Sieve can be used to automatically sort & de-clutter your inbox. These steps are covered in the final tutorial: Raspberry Pi Email Server Part 5: Spam Sorting with LMTP & Sieve Enjoy! I’d love to hear how you get on, so leave a comment below :)

Comments

Luis Interguglielmo

Fri, 05/02/2014 - 00:05

Estimado,
Gracias a su tutorial, he logrado configurar un servidor de correo, no siendo experto ni en correo ni en linux.
Le comento cual es mi problema y mi situación actual:

a) He cumplido al pie de la letra todos los pasos de los puntos 1 y 2.
b) He podido configurar clientes tanto en mi teléfono Android (K 9), en mi PC con el Thuderbird (version 24?), y en mi Ipad.
c) desde cualquiera de estos clientes, puedo enviar y recibir mensajes de usuarios "internos" a mi servidor, o sea:
- usuario 1 : configurado en mi servidor Raspi
- usuario 2 : configurado en mi servidor Raspi
Usuario 1 envia mail a Usuario 2 y todo bien. Viceversa tambien se cumple correctamente.
Pero aquí comienza mi problema.
Cuando desde el usuario1 o del usuario 2 envío un mail a un destinatario "remoto", o sea que no está en mi servidor de mail, este no lo recibe en algunos casos (aunque no recibo informe alguno de rechazo) - esto pasa por ejemplo cuando envío un mail a gmail.
Tampoco recibo los mails enviados por emitentes remotos (por ejemplo desde gmail), pero tampoco recibo ningún aviso de rechazo.

Solo tengo un destinatario probado que me rechaza los mensajes enviados por cualquiera de los usuarios (usuario 1 o usuario 2), por motivo de SMTP no Autenticado. (esto hace relación al RBL o algo así). No pude hallar en el cliente como solucionar este tipo de problema, ya que todas las ayudas hacen referencia a Thunderbird 3, que apaarentemente tiene otras opciones que ahora no estan a mi alcance.

O sea, que en definitiva, da la impresión que tengo problemas para salir de mi entorno.

Mi dominio está registrado y vigente y lo puedo utilizar para acceder remotamente a mi centro de operación.
He abierto los puertos indicados para que pasen directamente al servidor Rasp (por su dirección ip estática).
He configurado en mi ISP para que el tráfico SMTP sea ruteado a mi dominio (a mi dirección IP).

Ya no se me ocurre otra cosa para probar.

Estimo que es un detalle pero agradecería cualquier aporte que pueda Ud. brindarme.

Saludos cordiales,

Luis

first off :D YAY youre back :D (sorry bit late to the party)

just wondering if its possible to not have the web interface, and have a client like outlook or Thunderbird connect? maybe even deleting the email after its been pulled (save space on my SD card lol) My router is already forwerding all port 80 traffic to my pi thats hosting my blog, and lacks the ability to split traffic based on domain (dono why, its new)

thanks

Dan

Hi mate! It's nice to have been missed :) Yes it's possible to have postfix and dovecot without Squirrelmail. It's also possible to install Squirrelmail on your website Pi, and have it access your mail server remotely (Squirrelmail does just the same as Thunderbird does to connect to Dovecot and display your content: it logs in with IMAP, which you can do from anywhere). If you want to delete email after it has been pulled, look into POP (setup should be similar to IMAP)... but do you really want that? It means you can't connect more than one client machine to the same server (once the first client has received the message, it won't be there for the second client). You could also configure a gateway proxy on the website Pi to forward traffic to your mail server Pi... but don't change things without reading the manual! If you want to do either of these things, let me know and I'll help you out. Sam

Thanks for the warning ... that sounds rather nasty...
I'll have a think over the different options, and see what I can come up with :) I already posted on the pi forum, and been getting some advice there too :)

thanks again

Hi Sam,

Just wanted to take the time to say a big thank-you for this guide. I built a Raspberry-Pi into a 1U chassis with an external hard drive and some other peripherals, I was at a loss for something to make the hardware do when I came across your guide and my mind was made up instantly.

It was very easy to follow & the content was very thorough which is something that most guides lack. Thanks again for taking the time to create this wonderful guide!

Pete.

One other option you could cover (as I can't seem to get it to work) is to have a 'catchall' account so that anything sent to a wrong email address would have somewhere to land.

You're actually not the first to ask how to do this! Someone else asked me about it and actually found the answer themselves. Credit for this one goes to Jonathan: First, add a new user called "catchall" or something similar
sudo adduser catchall
Now add these lines to /etc/postfix/main.cf:
local_recipient_maps =
luser_relay = catchall
Now any email for unknown recipients in domains that match mydestination will be delivered to the catchall user. You can add that catchall user to an email client just the same as your normal account. Be aware you'll get loads more spam this way! Source: Ubuntuforums (instructions edited slightly). Hope that helps! Sam

I seen that info myself and gave it a whirl but it didn't work. I was able to do everything ad asked but the email isn't landing in that account

Petr

Rogier Schouten

Mon, 06/09/2014 - 10:44

Hi Sam, FYI the link to the 5th part of this tutorial is broken - it refers to part 4. Correct link is this link

Bruce Stelmar

Sun, 07/06/2014 - 23:04

Hi Sam,

Using your excellent tutorials, I now have my mail server up and running. But only for one domain. Do you have any suggestions on how (or if it is possible) to set this up for multiple domains?

Best Regards,
Bruce

Hi Bruce, Thanks :) If you set your mydestination parameter to include other domains then the server will accept email for those too (you need MX records for the other domains). If you have a system user called "pi" then the mailbox for pi will contain messages to pi@domain1.com and pi@domain2.com etc. Sam

Hi Sam,

Thanks for sharing this all-round tutorial! I have my RPi 1 up and running.

As you suggested, we can handle multiple domains by adjusting the mydestination variable. Great, but I want the mail different domains to funnel the various user accounts .. I saw one suggestion on another website, to use 'virtual accounts' .. but since we are using a file oriented mailstore (~/Maildir) this does not seem the ideal approach to me (is/would it?).

So question is : How to bind e-mail from certain domains to specific [mail / user] accounts?

Thanks for your time and effort!

Greetings,
Gerrit-Jan

Rui Branco

Thu, 07/10/2014 - 16:30

After that if you want use POP service in your RPI only need:
# sudo apt-get install dovecot-pop3d

and you'll also need to uncomment following line in /etc/dovecot/conf.d/10-master.conf:
service pop3-login {
inet_listener pop3 {
port = 110
}
inet_listener pop3s {
port = 995
ssl = yes
}
}

Rui

Hi Sam,

This is a great and understandable tutorial. I have the email server running on the raspberry.

Do you have a fallback scenario when your server is down for maintanace or even something worse? I don't want to lose any mail.

Martin

I was thinking about this recently, and was considering configuring another Pi at my parents' house and adding it to the MX record with a lower priority. That would mean I'm always able to send email (if the primary sever is down, message gets sent through the second one) and likewise email would land in the secondary server if there was a problem with the first. The question then is how to sync the two: possibly fetchmail on the primary server to retrieve email from the secondary one. I think this would mean that under normal circumstances you would get all of the email from the primary sever, including stuff that was delivered to the secondary one. If the primary server was down for any length of time your client would connect to the secondary server and fetch mail directly from there. Something to remember is that spammers sometimes deliberately connect to the lowest priority server in the MX record and send email to that one on the assumption that it will have worse spam filtering... so either the secondary Pi would have to pre-filter for spam, or fetched mail would have to be piped through spamassassin when it arrives at the primary server. There probably a cleverer way to do all that, too - it's hardly a new problem so I'm sure some clever people have cone up with great solutions! All of that aside, in my experience you never really lose email because if MTAs like Postfix can't connect to send you a message they try again, and again, and again with a longer delay each time. If they finally fail, the sender and postmaster receive an undeliverable mail message so whoever emailed you knows you didn't get it. When my pi bricked I had about 2 weeks where the mail server was down before I got my NUC. In the week after it was operational again I received delayed emails from my Dad via Yahoo, i.e. Yahoo's SMTP server trying again too deliver. Sam

Tom Simmons

Mon, 08/04/2014 - 21:56

I'm looking to set up a mail server on the Pi to replace my Microsoft hosted one.

It will be accessed by Outlook and a mail client on a Samsung Android phone. I'm looking for an exchange like set up, that is to say calendar, contacts and push email.

This guide covers the basic email, and obviously any client an be configured to talk to it, but from what I can see push isn't available?

Can anyone provide details on how to provide the missing parts I'm looking for, or a all in one option available on the Pi if there is one?

Thanks

Tom

Bob Daniel

Wed, 08/20/2014 - 18:39

I have a Synology NAS which gets the mail from the ISP with IMAP and from other accounts. The MX records for MYDOMAIN.com point to the ISP and I want to leave it like that. At the ISP all mail gets shoved into a catchall, which I pick up on the NAS and sort out with fetchmail (some horrible multidrop "poll" statement which took me ages to work out.) When I set it all up I had a rudimentary knowledge of email so perhaps I wouldn't do it the same now (not that I'm all that confident of doing it now!). On my local computers all the family members use sylpheed to read their mail from the NAS.
I want to plan for the day when the NAS dies. If I could then just change the port forwarding from NAS to Pi I would feel delighted. Does it make sense to attempt to replicate the fetchmail/dovecot/postfix setup on the NAS on the Pi?

Apologies if this is barely coherent.

Hi :) I've never experimented with fetchmail but I'm sure you could integrate it with this setup pretty easily. Can I ask why you don't want to change the MX record to point at your IP address directly? Is your internet connection unreliable? It seems like a bit of a pain to jumble everything up and then sort it out again! I don't get what you mean about port forwarding... if all your mail reaches your LAN with fetchmail (i.e. the connection to your ISP is always initiated by the client) then you shouldn't need any port forwards? Or have I misunderstood how fetchmail works? Sam

Thanks Sam
1. I had a terror of changing the MX records and losing mail. Plus, I don't have a static IP address; I use Synology's dynamic XXXXXX.synology.me thingy.
2. I use my router (a BT Business Hub, don't ask why) to send incoming stuff to the Synology with port forwarding. I've only opened the ports that I found the Synology needs for what I do with it. My idea was just to change the destination of the port forwards to the Pi when the Synology crashes - simple.
(fetchmail stores the incoming stuff on the NAS)
Sorry about the vagueness/poor terminology. I am self-taught about system stuff, when I retired. And my brain isn't what it was.
Bob

I have a Synology NAS which gets the mail from the ISP with IMAP and from other accounts. The MX records for MYDOMAIN.com point to the ISP and I want to leave it like that. At the ISP all mail gets shoved into a catchall, which I pick up on the NAS and sort out with fetchmail
I think I get it! The port forward is to allow you to connect to the NAS from outside your LAN, right? Lol. That stumped me for a while there, sorry for being slow. Are you using IMAP to connect your email clients to your NAS (I.e. is the NAS also an IMAP server)? Why don't you just fetch your mail directly from your ISP's IMAP server to each client? I don't see what you gain by bringing it in to your LAN and then fetching it again... It would make sense if your ISP only offered POP, because connecting directly would mean the email would be removed from your ISP's server after the first client fetched it. Anyway... yes it's definitely possible to do what you want. In fact, you can just follow the whole tutorial which will give you a fully functional email server, and then choose not to forward ports 25 and 465 to the Pi. If you then configure fetchmail on the Pi to retrieve your email from your ISP and hand over to postfix, that will be equivalent to your server receiving emails directly through port 25. As you said, you should then be able to swap the IMAP port forward to the Pi from the NAS. What's your current outgoing email setup? Do you send email through your ISP's SMTP server? Sam

Bob Daniel

Thu, 08/21/2014 - 10:51

Dear Sam
Sorry I wasn't clear enough. As I don't have the right language I was obviously fumbling. I have found the client/server model of email to be fundamentally unhelpful as packages do more than just their simple functionality (e.g. dovecot)

To answer your questions first.
Yes, I do connect to the NAS from outside the LAN e.g. when on holiday.
Yes, I use IMAP to connect the various PCs in the house to the NAS. I wanted to have the email centrally so any family member can use any PC to access their email.
Yes, I send outgoing email through my ISP's SMTP, using Sylpheed to keep a copy on the NAS.
I believe that doing things this way keeps a copy of all email (in and out) on the NAS. Periodically I delete all email that's stored at the ISP.

I own MYDOMAIN and use lots of different blah@DOMAIN when I sign up for various things so I can track whom they sell the email address to. I use this as a 2nd level spam filter. So I have to have a catchall anyway. I suppose I could set up lots of mailboxes at my ISP, but I believe they have a maximum number. Perhaps I should have a mailbox there for each "proper" email address and a catchall for the pseudo-junk.

Can I thank you so much for the help you are giving me. I owe you a bottle of very nice wine. It's been a hard grind getting from a position where I had a support department to doing things on my own!
Bob

I actually don't think it was you, I was being very slow yesterday! The one thing that would have made it easier to understand is if I'd known what the Synology NAS thing was. It sounds like it's more than just Network Attached Storage (NAS) - it's also an email server if it's running Dovecot and Postfix. "Home Server" would probably be a better description, since it does so many things. So, it sounds like when you send email you connect to Postfix (or another Mail Transfer Agent (MTA) like Sendmail) on the home server and it relays your email through your ISP. Can you confirm that you have the following ports forwarded to the home server from your router, just to confirm we're on the same page?
  • Port 25 or 465 or 587 for SMTP
  • Port 143 or 993 for IMAP
By the way, you don't have to create a new system user every time if all of those are aliases for you - this tutorial has a section on adding aliases (for example, I have aliases for postmaster, webmaster, root etc. pointing to my user). Sam

Bob Daniel

Thu, 08/21/2014 - 17:01

The Synology NAS is just a Linux box with lots of installable packages. One of these it calls "mailserver" and when set up it runs, inter alia, dovecot and postfix. I must have set up fetchmail but age dulls the memory. Heaven only knows what else mailserver does; looking at the executable it has references to postfix and dovecot. These are in the same directory as mailserver: clamd dovecot postalias postcat postconf postdrop postfix postkick postlock postlog postmap postmulti postqueue postsuper saslauthd -> /usr/sbin/saslauthd sendmail syno_mailloggerd

nmap says the BT hub has these ports open and forwarding to the Synology: 22, 80, 143, 993, and some irrelevant others. Port 25 isn't forwarded to the Synology, but I can telnet to port 25 internally and get postfix. I cannot telnet to port 25 from outside (no surprise there). This makes me wonder how the mail runs fine on the Synology and has destroyed my paradigm completely.

I really am grateful for your help.
Bob

Add new comment

The content of this field is kept private and will not be shown publicly.

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.