Search code examples
google-apps-scriptgoogle-sheetsgmail

Why wont my email script send emails past line 2?


I have a email script and its been working great when it was on individual google sheets, we have now combined all the information we need from multiple separate sheets, to 1 sheet with IDs and so on, makes it more clean and easier to work with. Since the combination, the same email script has not sent emails to all my rows. Only to row 2.

Please note this is all testing stage and the sheets and emailer are not currently being used in the day to day business.

I have verified that sheet ID is correct

I have verified that the sheet name is correct in the script

I know the script works because if I plug in my test email into line 2, I receive the email as expected, when I plug it into any other line, it doesn't work and I get a error: Exception: Failed to send email: no recipient.

Screen grab of error, ( email removed for privacy)

Screen grab of error

Screen grab of the emailer script: screen grab of emailer script

sorry if the image is too small I wanted to get all the code on there.

Also, when I manually run the script via the Run option in the script window its self, I do not get any errors and the email still does not send, I have tried using Logger.log(); and Console.log(); but both options give me no results at all.

    let SHEETID = '1SWspXa1LrC-L5NaVZAdEuQBGWpQRohKsd_zipAzENmE';
let DOCID = '1F9drCz8b5HDMCZT48nb57YX9_80SHMzFL2-rDfbyRGA';
let PDFFOLDERID = '1CWAXcMvi6d_ku9ZgsXY42YSdUoTrvIEC';

const MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
const now = new Date();
const due = new Date(now.getTime() + 30 * MILLIS_PER_DAY);

function onOpen(){
  SpreadsheetApp.getUi()
  .createMenu('Send PDFs')
  .addItem('Send Invoice PDF', 'emailer')
  .addToUi();
}

function emailer() {
  let sheet = SpreadsheetApp.getActive().getSheetByName('Shop');
  let template = DriveApp.getFileById(DOCID);
let pdfFolder = DriveApp.getFolderById(PDFFOLDERID);
  let data = sheet.getDataRange().getValues();
  let rows = data.slice(1)

  rows.forEach((row, index)=>{
    if (row[05] ==''){
let file = template.makeCopy(pdfFolder);
   let doc = DocumentApp.openById(file.getId());
   let body = doc.getBody();
   body.replaceText('{Shop_ID_Name}',row[01]);
   body.replaceText('{Shop_Address}',row[03]);
   body.replaceText('{S1_Name}',row[03]);
   body.replaceText('{S2_Name}', row[03]);
   body.replaceText('{S3_Name}',row[03]);
   body.replaceText('{S4_Name}',row[03]);
   body.replaceText('{S5_Name}',row[03]);
   body.replaceText('{S6_Name}',row[03]);
   body.replaceText('{S7_Name}',row[03]);
   body.replaceText('{S8_Name}',row[03]);
   body.replaceText('{S9_Name}',row[03]);
   body.replaceText('{S10_Name}',row[03]);
   body.replaceText('{S11_Name}',row[03]);
body.replaceText('{CURRENT}', new Date);
body.replaceText('{DATE}',due);
  data[0].forEach((heading,i)=>{
    let header1 =heading.toUpperCase();
    body.replaceText(`{${header1}}`,row[i]);
  })
  doc.setName(row[01]);
  let blob = doc.getAs(MimeType.PDF);
  doc.saveAndClose();
  
  let pdf = pdfFolder.createFile(blob).setName(row[02]+row[03]+row[04]+row[05]+row[06]+row[07]+row[08]+row[09]+' .pdf');

  let email = row[03].trim();
  let subject = row[02]+' New Invoice ';
  let messagebody = `Hello, ${row[1]} Please see attached PDF.`;
  MailApp.sendEmail({to:email,
  subject:subject,
  htmlbody: messagebody,
  attachments: [blob.getAs(MimeType.PDF)]
  });

let tempo = sheet.getRange(index+2,6,1,1);
Logger.log(tempo);
tempo.setValue(new Date());
  
   file.setTrashed(true);
  }
  })

Solution

  • I believe what you are trying to do is this. I've removed some of the superfulous stuff to save on the length of the function. I'm not able to test it but I'm pretty sure it works.

    function emailer() {
      let sheet = SpreadsheetApp.getActive().getSheetByName('Shop');
      let template = DriveApp.getFileById(DOCID);
      let pdfFolder = DriveApp.getFolderById(PDFFOLDERID);
      let data = sheet.getDataRange().getValues();
      let header = data.shift(); // remove headers
    
      let sent = [];  // added
    
      data.forEach( (row, index) => {
          sent[index] = [row[5]]; /// added
          if( row[5] === '' ) {
            let file = template.makeCopy(pdfFolder);
            let doc = DocumentApp.openById(file.getId());
            let body = doc.getBody();
            body.replaceText('{Shop_ID_Name}',row[1]);
            body.replaceText('{Shop_Address}',row[2]);
            body.replaceText('{CURRENT}', new Date);
            body.replaceText('{DATE}',due);
            header.forEach( (column,i) => {
                let header1 = column.toUpperCase();
                body.replaceText(`{${header1}}`,row[i]);
              }
            );
            doc.setName(row[1]);
            let blob = doc.getAs(MimeType.PDF);
            doc.saveAndClose();
    
            let pdf = pdfFolder.createFile(blob).setName(row[2]+row[3]+row[4]+row[5]+row[6]+row[7]+row[8]+row[9]+' .pdf');
    
            let email = row[3].trim();
            let subject = row[2]+' New Invoice ';
            let messagebody = `Hello, ${row[1]} Please see attached PDF.`;
            MailApp.sendEmail(
              { to:email,
                subject:subject,
                htmlbody: messagebody,
                attachments: [blob.getAs(MimeType.PDF)]
              }
            );
    
            sent[index] = [new Date()];  // rather than setValue() I use setValues() later
      
            file.setTrashed(true);
    
          }
        }
      );
      sheet.getRange(2,6,sent.length,1).setValues(sent);
    }