Preventing bounce emails from leaving the server

It’s been about two weeks since we’ve switched from our in-house email system to Mailgun SMTP services in order to improve delivery of our email. Not that we send many, no – we average just about 3000 emails a month, the majority of which are account signup emails, and invoices being sent to our customers. The configuration was easy and straightforward, and they always have someone available to help if you run into problems (We didn’t!).

After having everything set up, we noticed a large number of internal emails were getting routed via Mailgun and, subsequently bounced. Oops! That shouldn’t happen. Those emails were never supposed to leave our server.

A little search on Google revealed that DirectAdmin, the control panel we use, was trying to deliver bounce emails – the ones coming from MAILER-DAEMON – to a local mailbox using remote SMTP. This needed to be fixed. We also run this panel on all our DirectAdmin Hosting plans, so we had to repeat this process on each server. First of all, it uses up our Mailgun email quota, and it just simply shouldn’t happen. Email between internal accounts should be delivered internally without leaving the server at all. Let’s start to fix this…

Even the official DirectAdmin team’s solution says that what we’re about to do is ‘not entirely correct in it’s logic’, we’re going to go ahead and fix the problem. Problems are meant to be fixed.

DirectAdmin uses Exim to send email, and we’ve already configured everything to be passed on to Mailgun, which is why we will not cover that topic here, and will only focus on preventing bounce messages from leaving the server, so the first thing to do is to open /etc/system_filter.exim and find this code:

if not first_delivery
then
finish
endif

Then paste this right before it:

if $sender_address is ""
then
if $header_Auto-Submitted: is not "auto-replied"
then
if ${lookup{${extract{2}{@}{$recipients}}}lsearch{/etc/virtual/domains}{yes}{no}} is "no"
then
noerror fail text "Delayed bounce message ignored"
seen finish
endif
endif
endif

Save the file and restart Exim by ‘service exim restart‘ or /etc/init.d/exim restart – whatever you prefer, or whichever is available on your system.

The above was done on a CentOS 6 system. If you run a different Linux distro, modify the commands accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *