Postfix modify email in queue and re-inject

I've a legacy webapp that sends mail to an external SMTP (specified by a conf file). These emails came out from "noreply" account and were correctly delivered. Now, we want mails came out from "[email protected]" but unfortunately is not possible modify the app. From the website, we can recognize the logged in user but we're unable to set it before the send.. So we've to intercept the mail before they arrive to the external SMTP. For this, we've configured a local Postfix to substitute to the external SMTP. It have to accept mails, change the sender (the new one will be in the Subject between some special chars) and re-route the mail to the official external SMTP. All mails have attachments (doc/pdf file). Is there any direct commands/method to do this?

At high level, the solution I thinked about is based on: hold the queue, postcat the messages, change the sender by a script, send the mail by mail/mailx command.. Thanks.


Solution 1:

Presumably you want to change the envelope sender address as well as the "From:" address in the email headers?

The first part is easy - it's basically generic address mapping for outgoing SMTP mail

You need to define a generic address map in main.cf and then create the actual address map file with the address conversion(s) you need.

 /etc/postfix/main.cf:
    smtp_generic_maps = hash:/etc/postfix/generic

/etc/postfix/generic:
    [email protected]        [email protected]

To modify the email header "From:" as well, you need a header check (http://www.postfix.org/header_checks.5.html). I highly recommend reading FILTER_README as well to see if there's a "nicer" way to do it and to understand where it can take place during the message flow, but this is a basic way to change the header on the message.

Here you define a header_checks map in main.cf and then create the actual header_checks map file with the REPLACE verb and the new text. The PCRE map is a regex format, so you can use one to match the text you need to replace (rather than the exact text) - in the example, it'll match a From: field that contains the "bad" sender address (plus any other text in that field), and replace the whole field with the new text.

/etc/postfix/main.cf:
    header_checks = pcre:/etc/postfix/header_checks.pcre

/etc/postfix/header_checks: 
    /^From:.*noreply@localdomain\.local.*/ REPLACE From: "Some Name" <[email protected]>

Remember to postmap any new map files you create!