Search code examples
phpemailphpmaileremail-bounces

PHPMailer: Set custom header to identify it inside the bounce email


I'm sending emails with PHPMailer. When an email is bounced it goes to an account like this: [email protected]

Inside my email client where I manage this account ([email protected]), I have the option to adds filters in order to redirect an email to any other email account, based on the comparation of fields like "Subject", "From", "To" and so on. That's good.

The problem is that the bounced email loses all of my headers/Subject...that I set with PHPMailer because it's ALWAYS composed by the server as it follows:

So I have no guide marks to use for adding a filter.

So, is there any way to set a mark(like a custom header, etc...) in PHPMailer that REMAINS in the bounced email?. For example, something like having this:

  • Subject: Undelivered Mail Returned to Sender (bounce_redirect)

So the word "bounce_redirect" in the Subject(or wherever) would indicate my email client that this email has to be redirected.

Thanks in advance.


Solution

  • Unfortunately there is no way you can force this issue in headers; The only way around it is to use VERP addressing, which is the only way that you can guarantee that it preserves info about the message and what address it was originally sent to. It's common for MS Exchange to send bounce messages that do not mention the original address the message was sent to at all, so VERP is the only solution.

    For your example, a typical VERP address would be:

    [email protected]
    

    You mail server would be set to spot the account_bounces prefix and remove it, and convert the = to a @ in the local part to extract the original address.

    In PHPMailer you would set this as your Sender property, like:

    $mail->Sender = '[email protected]';
    

    This will be used as the SMTP envelope sender, and converted to a Return-Path header by the receiving server, and thus will be used as the RCPT TO address (the bounce destination) when the message gets bounced.

    You can take this further and embed additional info in the Sender address that can be used to identify the mailing list, a specific mailshot etc.