Wednesday, November 19, 2014

Customize outgoing SendGrid emails X-SMTPAPI header by Postfix

SendGrid’s SMTP API allows developers to specify custom handling instructions for e-mail. This is accomplished through a header, X-SMTPAPI, that is inserted into the message.

We can do it easily, for example in PHP:
 $email = new SendGrid\Email();  
 $email->addTo('from@abc.com')->  
     setFrom('to@abc.com')->  
     setSubject('Subject goes here')->  
     setText('Hello World!')->  
     addFilter("subscriptiontrack", "enable", 0)->  
     addFilter("clicktrack", "enable", 0)->  
     addFilter("opentrack", "enable", 0)->  
     addCategory("www")->  
     setHtml('<strong>Hello World!</strong>');  

But for some reasons, Client would like to replay emails to SendGrid by local Postfix and using Drupal built-in mail function without custom code, we can use Postfix smtp_header_checks to add the X-SMTPAPI header for outgoing emails.

Below are steps to do that:

1. Setup Postfix and config it to send emails via SendGrid as here
(it's better to use hashed password file like smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd instead smtp_sasl_password_maps = static:yourSendGridUsername:yourSendGridPassword)

2. Add smtp_header_checks to /etc/postfix/main.cf:
smtp_header_checks = regexp:/etc/postfix/smtp_header_checks

3. Create /etc/postfix/smtp_header_checks file with the content, like:
/^From:/ PREPEND X-SMTPAPI: "category":["www"],"filters":{"subscriptiontrack":{"settings":{"enable":0}},"clicktrack":{"settings":{"enable":0}},"opentrack":{"settings":{"enable":0}}}}

Hint: we can easily get the X-SMTPAPI content by print it out from above PHP code, like:
 $arr = $email->toWebFormat();  
 echo $arr['x-smtpapi'];  

4. Reload Postfix

1 comment: