Wednesday, June 30, 2010

Using Exim as a Mail Relay

One service that always seems required by any platform I've ever worked on is an outbound mail transfer agent. Essentially, everybody wants to send their customers notifications and needs a clearinghouse to pass it through.

This is all well and good, but there are a few inevitable problems one is likely to run into when putting one up.

By far, I've had the most success with Exim running on Debian since both are very lightweight, incredibly reliable and closely intertwined. (Exim is Debian's default MTA.)

Step 1 is to provide the basic setup. Log in, su to root and run the following:

dpkg-reconfigure exim4-config

You'll walk through some basic setup info. Essentially, you want to specify the host as an internet mail server and provide the ip addresses of your internal hosts are valid hosts to relay for.

When that's complete, you need to cd into /etc/exim4 and modify the exim4.conf.template file. Find the rewrite section by looking for

begin rewrite

Then add your rewrite rule under it. This will make it apply to all messages that pass thorugh Exim.

The generic rule I usually use looks like this:

*@* $1@mycompanysdomain Ffrs

What it essentially says is "match everthing (*@*) and replace what's in front of the @ with what was to the left of the original and everything after the @ with with explicit domain name - also, apply it to the following types of addresses: F - envelope From field, f - From header, r - Reply-To header, s - Sender header"

With that rule in place, restart Exim:

invoke-rc.d exim4 restart

And the config will be written out to /var/lib/exim4/configuration.autogenerated.

The best way to test is to use the Exim command line to see what rewrites will get applied:

# exim -brw root@localhost
sender: root@
mycompanysdomain
from: root@mycompanysdomain
to: root@localhost
cc: root@localhost
bcc: root@localhost
reply-to: root@
mycompanysdomain
env-from: root@mycompanysdomain
env-to: root@localhost

With that done, you need to take care of the blacklists. First, add an A record to your domain's authoritative DNS WITH A PTR. The reverse lookup is used as a method to ensure the mail server is a legitimate member of your domain. NOTE: A lot of people think MX records are required but that's incorrect. MX records are for inbound mail only.

Now fire off some messages to big mail destinations like gmail and yahoo. Tail the /var/log/exim4/mainlog to see what results you get. Yahoo especially is good about telling you where your IP is blacklisted for some reason. If it is, you'll get a lot of dropped messages till you contact the Blacklister and petition to have it removed.

On that same note, be careful about sending out a bunch of unsoliticed test messages. I've seen hosts get black-listed for that reason alone and it's a pain to get delisted.