Bounced Email Parsing 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()
                        ]);
                    }
                }
            }
        });
    });
}