Error Handling

576 views
Skip to first unread message

Kareem Gomez

unread,
Mar 16, 2022, 8:08:13 PM3/16/22
to Google Apps Script Community
Help Needed...
I have a script that basically sends out multiple emails (reports) to various recipients. However, when there is an error with a recipient's email address the script stops (eg if no email address is provided or an invalid email address for a recipient).

I need help in putting a line(s) of code that tells the script to skip over the one with the error and continue on to the next recipient.

I would appreciate any guidance provided.
Respectfully, Kareem

This is the code below...

function emailALL() {
 
 var ui = SpreadsheetApp.getUi();
  var response = ui.alert('Confirm', 'Are you sure you want to email all the reports for this class?', ui.ButtonSet.YES_NO);

  if (response == ui.Button.YES) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const studentTerm = ss.getSheetByName("Student Report");
  const sheetId = studentTerm.getSheetId();
  const sheet = ss.getSheetByName("Marks Master");
  const students = sheet.getRange("Ao2:Ao41").getValues();
  var loopCount= sheet.getRange("Ao1").getValues();

  var url_base = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/";
  let url = ss.getUrl();
  url += '#gid=';
  url += sheetId;
  Logger.log("Url: ", url);
  ss.setActiveSheet(studentTerm);

  for(var i=0; i<loopCount +1; i++){
    ss.getRange('C7').setValue(students[i]);
  
  // const sheet = ss.getRange(1, 1, 46, 16);
  // Subject of the email message
  const words = ss.getRange('C7');
  const title = words.getValues()[0];
  const term = ss.getRange("D9");
  const terms = term.getValues()[0];
  const email = ss.getRange('c3').getValues()[0];
  const school = ss.getRange('C1').getValues()[0];
  const subject = school + ": " + title + "_Term_"+ terms +" Report";
  const motto = ss.getRange('C2').getValues()[0];
  const body = "Good day Parent/Guardian, \n\nPlease find attached, school term report for " + title + "."+ "\n\nRegards, \n" + school + "\n" + motto + "\n";

  //"Good day Parent/Guardian," & vbLf & vbLf _
 // & "Please find attached, " & Title & "'s School Term Report." & vbLf & vbLf _
 // & "Regards," & vbLf _
  //& School & vbLf _
 // & Motto & vbLf
  
  // Email Text. You can add HTML code here - see ctrlq.org/html-mail
 
   // let sheet = ss.getSheetName("Student-Term");
  
 // const unformattedUrl = studentTerm.getUrl();
 // Logger.log("SpreadSheet Url " + unformattedUrl);
 // let formattedUrl = unformattedUrl.split("/");
 // formattedUrl = formattedUrl.slice(0, formattedUrl.length - 1);

 // formattedUrl = formattedUrl.join("/");
 // formattedUrl = formattedUrl + "/export?";
  
    const exportOptions ='export?exportFormat=pdf&format=pdf'   //export as pdf

      // Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId)) 
      // following parameters are optional...
      + '&size=letter'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=false'        // fit to width, false for actual size
      + '&sheetnames=false&printtitle=false&pagenumbers=true'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page
  
  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  
  Logger.log(url+exportOptions);
  var response = UrlFetchApp.fetch(url_base+exportOptions, params);
  var blob = response.getBlob().setName(title + '.pdf')
  
  var mailOptions = {
      attachments:blob
    }
  
  //var pdfFile = ss.getBlob().getAs('application/pdf').setName("Pdf1");
  
  //// Send the PDF file as an attachement 
    GmailApp.sendEmail(email, subject, body, mailOptions);
    Utilities.sleep(1000)
  }

}
else {}
}

Andrew Roberts

unread,
Mar 17, 2022, 5:05:59 AM3/17/22
to google-apps-sc...@googlegroups.com
Look at try/catch

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/d8b8a1b8-37ec-4318-a68b-c88579e8f896n%40googlegroups.com.
Message has been deleted

Andrew Roberts

unread,
Mar 17, 2022, 6:22:48 AM3/17/22
to google-apps-sc...@googlegroups.com
Put it around the sendEmail, and log the error just in case, but otherwise carry on. 


    try {

//// Send the PDF file as an attachement 
    GmailApp.sendEmail(email, subject, body, mailOptions);
    Utilities.sleep(1000)

catch (error) {
Logger.log(error.message)
}

On Thu, 17 Mar 2022 at 09:35, Kareem Gomez <school.re...@gmail.com> wrote:
Hi Andrew... I looked at a few try/catch videos but I am unsure of where to place the try and catch lines of code. I am not developer. Would you be able to show me?

Kareem Gomez

unread,
Mar 17, 2022, 6:26:09 AM3/17/22
to Google Apps Script Community
Thank you so much Andrew.

 And yes I will change to MailApp as opposed to GmailApp as you suggested. I saw the reasoning in the hyperlink provided.

Cheers and have a great day 

Laurie Nason

unread,
Mar 19, 2022, 3:11:55 AM3/19/22
to google-apps-sc...@googlegroups.com
I used the following regex:
  var emailAdd='somevalid_...@email.address.com';
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(emailAdd.match(mailformat)){
// Valid email address
} else {
// invalid email address - do something else
}

I hope this helps.
Laurie

Reply all
Reply to author
Forward
0 new messages