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 is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

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

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

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

We will never send any spam emails. Promise 🫶🏻