Parse Bounced Email Messages in Gmail with Google Scripts

The Google Script scans your Gmail mailbox for messages from mailer-daemon@gmail.com and prepares a bounce email report logging the failed deliveries in a Google Spreadsheet. See sample Gmail bounce report

function getBouncedEmails() {
  /* Written by Amit Agarwal */
  /* Email: amit@labnol.org  */

  // Write the bounced email report to a Google SpreadsheetApp
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).clearContent();

  // Find all emails returned via Gmail Mailer Maemon
  var query = 'from:(mailer-daemon@google.com OR mailer-daemon@googlemail.com)';

  // Get the most recent 500 bounced email messages in Gmail
  GmailApp.search(query, 0, 500).forEach(function (thread) {
    thread.getMessages().forEach(function (message) {
      if (message.getFrom().indexOf('mailer-daemon') !== -1) {
        var body = message.getPlainBody();
        // Get the bounced email address from the body
        var matches = body.match(/Delivery to[\s\S]+?(\S+\@\S+)\s([\s\S]+?)----- Original Message/);
        if (matches) {
          // Get the exact reason for the email bounce
          var reason = matches[2].match(/The error.+:\s+(.+)/) || matches[2].match(/Technical details.+:\s+(.+)/);
          if (reason) {
            // Save the data in a Google Spreadsheet
            sheet.appendRow([
              thread.getLastMessageDate(),
              matches[1],
              reason[1].replace(/ (Please|Learn|See).*$/, ''),
              thread.getPermalink(),
              thread.getFirstMessageSubject(),
            ]);
          }
        }
      }
    });
  });
}
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.