Step 1. Edit /etc/postfix/master.cf
This file configures the Postfix master process, and is essentially a set of named services. The first argument in a line is the name of a service. Let's call ours "myscript". There's a bunch of other arguments, do man 5 master for the nitty-gritty details.
The last argument is a command + any required arguments for said command. A lot of the pre-existing lines in this file are calling one of the other daemons in the Postfix suite, but the one we're calling will let us do pretty much anything we like - it's called pipe. Again, do man 8 pipe to learn more, but I will share the basics. What pipe does is calls any executable you'd like and pipes its output into it. So let's pipe this into mailscript.php, which I prepared earlier:
myscript unix - n n - - pipe
flags=O user=mail argv=/usr/bin/php5 /home/dante/mailscript.php ${recipient} ${sender}Yes, yes, this is two lines (it's only two - the second one wrapped). It's not, though - it uses the standard "folding" technique whereby you continue a line by starting the next one with whitespace. The flags param mostly adds various email headers that you may want - check man 8 pipe for details. The user param tells master what user should this command run as. argv is the actual executable (plus arguments) that master will call and pipe its output to. ${recipient} and ${sender} will expand to the full email addresses of recipient and sender respectively. Note that the format and order of the argv param is entirely up to you - if you want to make your script executable and run it directly, that's cool.
So the net effect of this is the equivalent of the "mail" user making this call from the shell:
/usr/bin/php5 /home/dante/mailscript.php ${recipient} ${sender}Step 2. Edit /etc/postfix/main.cf
You need to locate (or add) the line that begins with "default_transport". This defaults to "smtp", which is normally how one wants one's mail to be delivered. Change it to read:
default_transport = myscriptAnd you're pretty much done.
Step 3. Write your script
In our example here, ${recipient} and ${sender} will be $argv[1] and $argv[2] respectively, and STDIN will contain a standard RFC 2822 message. That is, the first set of lines coming in will contain the email headers, followed by a blank line, followed by the message itself. My current M.O. is to call
trim(fgets(STDIN)) in a while loop to gather up the headers and let the loop die when it sees an empty string - then you can just suck up the rest of the input. Step 4. Restart Postfix
Step 5. Profit
That's pretty much it, I think. As I (hopefully) implied, you can pipe the output into pretty much anything that will accept it, so write a Python or Perl script, a C/Java/Erlang/etc program, pipe it into /dev/audio if that's the cut of your jib. Make Postfix your bitch.
No comments:
Post a Comment