The following stackoverflow link (Google Scripts – Grab email address from bounced message and parse information) has given very good information on how to tackle the Bounces using script from Amit Agarwal at (https://www.labnol.org/internet/gmail-bounced-email-report/29209/).
My question is on whether the code can be called programmatically? I have tried putting each of the code snippets into functions and call them, in vain.
function RunReport() { const findBouncedEmails_ = () => { try { const rows = []; const { messages = [] } = Gmail.Users.Messages.list("me", { q: "from:mailer-daemon", maxResults: 200 }); if (messages.length === 0) { toast_("No bounced emails found in your mailbox!"); return; } toast_("Working.."); for (let m = 0; m < messages.length; m += 1) { const bounceData = parseMessage_(messages[m].id); if (bounceData) { rows.push(bounceData); } if (rows.length % 10 === 0) { toast_(`${rows.length} bounced emails found so far..`); } } writeBouncedEmails_(rows); } catch (error) { toast_(error.toString()); } }; }
I have also tried copying the code into my project, and the lines with “const” are showing syntax errors and could not save the code in the sheet.
After the inputs from https://stackoverflow.com/users/1595451/rubén made the code as below which will collect the date, subject and email of the bounced email and store data in the google sheet. Posting this to help others.
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]); } } }); }); }
On the first run, you need to provide the permission to access the corresponding Gmail email box. All the best in coding.
Advertisement
Answer
One way to call the code “programatically” is this:
function RunReport(){ findBouncedEmails_(); }
Anyway, the code in the question is fine but it requires to use the new Google Apps Script runtime, V8, because it uses
- Arrow functions
- Template strings
let
andconst