Ubuntu - execute bash script when receiving emails through postfix gmail relay

I have configured postfix on my Ubuntu system to use gmail as a mail relay for sending emails. The outgoing mail functionality works perfectly. However, I want to set up an automated system that triggers a bash script whenever I receive an email through this relay configuration. I need to know if it’s possible to monitor incoming emails and automatically execute custom scripts when new messages arrive. What would be the best approach to implement this kind of email-triggered automation on Ubuntu? Are there any specific configurations I need to add to postfix or should I use a different method entirely?

if u got dovecot for IMAP, check out sieve filters! u can run external programs when emails hit - just enable the vnd.dovecot.execute. its way simpler than messin with postfix transports and has better options for filtering.

procmail is pretty helpful for this! it can catch the incoming emails and run the scripts you want. just set up a .procmailrc file and add your commands there. if it doesn’t suit your needs, you could also use fetchmail with a cron job instead.

You can do this with maildrop or a custom postfix transport. I’ve set up something similar by tweaking master.cf to pipe messages to a custom script. Just add a transport that calls your bash script directly - every message gets processed instantly without polling delays. Your script gets the email through stdin, so you can parse headers and body however you need. Make sure it handles errors properly since postfix wants clean exit codes. Way more reliable than fetchmail since it hooks right into postfix’s processing.

Here’s another option - use postfix’s pipe transport with a dedicated user account. I set up a virtual alias that forwards specific emails to a pipe command. Configure it in /etc/postfix/virtual and /etc/postfix/master.cf, then create a pipe transport that runs your script with the right permissions. This beats the transport method because you can filter which emails trigger the script by recipient or domain. Just make sure your script processes email data quickly - postfix waits for it to finish before marking delivery complete. Way more maintainable than procmail for simple automation since it’s all in postfix config.