# Running your own mail server



## wlanboy (Aug 9, 2013)

This tutorial is about setting up a mailserver. It is based on my own efforts to not use gmail any longer.
I want to keep my own emails and I want to keep my own backups.

Running your own mail server is pain. This is something you have to monitor all the time. And as long as your server is not encrypted (and even if) you should use a client based enryption for your email client.

It is also a good idea to separate this from your other services. I am using a small 128 MB vps that is only running the mail server. It is fine for 5 users. If you want to run additional services like clamav and if you have more than 5 users you should use 512 MB of RAM.

This post will be updated once a week. This topic is quite huge so I will need some iterations to complete this tutorial. I also want to include all feedback to ensure that this tutorial is up to date.

Because email servers can have a lot of features like:


marking spam
graylisting
virus scanning
virtual mappings
etc
I will mark every step that is just adding a feature as *OPTIONAL*.

So let's start with the preparations:

*1. Setup your DNS:*

*Create an A record* that is pointing to your vps (which should run the mailserver).


mailserver 55.55.55.55 A 1800
mailserver 2500:f5f5:25::b25f:2525 AAAA 1800

I use a service oriented nameing shema so in my case: "mailserver.domain.com". This name is quite important because it is used in a lot of different places.

You can add additional cnames to ensure that all the mail clients find the correct ips:


pop3 mailserver.domain.com. CNAME 1800
pop mailserver.domain.com. CNAME 1800
imap mailserver.domain.com. CNAME 1800
smtp mailserver.domain.com. CNAME 1800

And the AAAA records too if you want to support IPv6.

*Create a MX record* for your domain and subdomains


@ mailserver.domain.com. MX 10 3600

"@" is an alias for you domain. So all email for your domain should be sent to "mailserver.domain.com"

You have to create records for your subdomains too:


mysubdomain mailserver.mydomain.com. MX 10 3600

And to ensure that SPF gets more support add this TXT DNS entry too:


@ IN	TXT	"v=spf1 mx -all"

This adds the additional security that you say that only your MX entries are allowed to send emails for your domains. Quite obvious but you can add other ips too:


@ IN	TXT	"v=spf1 mx ip4:11.22.33.44 a:mail.company.com -all"

This states that all MX servers, the IP 11.22.33.44 and the mail.company.com are allowed to send emails for your domains.

Why? Because sometimes (e.g. for forums/mailing lists) an external company is sending emails for your domains. This is a way to approve them.

*2. Setup your rDNS:*
Go to your vps control panel and add the DNS record "mailserver.domain.com" to your IP address 55.55.55.55.

*3. Setup your mailname in /etc*


sudo nano /etc/mailname
Add "mailserver.mydomain.com"

*4. Setup your iptables rules*
You find the rules here. But I add them here too:


# allow SMTP
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 25 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 25 -j ACCEPT

# allow SMTPS
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 465 -j ACCEPT
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 587 -j ACCEPT

ip6tables -A INPUT -i $device -p tcp --dport 465 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 587 -j ACCEPT

# allow POP3
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 110 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 110 -j ACCEPT

# allow POP3S
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 995 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 995 -j ACCEPT

# allow IMAP
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 143 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 143 -j ACCEPT

# allow IMAPS
iptables -A INPUT -i $device -m state --state NEW -p tcp --dport 993 -j ACCEPT
ip6tables -A INPUT -i $device -p tcp --dport 993 -j ACCEPT

If you run this server with SSL certs you can disable the POP3 and IMAP rules.

A lot of email clients first try the non-SSL ports and will therefore suggest a not secured connection.

Keep in mind that all communication without SSL is not save.

*5. Setup your mail server*
Installation is really simple because of the great package: *dovecot-postfix*


sudo apt-get install dovecot-postfix

After using some other mail daemons for a while I do prefer the postfix/dovecot combo.

Postfix is mail daemon like sendmail but whith a real nice pipe framework. It is really easy to tunnel email through different modules. Dovecot is a daemon that provides pop3 and imap access to the mail accounts.

*6. Config dovecot*
Dovecot is providing access to your emails via pop/imap.
Only file to edit is /etc/dovecot/conf.d/10-auth.conf


nano /etc/dovecot/conf.d/10-auth.conf

Remove the # of the line "disable_plaintext_auth = yes"

*7. Config postfix*
*Edit the file /etc/postfix/main.cf*


nano /etc/postfix/main.cf

Things to edit:


mydomain = domain.com
myorigin = domain.com
myhostname = mailserver.domain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
local_recipient_maps = $alias_maps
mydestination = domain.com, mailserver.domain.com, subdomain.domain.com, localhost

smtpd_recipient_restrictions = 
reject_unknown_sender_domain, 
reject_unknown_recipient_domain, 
reject_unauth_pipelining, 
permit_mynetworks, 
permit_sasl_authenticated, 
reject_unauth_destination,
reject_rbl_client zen.spamhaus.org, 
reject_rbl_client bl.spamcop.org

smtpd_data_restrictions =
reject_unauth_pipelining,
reject_multi_recipient_bounce,
permit

So what I am doning here?

I define the domain and origin of the mail server. He should handle the domain "domain.com".

I define an alias map to map different email accounts to different linux users.

And I define all allowed destinations - including all subdomains. And of course "localhost" for all my scripts.

All mail for a different domain will be rejected.

"smtpd_recipient_restrictions" is a list of filters to ensure that we did not get spammed.

"reject_rbl_client" is a referrer to one of the spam lists provided by different groups. I do like spamhaus and spamcop.

"check_policy_service" is used for my favorit greylister. Greylister do something very bad. They dismiss emails - out of the fact that real and good mail servers will try again. A lot of spammers don't have time to wait for any retries.

I know that this is ... still in discussion ... but for a private mail server it just saves a lot of time.

Another time saver is local_recipient_maps. So every email like "[email protected]" will be rejected if the mail address is not within the alias map. You do only receive emails to mailboxes you added.

*Edit the file /etc/postfix/master.cf *


nano /etc/postfix/master.cf 

Things to edit:


submission inet n - - - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
-o milter_macro_daemon_name=ORIGINATING

dovecot unix - n n - - pipe
flags=DRhu argv=/usr/lib/dovecot/deliver -f ${sender} -d ${recipient}

Be carefull ... spaces etc. do count!

So what did I change?

I have added an output pipe for spam assassin and one for dovecot.

Postfix is recieving all mails and has to forward them to dovecot. Additionally a content_filter is set (defined at the end of the file) to ensure that the mails are sent to spamassassin and afterwards to dovecot.

*8. Config aliases*

I do prefer aliases instead of virtual mappings. I don't want to run a MySQL server to choose who is getting what email. There are a lot of tutorial on how to use virtual mappings. I stick to simple config files.

There are some DDOS attacks too that aim at a high load of MySQL querries too.

Now edit the file /etc/aliases


nano /etc/aliases

Content:


#
# Mail aliases for sendmail
#
# You must run newaliases(1) after making changes to this file.
#

# Required aliases
postmaster:	wlanboy
MAILER-DAEMON:	postmaster

# Common aliases
abuse: postmaster
spam: postmaster

# Other aliases
webmaster: wlanboy
contact: wlanboy
root: wlanboy
user1: user1
wlanboy: wlanboy

Double check that you do not map circles like: postmaster -> spam -> wlanboy -> admin -> admin -> postmaster.

You wont have any chance to see the cause in the logfiles.

On the left side are email addresses like "[email protected]".

On the rigth side there are linux users which will receive the emails.

Afterwards you have to run "newaliases" to generate the alias map file.


sudo newaliases

To add a new user just type:


sudo useradd -m -s /bin/false [username]
passwd [username]

This ensures that this user can only login into your mail server and not use any other services like ssh/scp/rsync.

*9. OPTIONAL: Install postgrey*


sudo apt-get install postgrey
sudo nano /etc/default/postgrey
add:
POSTGREY_OPTS="--inet=127.0.0.1:10023 --delay=55"

The OPTS I add are:


listening to localhost only
add a delay of 55 seconds
Afterwards you have to *edit the file /etc/postfix/main.cf*
 


nano /etc/postfix/main.cf


```
smtpd_recipient_restrictions = 
  reject_unknown_sender_domain, 
  reject_unknown_recipient_domain, 
  reject_unauth_pipelining, 
  permit_mynetworks, 
  permit_sasl_authenticated, 
  reject_unauth_destination,
  reject_rbl_client zen.spamhaus.org, 
  reject_rbl_client bl.spamcop.org,
  check_policy_service inet:127.0.0.1:10023
```
Add the check_policy_service inet:127.0.0.1:10023 to the smtpd_recipient_restrictions.

*10. OPTIONAL: Install spam assassine*

Enhance postfix configuration:


nano /etc/postfix/master.cf

Things to edit:


smtp inet n - - - - smtpd
-o content_filter=spamassassin

submission [.....]
dovecot [.....]

spamassassin unix - n n - - pipe
user=spamd argv=/usr/bin/spamc -f -e 
/usr/sbin/sendmail -oi -f ${sender} ${recipient}

And now install spam assassine


sudo apt-get install libnet-dns-perl pyzor razor libdigest-sha-perl libencode-detect-perl libdbi-perl libgeo-ipfree-perl libnet-ident-perl 
sudo apt-get install spamassassin
sudo adduser --system --no-create-home spamd

Afterwards you have to activate it:


sudo nano /etc/default/spamassassin
change to: ENABLED=1
sudo service spamassassin restart

Update spam asssasin rules:


cd /etc/spamassassin/
wget http://yerp.org/rules/GPG.KEY
sa-update --import GPG.KEY
sa-update --gpgkey 6C6191E3 --channel sought.rules.yerp.org

sa-update -D -v

*11. Install fail2ban*


sudo apt-get install fail2ban

You have to configure the services fail2ban has to check:


sudo nano /etc/fail2ban/jail.conf

Things to edit:


bantime = 3600
maxretry = 2

action = %(action_mw)s

[pam-generic]
enabled = true

[postfix]
enabled = true
port = smtp,ssmtp
filter = postfix
logpath = /var/log/mail.log

[sasl]
enabled = true
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = sasl
# You might consider monitoring /var/log/mail.warn instead if you are
# running postfix since it would provide the same log lines at the
# "warn" level but overall at the smaller filesize.
logpath = /var/log/mail.log

[dovecot]
enabled = true
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = dovecot
logpath = /var/log/mail.log

What did I do?

Set the bantime to 1 hour and the number of retries before ban to 2.

And enabled the observation of pam-generic, postfix, sasl and dovecot.

So all mail related login actions are checked.

*12. OPTIONAL: Own SSL configuration*

The package is creating self signed certificates. So if you want to change them because you want to use official ssl certs edit following lines:


/etc/postfix/main.cf
/etc/dovecot/conf.d/10-ssl.conf
/etc/dovecot/conf.d/01-mail-stack-delivery.conf

/etc/postfix/main.cf:smtpd_tls_cert_file = /etc/ssl/certs/ssl-mail.pem
/etc/postfix/main.cf:smtpd_tls_key_file = /etc/ssl/private/ssl-mail.key

/etc/dovecot/conf.d/10-ssl.conf:ssl_cert = </etc/ssl/certs/dovecot.pem
/etc/dovecot/conf.d/10-ssl.conf:ssl_key = </etc/ssl/private/dovecot.pem
/etc/dovecot/conf.d/01-mail-stack-delivery.conf:ssl_cert = </etc/ssl/certs/ssl-mail.pem
/etc/dovecot/conf.d/01-mail-stack-delivery.conf:ssl_key = </etc/ssl/private/ssl-mail.key

*13. OPTIONAL: Set rate limits*

If your mail server is used by yourself ... you do not need to limit the number of emails a user can send.

Edit /etc/postfix/main.cf


sudo nano /etc/postfix/main.cf

And add these lines at the end of file:


smtpd_client_event_limit_exceptions = $mynetworks
#Clients that are excluded from connection count
anvil_rate_time_unit = 60s 
#The time unit over which client connection rates and other rates are calculated. 
anvil_status_update_time = 120s 
#How frequently the server logs peak usage information. 
smtpd_client_message_rate_limit=5 
#The maximal number of message delivery requests that any client is allowed to make to this service per time unit.

So each client - not connected through $mynetworks - is only able to send 5 emails per 60 seconds.

*14. OPTIONAL: DKIM*

Well ....



> DomainKeys Identified Mail (DKIM) is a method for E-mail authentication, allowing a person who receives email to verify that the message actually comes from the domain that it claims to have come from. The need for this type of authentication arises because spam often has forged headers.


So your mail server can sign your emails to ensure that someone can check if the emails are from your approved mail servers.

Installation is quite easy:


sudo apt-get install opendkim opendkim-tools

For 12.04 you have to use backports:


sudo apt-get install opendkim/precise-backports
sudo apt-get install opendkim-tools/precise-backports

Configuration is done on two files:


/etc/opendkim.conf
/etc/default/opendkim
Things you have to change:


nano /etc/opendkim.conf
UserID 105 # 'id postfix' in your shell
Domain domain.com
KeyFile /etc/mail/dkim.key


```
nano /etc/default/opendkim
SOCKET="inet:54321" # listen on all interfaces on port 54321
#Don't forget to allow this port on iptables
```
Now we have to tell postfix to use this service:


nano /etc/postfix/main.cf
# DKIM
milter_default_action = accept
milter_protocol = 2
smtpd_milters = inet:localhost:8891
non_smtpd_milters = inet:localhost:8891

To generate the key run following command:


cd /etc/mail
sudo opendkim-genkey -t -s mail -d domain.com
cp mail.private /etc/mail/dkim.key

The DNS TXT entry should be a copy&paste of mail.txt


mail._domainkey.domain.com. IN TXT "v=DKIM1; g=*; k=rsa; p=openssl_public_key";

*15. OPTIONAL: Add backup MX*

First of all you have to add an additional MX record with a higher priority:


@ mailserver.domain.com. MX 10 3600
@ backupmailserver.domain.com. MX 20 3600

Everyone is first trying to send the email to mailserver.domain.com, if it is not reachable backupmailserver.domain.com is used.

The higher the priority the lower the chance that someone is using the MX server.

Next change of the backup mail server is the main.cf:


relay_domains = $mydestination, hash:/etc/postfix/relay_domains
transport_maps = hash:/etc/postfix/relay_transport

Now we have to define the relay domains:


nano /etc/postfix/relay_domains

Content:


domain1.com anything
domain2.com anything
domain3.com anything

A backup MX can be responsible for more than one domain.

Now we have to define what the backup mail server should do with an incoming email:


nano /etc/postfix/relay_transport

Conent:


domain1.com relay:mailserver.domain1.com
domain2.com relay:mailserver.domain2.com
domaint3.com relay:mailserver.domain3.com

Just forward them to the real mail servers.

Last step is to map both files:


cd /etc/postfix
postmap relay_domains
postmap relay_transport

If you want you can add a time to live for the emails too:


maximal_queue_lifetime = 60d 

So the backup server will store the mails for 60 days. Hopefully your main mail server will not be offline for more than 60 days.

*16. Restart you vps*

Done.

*Comments:*

We now have a smtp/pop3/imap server that uses graylisting, spam assassine and a white list of mail addresses to ensure that you only receive mails you want.

Additionally fail2ban bans everyone trying to get access to your mail server.

Postfix and dovecot are by default supporting IPv6. You only have to add the AAAA records to ensure you mail server is accessable via IPv6.

You can even decide to drop the iptables/ip6tables rules for SMTP/POP3/IMAP to ensure every client is only using SSL secured connections.

If you need a GUI for this mail server:

Use a second vps with webserver and php and install roundcube.

*Additional notes:*

Yup you are right there is not a fancy clicky GUI to add new mailboxes. But I like the idea to keep things simple.

Adding a user to a linux system (one without a console access) is dead simple. Adding an alias for him too.

This is a private server - so you will not add new users every minute.

A lot of things a file based so the whole system is not using a lot of resources. A real low end mail server running on a 128 MB vps:


free
total used free shared buffers cached
Mem: 131072 82560 48512 0 0 28564
-/+ buffers/cache: 53996 77076
Swap: 131072 15808 115264

This is the state without any active connections. Dovecot is using some RAM for each logged-in user.

This tutorial is quite long and as you can see most of the steps is about securing your mail server. Mail servers are still targets of quite a lot of attacks. These attacks are simple and don't need a lot of time of traffic. So an easy target. The ports cannot be changed too so you know that port 25 is listening.

So a lot of arguments to run your mail server on another vps.

Multiple Domain instructions are here: http://vpsboard.com/topic/1506-running-your-own-mail-server/page-2#entry28355


----------



## drmike (Aug 9, 2013)

Wow, there goes my upcoming weekend   You are most excellent @wlanboy!

Someone give this tutorial a spin and see how it goes.


----------



## MannDude (Aug 9, 2013)

buffalooed said:


> Wow, there goes my upcoming weekend   You are most excellent @wlanboy!
> 
> Someone give this tutorial a spin and see how it goes.


I'll tinker with it this weekend. Got an idle VPS sitting around.


----------



## wlanboy (Aug 9, 2013)

I hesitated for weeks if I should write this tutorial.

You can get a lot of trouble if the security of your mail server breaks. You can loose your mails too if you do not run backups.

I am running my mail server for about 1 1/2 years. Everything is fine - but mabe this is based on luck.


----------



## drmike (Aug 9, 2013)

wlanboy said:


> You can get a lot of trouble if the security of your mail server breaks. You can loose your mails too if you do not run backups.


I'd rather have security issues and something break than continue to feed the monster systems directly and willingly.

Hopefully, others chime in with recommendations to build upon this tutorial.


----------



## wlanboy (Aug 9, 2013)

buffalooed said:


> I'd rather have security issues and something break than continue to feed the monster systems directly and willingly.


Totally agree. Same reason why I am running my own mail server.


----------



## Amitz (Aug 9, 2013)

You are surely aware of that fact that you are feeding the monsters already by sending and receiving unencrypted eMail alone. But I guess you meant the corporation monsters and not the government monsters... However, I was was always looking for a good step-by-step tutorial for setting up my own mailserver (without having to use a panel) and I am VERY thankful for your posting, wlanboy!

Like others already said: There goes my weekend! ;-)


----------



## drmike (Aug 9, 2013)

Amitz said:


> You are surely aware of that fact that you are feeding the monsters already by sending and receiving unencrypted eMail alone


Oh no doubt.  

But, I use PGP to encrypt my real emails with some people.  That's when I actually use email.  

I'll be interested in seeing how your install goes @Amitz.  Everyone report back when they get this running or don't.


----------



## wlanboy (Aug 9, 2013)

Amitz said:


> You are surely aware of that fact that you are feeding the monsters already by sending and receiving unencrypted eMail alone.


Yup, but encryption should not be on server side! It should be client based. Even if someone is taking the whole disk or tracing tcp packets- they cannot read anything without the GnuPG keys on my local disk.



buffalooed said:


> But, I use PGP to encrypt my real emails with some people.  That's when I actually use email.


Me too.

Looking to the RAM usage per login:


23957 ? S 0:00 0 0 5180 2528 1.9 dovecot/imap-login
23958 ? S 0:00 0 0 4412 2212 1.6 dovecot/imap
23960 ? S 0:00 0 0 5172 2536 1.9 dovecot/imap-login
23961 ? S 0:00 0 0 4292 2080 1.5 dovecot/imap

5 MB of RAM per user should be sufficient.


----------



## tdc-adm (Aug 9, 2013)

Thank you wlanboy. Do you know how to limit the sending rate? I'd like to set up a send-only server for multi users.


----------



## wlanboy (Aug 9, 2013)

buffalooed said:


> Everyone report back when they get this running or don't.


After buying a new vps from ramnode (NL) I have setup my brand new mail server for my domain wlanboy.com (was once hosted at hotmail).

You can test my mail server by sending an email to [test][at][wlanboy].[com]


----------



## shawn_ky (Aug 9, 2013)

Good tutorial! I'm about to repurpose another VPS so will use this instead of an utosetup with a panel and see how it goes... I'll be using Centos, but config files are config files.


----------



## wlanboy (Aug 9, 2013)

tdc-adm said:


> Thank you wlanboy. Do you know how to limit the sending rate? I'd like to set up a send-only server for multi users.


This is done in /etc/postfix/main.cf


```
smtpd_client_event_limit_exceptions = $mynetworks
#Clients that are excluded from connection count
anvil_rate_time_unit = 60s 
#The time unit over which client connection rates and other rates are calculated. 
anvil_status_update_time = 120s 
#How frequently the server logs peak usage information. 
smtpd_client_message_rate_limit=5 
#The maximal number of message delivery requests that any client is allowed to make to this service per time unit.
```


----------



## wlanboy (Aug 13, 2013)

Anyone interested in server side virus scanner?


----------



## drmike (Aug 13, 2013)

Server side virus scanner for the email?  Well, good for the WIndozer users I guess.   I don't need it personally


----------



## nixcom (Aug 13, 2013)

Good howto!


----------



## splitice (Aug 13, 2013)

buffalooed said:


> Server side virus scanner for the email?  Well, good for the WIndozer users I guess.   I don't need it personally


Its good for spam reduction  Those spammers be always trying to target the lowest denominator.

But seriously good howto, but I think I will stick with Zimbra. Never been willing to accept the risk myself. It would be nice to see integrated backup into the tutorial (e.g to Backupsy), I hate to say it but its a must in this day and age.


----------



## wlanboy (Aug 14, 2013)

Added SPF and DKIM to the tutorials. Later just for the sake of having it.


----------



## Maximum_VPS (Aug 14, 2013)

Excellent tutorial / walk through wlanboy! Though i use iredmail this style is my preferd for low ram use / leb's


----------



## jcaleb (Aug 14, 2013)

thanks, been waiting for such tutorial


----------



## rm_ (Aug 14, 2013)

> Added SPF and DKIM to the tutorials. Later just for the sake of having it.


Don't overcomplicate it, was already too much with all the greylisting/filtering, people are just going to glance over and decide, "nah this is too difficult and time-consuming, guess I'm staying with GMail". What's wrong with just showing how to get basic postfix+dovecot running, and all the extra stuff as separate tutorials? Also for example I don't even use any spam filtering on the server, just got a Bayesian plugin for my mail client (Claws-mail), works perfectly, and worlds simpler to set up and use.


----------



## wlanboy (Aug 15, 2013)

rm_ said:


> Don't overcomplicate it, was already too much with all the greylisting/filtering, people are just going to glance over and decide, "nah this is too difficult and time-consuming, guess I'm staying with GMail". What's wrong with just showing how to get basic postfix+dovecot running, and all the extra stuff as separate tutorials? Also for example I don't even use any spam filtering on the server, just got a Bayesian plugin for my mail client (Claws-mail), works perfectly, and worlds simpler to set up and use.


I was thinking about splitting the tutorials too, but it is easier to maintain this topic in one complete list of todos.

If you have to open 10 posts to see what you can do / should do, the reader can easily lose track. It might look difficult too if I say "please read this 10 threads in this order and afterwards you know what you have to think about".

This is the main reason why I am updating my first post every week on each tutorial. Each comment and suggestion is used to make my tutorials better. No one should have to read through all the pages to see if the original post is still up to date.

I have now marked all things that you do not need as *OPTIONAL*.

But all steps should stay in this tutorial because everyone reading through it does have a chance to say "hey this feature is cool - I take the extra work for it".


----------



## peterw (Aug 19, 2013)

Great tutorial. I added a rule on maildrop to move all spam mails to a spam folder.


```
/etc/courier/maildroprc

if ( /^X-Spam-Flag: YES/ )
{
to “Maildir/.Spam”
}
```


----------



## drmike (Aug 19, 2013)

Great work and thanks for updating the original tutorial/how to.

Eventually, I'll get this tested.  Time is a luxury currently.


----------



## HDPIXEL (Sep 2, 2013)

Can you add notes or any additional configuration for using this tutorial with multiple domains on the same server?  Thank you so much for this.


----------



## wlanboy (Sep 3, 2013)

HDPIXEL said:


> Can you add notes or any additional configuration for using this tutorial with multiple domains on the same server?  Thank you so much for this.


Depends on the stuff you want to do.

If you have different users per domain you have to setup vitual mapping. This will be added to the tutorial later.

If you just want to add a second domain following steps have to be done:


Add MX, CNAME, SPF records to second domain (with the same ips of the mailserver)
Edit the file /etc/postfix/main.cf
And add the additional domains/subdomains to the mydestination line. Like:


mydestination = domain.com, subdomain.domain.com, domain.net, subdomain.domain.net

Keep in mind that this setup have some drawbacks. Because [email protected] and [email protected] ends up into the same mailbox. Because we do not have a domain based mapping (like virtual mappings have).

PS:


Cannot edit the original post so I have to add this here.


----------



## drmike (Sep 4, 2013)

Thanks for the additional info on multiple domains and willingness to append the original tutorial.

I'll ask about the post editing again. Not sufficient as-is where you and others edit/append useful information to their original post.


----------



## blergh (Sep 4, 2013)

rm_ said:


> Don't overcomplicate it, was already too much with all the greylisting/filtering, people are just going to glance over and decide, "nah this is too difficult and time-consuming, guess I'm staying with GMail". What's wrong with just showing how to get basic postfix+dovecot running, and all the extra stuff as separate tutorials? Also for example I don't even use any spam filtering on the server, just got a Bayesian plugin for my mail client (Claws-mail), works perfectly, and worlds simpler to set up and use.


Overcomplicate it? You sir are an idiot if you think DKIM/SPF is "overcomplicating it". If you are going to setup and run your own mail, at least do it right. Cutting corners is just going to make your service run like shit.


----------



## acd (Sep 4, 2013)

I often disagree with blergh, but this time, he is absolutely right. DKIM and SPF has been made so easy to install on debian, you can do it in about 10 minutes. This guide elucidates how easy the process is. Granted, it could be made easier if debian's post-config script auto-installed into postfix's filter chains, but we can't have everything for free.

https://kura.io/2011/09/17/postfix-dk-dkim-spf/

Please configure your domains with spf records and in it, please use -all (not ~all). Reduce spam for everyone.

best regards,

-tw


----------



## HalfEatenPie (Sep 4, 2013)

wlanboy said:


> Depends on the stuff you want to do.
> 
> If you have different users per domain you have to setup vitual mapping. This will be added to the tutorial later.
> 
> ...


I did a pretty crappy edit to the main post.  let me know if I should fix it up differently.  Thanks for this fantastic tutorial buddy!


----------



## rm_ (Sep 5, 2013)

> You sir are an idiot if you think DKIM/SPF is "overcomplicating it". If you are going to setup and run your own mail, at least do it right. Cutting corners is just going to make your service run like shit.


Hello!

Yes, DKIM is some silly crap invented by Yahoo for no good reason, I completely ignore it.

SPF is an extravagancy you can bother with "to feel good about yourself" if you have too much free time, but in reality no one cares about SPF anyway, and you can not practically set hardfails either, since it breaks too much stuff such as forwarding.

And yes, both are unnecessary for a basic mail server. The principal thing to do is to ensure your IP is not in RBLs (can use http://bgp.he.net/ for that, it can check 51 RBLs automatically). Other than that, yes, DKIM and SPF are awesome-on-paper, pie-in-the sky ideas that (unfortunately?)went exactly nowhere in the real world.


----------



## peterw (Sep 5, 2013)

acd said:


> .





rm_ said:


> .


Can you please calm down? Everyone knows your opinion about this.



HalfEatenPie said:


> Thanks for this fantastic tutorial buddy!


Thank you wlanboy. My mailserver is running!


----------



## rm_ (Sep 5, 2013)

blergh said:


> Overcomplicate it? You sir are an idiot


Somehow you did not feel the need to ask *blergh* to "calm down" after the above crap, yet my response which addresses all of his points without personal insults is somehow "not calmed down enough" for you?



peterw said:


> Can you please calm down?


----------



## sleddog (Sep 5, 2013)

rm_ said:


> Don't overcomplicate it, was already too much with all the greylisting/filtering, people are just going to glance over and decide, "nah this is too difficult and time-consuming, guess I'm staying with GMail". What's wrong with just showing how to get basic postfix+dovecot running, and all the extra stuff as separate tutorials? Also for example I don't even use any spam filtering on the server, just got a Bayesian plugin for my mail client (Claws-mail), works perfectly, and worlds simpler to set up and use.


I agree with this. Mail setup should be modular. First, the core setup that gets mail flowing, then the 'addons'.

Each addon needs to be evaluated and an informed decision made as to whether or not it appropriate or required.

The newbie mail admin really needs to understand how all the components interact. Simply copying/pasting commands and configurations is not only confusing but leads to problems down the road, when something breaks and he/she has no idea how to fix it.


----------



## wlanboy (Sep 5, 2013)

HalfEatenPie said:


> I did a pretty crappy edit to the main post.  let me know if I should fix it up differently.  Thanks for this fantastic tutorial buddy!


Thank you. Maybe you should write your name.

"HEP" is quite short...



sleddog said:


> I agree with this. Mail setup should be modular. First, the core setup that gets mail flowing, then the 'addons'.


Totally agree.

I have added optional tasks out of this reason.



> Because email servers can have a lot of features like:
> 
> 
> marking spam
> ...


----------



## HalfEatenPie (Sep 5, 2013)

wlanboy said:


> Thank you. Maybe you should write your name.
> 
> "HEP" is quite short...


Done!


----------



## grayfuz (Sep 9, 2013)

how can you prevent your emails going gmail spam folder?


----------



## peterw (Sep 9, 2013)

grayfuz said:


> how can you prevent your emails going gmail spam folder?



Don't send spam
Don't use dynmaic ips for sending emails
Remove your ip from spam blocklists
Configure rDNS and MX
Create SPF
Send all messages from the same ip (per domain)
Sign email with domain keys or DKIM
If you mass email add a list-unsubscribe header


----------



## grayfuz (Sep 9, 2013)

thanks.. i already did all of that but still my emails are going to gmail spam folder. any more suggestions?


----------



## Aldryic C'boas (Sep 9, 2013)

If you have this running on a VM, it's very likely that Google has already greylisted the provider's IP ranges.  Safest bet is to contact Google directly, explain exactly what your mail server is used for (personal, mass, etc), and request a whitelisting for your assigned IP/domain.  If your provider offers SWIP, having the assigned IPs SWIP'd to your name will also help.


----------



## grayfuz (Sep 9, 2013)

thanks.. how long does this usually take? does colo crossing supports swip?


----------



## Aldryic C'boas (Sep 9, 2013)

grayfuz said:


> thanks.. how long does this usually take? does colo crossing supports swip?


Hearing back from Google?  Could be anywhere from a week to six months.  I've _never_ had decent reply turnaround from them unless it involved giving them money.

As far as ColoCrossing and SWIP... that's going to be a bit more difficult, regardless of whether they'll do the SWIP for you.  The problem there is that I've noticed a rather high percentage of abuse (both spam and network-related) coming from CC IP ranges - to the point that I've straight-up blacklisted a bunch of them from even being able to reach our clients.  It's very possible that their ranges may already be blacklisted at major email providers due to past spam complaints.

Velocity-Servers is a good example of this.  Their SpamHaus listing is pretty nasty ()http://www.spamhaus.org/sbl/listings/velocity-servers.net - including several ROKSO listings), and seeing as how they're on CC IP Space (http://whois.arin.net/rest/nets;q=216.246.49.27?showDetails=true&showARIN=false&ext=netref2), you're going to have a hard time getting your assigned IP whitelisted anywhere.

Best course of action if you're sending emails that have to get through - either run your mail server on a provider with 1) clean netblocks, and 2) a solid history of actively dealing with spam;  or just use AmazonSES.  SES is fairly cheap (we send out something like 50-70k emails a month, and it costs less than 5$), they're whitelisted for Google, Yahoo, and other major mail providers, and it's real easy to work with.


----------



## wlanboy (Sep 9, 2013)

grayfuz said:


> thanks.. i already did all of that but still my emails are going to gmail spam folder. any more suggestions?


Try MX Lookup Tool.


Enter you domain
Click the green "find problems" button
Quite decent check about all domain settings and services.


----------



## grayfuz (Sep 10, 2013)

thanks aldryic, i recently checked my ip if it is included in blacklisted ip thankful it not. does dkim and spf helps?


----------



## grayfuz (Sep 10, 2013)

thanks wlanboy, so far everything is ok.


----------



## Jack (Sep 28, 2013)

Great guide, I think I will try this out with a personal domain now


----------



## wlanboy (Oct 4, 2013)

Jack said:


> Great guide, I think I will try this out with a personal domain now


Looking forward to your feedback.


----------



## Riccardo_G (Oct 10, 2013)

excellent tutorial

a lot of passion


----------



## wlanboy (Oct 10, 2013)

Riccardo_G said:


> excellent tutorial
> 
> a lot of passion


Thank you.

Feel free to add steps/comments. They are both welcomed.


----------



## BuyCPanel-Kevin (Oct 15, 2013)

Wow, this is amazing, I will definitely have to try this out soon. Thanks for putting in the time to make this in depth tutorial!


----------



## DragonDF (Oct 22, 2013)

Nice tuto. Specially because it runs in a low RAM VPS.

I think it could be a good idea to test if your messages are being received by big providers, specially Hotmail and Yahoo.


----------



## perennate (Oct 23, 2013)

DragonDF said:


> Nice tuto. Specially because it runs in a low RAM VPS.
> 
> I think it could be a good idea to test if your messages are being received by big providers, specially Hotmail and Yahoo.


Hotmail is a pain because they often silently discard email. I'm surprised anyone finds it usable.


----------



## DragonDF (Oct 24, 2013)

I do not know where you live, but where I live, I think at least 60% of the people use Hotmail (I think because in the past it was the unique way to use MSN).

I have 2 hotmail accounts. But I usually use Gmail.


----------



## wlanboy (Oct 25, 2013)

DragonDF said:


> Nice tuto. Specially because it runs in a low RAM VPS.
> 
> I think it could be a good idea to test if your messages are being received by big providers, specially Hotmail and Yahoo.


Yup, you should always check if your ip is clean.

Good test of all DNS/MX/Mail settings are:


http://mxtoolbox.com

http://www.dnsinspect.com
It is comforting to have your domain checked:


----------



## wlanboy (Dec 16, 2013)

Updated some entries and added a chapter about backup mx.


----------



## wlanboy (Jun 29, 2014)

Updated the iptables and ssl part of the tutorial.


----------



## ADDISON (Oct 14, 2014)

Excellent tutorial. In the last two weeks I struggled myself to understand how the emails are sent (MTA - MDA - MUA) and still finding more and more stuff. This is the main reason I came on this page and subscribed to your Forum.

MTA: Postfix, Exim 4, Courier New Mail, Sendmail. Most of you are using Postfix

MDA: Procmail, Sieve, Maildrop. I am forced to used Procmail because Virtualmin/Webmin like it. But using Dovecot a dovecot-sieve can be used. There a migration script from procmail to sieve.

As I understood right MTA deals with SpamAssasssin than passes the email to MDA for dropping them in the right folders. After that Dovecot is dealing with Email Agent (MUA) for getting the email into the user computer. I really appreciate if some of you will describe the full process of sending/receiving email. Thank you.

For VPS Enthusiast I appreciate if you provide a solution for filtering viruses. My test VPS will deal with Windows systems and I have to do this. Can you help me to understand Amavisd-new idea? They pretend ClamAV and SpamAssassin could be queried by Amavisd without having them loaded? Virtualmin is dealing with ClamAV and SpamAssasing and I guess it is being done by Postfix, then passed to Procmail then into boxes. 

Thank you for your time in providing a potential solution for viruses.


----------



## sshgroup (Nov 4, 2014)

thank youuuuu , i was looking for such a good tutorial

:wub:


----------



## Catalin (Nov 25, 2014)

Good tutorial, i will try it on a 128MB ram.. ipv6 only vps.. just to see if it works.


----------



## wlanboy (Jan 12, 2016)

Would anyone want to help me porting this tutorial to CentOS?
I think some would like to use CentOS instead of Debian/Ubuntu.


----------



## graeme (Jan 12, 2016)

wlanboy said:


> It is also a good idea to separate this from your other services



Is this because mail servers attract "attention" that that may affect other services?


----------



## wlanboy (Jan 12, 2016)

graeme said:


> Is this because mail servers attract "attention" that that may affect other services?



My personal reasons are:


If one goes down - everything is not available.
What to restore first? 
What if the backup is old? Database, email accounts and websites are changed in different timespans.
Mail server got hacked / spam-a-lot - one problem and all services have to be shut down (by firewall).
IP address got banned - same problem.
 

Migration is a big bang - upgrades too.
Package dependencies are quite a hell.
You cannot upgrade php because your webmailer depends on an older version.
If something fails you have to rollback everything.
Have to move some services to a new host? Good luck if your configs/services do depend on each other (sendmail localhost).
 

Cloudflare can hide web traffic but cannot hide smtp/imap traffic.
So all reverse proxies are useless if the mail server has the same ip and leacks it (MX records, smtp protocol).
 

Performance
Email servers run quite a lot of threads. Per imap connection, for spam check, virus check, smtp processes.
Easily a lot of XX MB RAM per connection. Thinking about bandwith problems too. Someone downloading a 300MB attachment and your website loading times go up.
 

Local forwards
I have a mail server that is responsible for about 8 domains. All that notifiers, mailing lists, forwarders are done through localhost - saves a lot of bandwidth.
Only ssh, postfix, dovecot, sa and fail2ban. No other services. Keep things simple.


----------



## souen (Jan 12, 2016)

wlanboy said:


> Would anyone want to help me porting this tutorial to CentOS?
> I think some would like to use CentOS instead of Debian/Ubuntu.



Thanks for the excellent tutorial. I followed it on a CentOS 7 vps sometime back, most of it still applies except for a few commands and config locations.



5. Setup your mail server


sudo yum install postfix dovecot




Postfix and Dovecot configuration files are in the same location. I skipped 9-12 so no input there, sorry. 


14. DKIM


opendkim is available in the EPEL repository.


sudo yum install epel-release
sudo yum install opendkim


Configuration is done in /etc/opendkim.conf, including the socket setting (no "/etc/default/opendkim").


After "cp mail.private /etc/mail/dkim.key" (or wherever the key is stored), I checked the ownership of the key file and assign ownership to the opendkim user given in /etc/opendkim.conf if the user is different:


ls -la /etc/mail/dkim.key
chown opendkimpendkim dkim.key




16. I started the services instead of restarting the vps -- is that a problem? Everything seems to work fine.


// Start Postfix and Dovecot, add to startup services
systemctl start postfix
systemctl start dovecot
systemctl enable postfix
systemctl enable dovecot

// After installing DKIM, restart Postfix
systemctl start opendkim
systemctl enable opendkim
systemctl restart postfix

// For CentOS 6 
service postfix start
service dovecot start
chkconfig postfix on
chkconfig dovecot on
service opendkim start
chkconfig opendkim on
service postfix restart




Hope that helps ... sort of?


----------



## graeme (Jan 12, 2016)

@wlanboyOK, lots of reasons. I am convinced. I have no experience of running a mail server, so had no idea about load - I had assumed they were fairly simple and low load....


----------



## souen (Jan 13, 2016)

Tried some more ...



9. Install postgrey


postgrey is available in the EPEL repository.


sudo yum epel-release
sudo yum install postgrey
sudo nano /etc/sysconfig/postgrey
add (default delay is 60):
POSTGREY_OPTS="--inet=127.0.0.1:10023 --delay=55"


After Postfix configuration, start and enable the service:


systemctl start postgrey
systemctl enable postgrey




10. Install spamassassin


Having a little trouble locating the packages, not entirely sure if the list is correct. I couldn't find perl-Geo-IPfree and perl-Net-Ident, RPMforge doesn't have them for CentOS 7. Does anyone know a reputable repository that carries them for CentOS 7?


// (CentOS 6) Install RPMforge repo to fetch some Perl modules
// 32-bit
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.i686.rpm
rpm -Uvh rpmforge-release-0.5.2-2.el6.rf.i686.rpm

// 64-bit
wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm
rpm -Uvh rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

rm -rf rpmforge*.rpm

sudo yum install perl-Net-DNS pyzor perl-Razor-Agent perl-Digest-SHA perl-Encode-Detect perl-DBI perl-Geo-IPfree perl-Net-Ident
sudo yum install spamassassin


There is no /etc/default/spamassassin, so I just started it up like other services:


systemctl start spamassassin
systemctl enable spamassassin


Minor note when updating the rules, there wasn't a /etc/spamassassin directory, I just download the GPG key somewhere and import. Before "sa-update -D -v", download and import the GPG key from Apache servers (or it returns "error: GPG validation failed! The update downloaded successfully, but it was not signed with a trusted GPG ...")


wget http://spamassassin.apache.org/updates/GPG.KEY
sa-update --import GPG.KEY
sa-update -D -v


Additional note -- if running into the error below during install and can't find the kernel-headers in the main repo:


Error: Package: glibc-headers-2.17-106.el7_2.1.x86_64 (updates)
Requires: kernel-headers
Error: Package: glibc-headers-2.17-106.el7_2.1.x86_64 (updates)
Requires: kernel-headers >= 2.2.1


This is due to kernel packages being excluded in /etc/yum.conf on some systems. Run the following command to grab the headers:


sudo yum --disableexcludes=main install kernel-headers




11. Install fail2ban


fail2ban is available in the EPEL repository.


sudo yum install epel-release
sudo yum install fail2ban


/etc/fail2ban/jail.conf recommends having a separate config file instead (/etc/fail2ban/jail.local or placed in /etc/fail2ban/jail.d) instead of editing jail.conf directly. Followed the config from there. The only thing was I couldn't find [sasl], but [postfix-sasl] (and there's no corresponding filter named sasl.conf in /etc/fail2ban/filter.d):


cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
nano /etc/fail2ban/jail.local

[postfix-sasl]

enabled = true
port = smtp,ssmtp,imap2,imap3,imaps,pop3,pop3s
filter = postfix-sasl
# You might consider monitoring /var/log/mail.warn instead if you are
# running postfix since it would provide the same log lines at the
# "warn" level but overall at the smaller filesize.
logpath = /var/log/mail.log


Check that the log files exist or fail2ban won't start. Create them if needed:


touch /var/log/mail.log /var/log/secure


Start it up:


systemctl start fail2ban
systemctl enable fail2ban


Additional note -- as when installing spamassassin, if the ipset package requires the kernel package not yet installed, do:


sudo yum --disableexcludes=main install kernel




12. Own SSL configuration


Sorry, I don't have certificates on hand to test it. There's no /etc/dovecot/conf.d/01-mail-stack-delivery.conf file on CentOS 7. Dovecot certificate paths are /etc/pki/dovecot/certs/dovecot.pem and /etc/pki/dovecot/private/dovecot.pem (self-signed certs are stored in /etc/pki/tls/certs), so I'm not sure where the 3rd step goes, if there's a 3rd step. The old (and possibly outdated) howto on the CentOS wiki adds it to /etc/dovecot/dovecot.conf:


ssl_cert_file = /etc/pki/tls/certs/mail.domain.com.cert
ssl_key_file = /etc/pki/tls/private/mail.domain.com.key


14. DKIM


Forgot to mention in my previous post -- there is no /etc/mail directory by default, but I suppose it could be created, as long as the KeyFile path in the config file is correct (I generated the key in /etc/opendkim/keys and linked to it there).


----------



## norival1992 (Feb 9, 2016)

Thanks for your good tutorial....


----------



## ZenithHosting (Apr 1, 2016)

Thank you for the tutorial


----------



## River (Apr 2, 2016)

This is a really good guide. I've always wondered though if there is a good control panel for just email servers. I know of the collab suites like Zimbra and OpenXChange but I haven't found anything for just the email without all the additional features - really just mailbox management and settings GUI.


----------



## drmike (Apr 3, 2016)

River said:


> This is a really good guide. I've always wondered though if there is a good control panel for just email servers. I know of the collab suites like Zimbra and OpenXChange but I haven't found anything for just the email without all the additional features - really just mailbox management and settings GUI.



There is:
http://www.iredmail.org/admin_panel.html


(I haven't used it)


----------



## Licensecart (Apr 3, 2016)

You are a legend @wlanboy been trying tutorials all over the net and found this one in our backyard, much easier to follow too.


----------



## Licensecart (Apr 3, 2016)

River said:


> This is a really good guide. I've always wondered though if there is a good control panel for just email servers. I know of the collab suites like Zimbra and OpenXChange but I haven't found anything for just the email without all the additional features - really just mailbox management and settings GUI.



Theres roundcube.net but I couldn't get it working myself but I was following rubbish online ones, might be able to get it to work by following wlanboy's. There's PostfixAdmin too I looked into: http://postfixadmin.sourceforge.net


----------



## bizzard (Apr 3, 2016)

@River Virtualmin is my choice for managing mail servers. Not a user focused panel, but good enough for administrators. Handles the mess of multiple domains and quotas pretty well and some other neat features too. Disable all the unwanted services and modules and it still works fine. The default username format is a nuisance though.


Have thought of writing a wrapper around Virtualmin for just mail management but haven't found the time for it. Need to complete the billing panel before I move to other stuffs.


----------



## TheLinuxBug (Apr 3, 2016)

bizzard said:


> Have thought of writing a wrapper around Virtualmin for just mail management but haven't found the time for it. Need to complete the billing panel before I move to other stuffs.



@bizzardYou mean Usermin? 


Cheers!


----------



## Licensecart (Apr 22, 2016)

wlanboy said:


> Would anyone want to help me porting this tutorial to CentOS?
> I think some would like to use CentOS instead of Debian/Ubuntu.



I tried using your tutorial on Centos 7 changing apt-get to yum and I couldn't get it working so maybe that's why 

I did have to use yum install dovecot postfix -y


----------



## WiredBlade (Jul 26, 2016)

Great tutorial. I have been hosting my own email server in Windows and found it to be very hard to manage. I have always want to move to a Linux mail server and this tutorial would help me enormously.


----------

