12 February 2020

How to Generate a Report of Bounced Email Addresses in Gmail


Bounced Emails in Gmail

Some email messages you have sent through your Gmail account may not get delivered at all. There could be a problem with the recipient’s email address, like a typo, their mailbox could be full or maybe the mail server could be specifically blocking your emails due to the content of the message.

When an email message sent via Gmail is bounced or rejected, you get an automated bounce-back notice from mailer-daemon@gmail.com and it will always contain the exact reason for the delivery failure along with the SMTP error code. For instance, an error code 550 indicates that the email address doesn’t exist while a 554 indicates that your email was classified as spam by the recipient’s mail server.

How to Get a List of Email Addresses that Bounced

It is important to keep track of your bounced messages and remove all undelivered email addresses from your future mailings as they may affect your sending reputation.

Mail Merge for Gmail keeps track of all your bounced messages in Gmail but if you are not using mail merge yet, here’s an open-source Google Script that will prepare a list of all email addresses that have bounced inside a Google Spreadsheet.

Gmail Bounce Report in Google Sheets

Gmail Bounce Report - Getting Started

Here’s how you can get started:

  1. Click here to make a copy of the Google Spreadsheet.
  2. Open the Bounced Emails menu in your Google Sheet and then select the Run Report option.
  3. Authorize the Google Script so it can scan your Gmail account for bounced emails and write them to the Google Sheet. The script runs entirely in your Google account, no data is stored or shared anywhere.
  4. Watch as the Google Sheet is populated with rejected and bounced email addresses.

The email bounce report includes the email address that bounced, the reason why that email failed to deliver and the date when the bounce occurred. The spreadsheet will also have a direct link to the bounced message received from mailer-daemon.

Technical Details - How the Script Works

The script uses the Gmail API to fetch a list of all bounced emails in your mailbox.

const findBouncedEmails = () => {
  const { messages = [] } = Gmail.Users.Messages.list('me', {
    q: 'from:mailer-daemon',
    maxResults: 200
  });
  for (let m = 0; m < messages.length; m += 1) {
    const bounceData = parseGmailMessage(messages[m].id);
    if (bounceData) {
      SpreadsheetApp.getActiveSheet().appendRow(bounceData);
    }
  }
};

Next, the script parses the headers of bounced email messages with regex and writes the bounced information to the Google Sheet.

const parseGmailMessage = messageId => {
  const message = GmailApp.getMessageById(messageId);
  const body = message.getPlainBody();
  const [, failAction] = body.match(/^Action:\s*(.+)/m) || [];

  /* If failAction is "delayed", igore message since Gmail will retry it */
  if (failAction === 'failed') {
    /* The X-Failed-Recipients header in Gmail contains the recipient's address */
    const emailAddress = message.getHeader('X-Failed-Recipients');
    /* Get the SMTP error code
       The first sub-field indicates whether the delivery attempt was successful
       (2= success, 4 = persistent temporary failure, 5 = permanent failure). */
    const [, errorStatus] = body.match(/^Status:\s*([.\d]+)/m) || [];
    /* The Diagnostic-Code DSN field contains the actual diagnostic code
       Some mail systems supply no additional information beyond that
       which is returned in the 'action' and 'status' fields. */
    const [, , bounceReason] =
      body.match(/^Diagnostic-Code:\s*(.+)\s*;\s*(.+)/m) || [];
    return [
      message.getDate(),
      emailAddress,
      errorStatus,
      bounceReason.replace(/\s*(Please|Learn|See).+$/, ''),
      `=HYPERLINK("${message.getThread().getPermalink()}";"View")`
    ];
  }
  return false;
};

Inside your Google Sheet, go to the Tools menu and choose Script Editor to view the full source code of the Google Script. You are welcome to reuse / modify the code.

Also see: Automatically Unsubscribe from Email Newsletters


No comments:

Post a Comment