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
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