Exim4 system-wide conditional email forwarding

This is a guest post written by Steve Goertz after he solved this particular issue.

Use:

  • Filtering and forwarding all emails received by exim4
  • Filtering by specific email components (sender information, subject, etc.)
  • Forwarding all filtered emails to a specific email address or email addresses

Assuming a working instance of exim4:

Create a filter file for exim4 using the appropriate filters and syntax as found in the exim4 filter documentation here: http://www.exim.org/exim-html-current/doc/html/spec_html/filter_ch-exim_filter_files.html

You may want to create a directory for exim4 filters and place the file in that directory, like:

/etc/exim4/conf.d/filters/filter_name

For our particular use, a conditional section and  deliver command were the only necessary components. A filter file will look something like this:

#Exim filter <<== do not edit or remove this line!

##Filter description, so you remember what you were trying to do.

if
  $sender_address is “sender@address.example” and 
  $header_subject does not contain “foo” and 
  $message_body contains “bar”
then
  deliver “recipient@other.example”
endif

Filters will then be placed as the first router in the exim4 router config ( found at /etc/exim4/conf.d/router/router_name ). Depending on your configuration the router name may vary, or you may need to add one. The filter should be formatted as follows:

filter_name:
  driver = redirect
  allow_filter
  file = /path/to/filter (in this case /etc/exim4/conf.d/filters/filter_name)
  user = exim4_user

It is essential that the  user variable match the user that owns exim4.  If not, the filter will not function and email traffic will not pass through the first filter to the remaining filters and all regular email processing will stop. You can probably figure this out by checking the init script for exim4 or using the command:

ps aux | grep exim4 

to see whom exim4 is running as.

After the filter file has been generated and correctly referenced in the router config, rebuild the exim4 config using:

sudo update-exim4.conf.template -r

And restart the service

sudo service exim4 restart

Test the email server to ensure that it is working as intended.

This configuration will prevent emails from arriving at their intended destination, which was our need. Also, if the incoming email does not meet all of the requirements above, it will pass through to the next router in the router configuration file.