Run script on receipt of email

dovecotemailpostfix

I run a Postfix/Dovecot mail server for personal use. There's only a handful of actual mailboxes, essentially just postmaster@domain.com and username@domain.com.

I frequently use the virtual file to create virtual mailboxes forwarded to username@domain.com. I have a number of these for throwaway accounts like one-time purchases from online stores, online games I want to try without worrying about ongoing spam, etc. To do so I SSH and run the following commands:

sudo vim /etc/postfix/virtual
# add a line that looks like:
# # username_servicename@domain.com      username@domain.com
sudo postmap virtual
sudo service postfix restart

I do this with enough frequency that I'd like to automate the process to some degree. I considered simply writing a shell script that took the virtual mailbox and real mailbox as arguments and made the changes itself, but am hoping for something even more hands off.

I would like to be able to send an email from username@domain.com to some other mailbox on the server with the virtual mailbox name as the body of the message. The issue would be the sudo calls but I can create a new user whose sole responsibility is to handle this which should handle that.

Mostly the question is this: how would I create an event that would be triggered by an email? Is there a service somewhere that does this? Can I configure either Postfix or Dovecot to listen for that email and run commands on that event?

Best Answer

The correct procedure to execute a script (I use a shell script) upon receipt of a mail message is the following. It involves modifying postfix's configuration file, master.cf (which, in my Debian, is located in /etc/postfix) by adding the following line:

 my_shell_script unix - n n - - pipe flags=F user=MY_USERNAME argv=/path/to/my/shell/script ${sender} ${size} ${recipient}

which instructs postfix to run the script (you need to make it executable) when some event occurs.

To specify when to execute the script, you do as follows: suppose you want it to be executed when username@domain.com receives a message. Place the following line

 username@domain.com FILTER my_shell_script:dummy

inside the file /etc/postfix/address.txt; you will need to create a proper database for postfix to use this file, which you accomplish by means of

  postmap /etc/postfix/address.txt

which produces as output a file called /etc/postfix/address.db. Now go back to the /etc/postfix/main.cf file and add the following line:

 smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/access, permit_mynetworks, reject_unauth_destination

Now restart postfix,

  postfix reload

and you should be good to go.

Related Question