Sunday, January 16, 2022

Google Apps Script to list bounced emails

The following script lists all emails which bounce. So there would be multiple rows with the same bouncing email id. Adding another column to the Google Sheet with something like
=UNIQUE(C2:C)
(where C is the column of email ids, assuming first row contains column headers)
will get the list of unique bouncing emails.

From https://stackoverflow.com/questions/63248390/google-scripts-bounced-emails

function getBouncedEmails() {

// Create a sheet in your project "BouncedEmails" and add this code in the script.
var sheet = SpreadsheetApp.getActive().getSheetByName('BouncedEmails');

// Fetch all the bounced emails using a query
var query = "from:(mailer-daemon@google.com OR mailer-daemon@googlemail.com)";

//Get the most recent 500 bounced email messages
//Change the number according to your requirement
GmailApp.search(query, 0, 500).forEach(function(thread) {
    thread.getMessages().forEach(function(message) {
        if (message.getFrom().indexOf("mailer-daemon") !== -1) {
          //get the emailAddress from the Header
          var emailAddress = message.getHeader('X-Failed-Recipients');
          //add a filter if you would like to write certain messages only
          //if(thread.getFirstMessageSubject() == "YOUR SUBJECT"){
                    // Save the data in Google Spreadsheet
                    sheet.appendRow([
                        thread.getLastMessageDate(),
                        thread.getFirstMessageSubject(),
                        emailAddress]);
          //}
        }
    });
 });
}

No comments:

Post a Comment