Search code examples
laravelamazon-ses

Laravel - How to add custom data to SES bounce back payload


This is the usual payload that given by AWS when the email bounce back.

{
    "notificationType": "Bounce",
    "bounce": {
        "bounceType": "Transient",
        "bounceSubType": "General",
        "bouncedRecipients": [{
            "emailAddress": "John Doe <john.doe@blablabla.com>"
        }],
        "timestamp": "2018-06-20T00:08:33.000Z",
        "feedbackId": "010199641a7787f4-b716a44c-87fd-b4e8-aac6-9f3addafbf8e-000000"
    },
    "mail": {
        "timestamp": "2018-06-20T00:08:29.000Z",
        "source": "no.reply@mysite.com",
        "sourceArn": "arn:aws:ses:us-west-2:112348978975:identity/no.reply@mysite.com",
        "sourceIp": "72.121.95.229",
        "sendingAccountId": "156123967765",
        "messageId": "0101016c8a81e492-57779c7b-9175-4ab4-a993-c323431c98d1-000000",
        "destination": ["John Doe <john.doe@blablabla.com>"]
    }
}

What I want is to add in custom attributes to the bounce back payload. E.g.

{"module": "reset_password"}

And I found this post saying that can use message tag.

How to set this tag with Laravel 5.6?


Solution

  • I found the doc here, and add the custom attributes to headers.

    \Mail::send([], [], function ($email) use ($recipient) {
        $email->getHeaders()->addTextHeader('X-SES-MESSAGE-TAGS', 'module=auth,submodule=reset_password');
        $email->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
        $email->to($recipient);
        $email->subject('Test SES subject');
        $email->setBody('This is a test content', 'text/html');
    });
    

    and must make sure the bounce back payload include original header.

    Then in the webhook

    $message_raw = \Aws\Sns\Message::fromRawPostData();
    $message = json_decode($message_raw['Message'],1);
    if (isset($message['mail']['headers'])) {
        $headers = collect($message['mail']['headers']);
        $tags = $headers->where('name', 'X-SES-MESSAGE-TAGS')->first();
        if ($tags) {
            $tags_arr = explode(',', $tags['value']);
            $tags = [];
            foreach ($tags_arr as $item) {
                list($key, $value) = explode('=', $item);
                $tags[$key] = $value;
            }
        }
    }
    
    $model->module = $tags['module']; // output auth
    $model->submodule = $tags['submodule']; // output reset_password