Postfix: Pass a copy of an email to a script but deliver the original one to mailbox
It's actually quite simple: I want to pass all incoming emails to a PHP-script, but only as a copy, the original email shall still be delivered to the mailbox as usual.
I just can't seem to get it working. I've tried the following
(1) Created a catchall-alias (mysql):
@mydomain.tld [email protected]
(2) Created a regex-transport mapping in /etc/postfix/mailpipe.cf (basically means: apply to all emails of mydomain.tld)
/.*@mydomain\.tld/ mailpipe:
(3) integrated it all in /etc/postfix/main.cf:
transport_maps = ... regexp:/etc/postfix/mailpipe.cf
virtual_alias_maps = proxy:mysql:/etc/postfix/....
(4) Added the transport to /etc/postfix/master.cf:
mailpipe unix - n n - - pipe
flags=FR user=localuser argv=/path/to/my/script.php
${nexthop} ${user}
The script:
#!/usr/bin/php -q
<?php
$file = '/home/localuser/pipe/log.log';
$input = file_get_contents('php://input');
file_put_contents($file, $input, FILE_APPEND | LOCK_EX);
So the setup seems to work, the script is hit on incoming emails, but the $input
is empty (works with any other string though). The email is being processed and then removed/discarded. So here are my 2 questions:
How can I access the contents of the email from the script?
How can I prevent the email from being discarded after processing? Is there a way to pass one copy to the inbox as usual and another one to the script for processing?
This can be accomplished by using recipient_bcc_maps to BCC all emails to a local-only address that is configured to route to your script.
Add the following line to /etc/postfix/recipient_bcc. Run "postmap /etc/postfix/recipient_bcc" after editing is done. This tells Postfix to BCC all emails where the domain matches "@yourdomain.tld" to the "robotscript@localhost" address.
@yourdomain.tld robotscript@localhost
Add the following line to /etc/postfix/transport. Run "postmap /etc/postfix/transport" after editing is done. This tells Postfix that emails destined for the "robotscript@localhost" address are to be delivered directly on this server, and not relayed elsewhere.
robotscript@localhost :
Add the following lines to /etc/postfix/main.cf so that Postfix will use the configurations entered above.
recipient_bcc_maps = hash:/etc/postfix/recipient_bcc
transport_maps = hash:/etc/postfix/transport
Make sure that the "mydestination" parameter in /etc/postfix/main.cf includes the "localhost" value.
Add the following line to /etc/aliases. Run "postalias /etc/aliases" after editing is done. This is what actually passes emails destined for "robotscript@localhost" to your PHP script. Your script should be set up to read the contents of the email from STDIN.
robotscript: "|/path/to/your/php_script.php"
Restart Postfix, and all your emails should then be copied to your script as well as delivered to the original recipient address.