Home > Back-end >  Adding Attachments from Drive to Email - Apps Script
Adding Attachments from Drive to Email - Apps Script

Time:11-16

I know this question has been asked and I read through the responses and updated my code, but I still can't get this to work properly and I don't see what I'm missing. I'm simply trying to add a PDF I have saved in my Google Drive to an email, and while the email sends (so there's no errors in my code) the attachment is not there (so there's a bug).

When I log the attachment itself, the name of my file shows in the log so I know it's not pulling null.

for the sake of privacy, I've removed the email addresses and the bodySignature of the email and replace those values with [Emails] and [Body]. Emails will have multiple emails in the array, hence the for-loop later on. I also have my "body" variable as blank and the actual body will be in the "bodySignature" variable.

Thank you for helping me debug my code - It's a skill I'm working on, and any & all help is appreciated!

const subject = "Revenue & Billing Missing Information";
const body = "";
const emails = [Emails]

 
const pdfName = "Rev&Bill DP.pdf";
let listOfFiles = DriveApp.getFilesByName(pdfName);

const bodySignature = [Body]


function monthlyReminder() {
  if(listOfFiles.hasNext()){
    let file = listOfFiles.next();
    for (let i = 0; i < emails.length; i  ) {
      GmailApp.sendEmail(emails[i], subject, body, {htmlBody: bodySignature, attachements: file});
    }
  }
  else{
    console.log("Error no file in listOfFiles. Email not sent.");
  }
}

CodePudding user response:

Try this:

function monthlyReminder() {
  const subject = "Revenue & Billing Missing Information";
  const body = "";
  const emails = [Emails]
  const pdfName = "Rev&Bill DP.pdf";
  let listOfFiles = DriveApp.getFilesByName(pdfName);
  const bodySignature = [Body]
  if (listOfFiles.hasNext()) {
    let file = listOfFiles.next();
    for (let i = 0; i < emails.length; i  ) {
      GmailApp.sendEmail(emails[i], subject, body, { htmlBody: bodySignature, attachements: [file] });
    }
  }
  else {
    console.log("Error no file in listOfFiles. Email not sent.");
  }
}

CodePudding user response:

I did some test, this is just a sample code without an HTML body (you can add that part later on):

function emailsPDF() {
  const subject = "testing email 3";
  const body = "This is a test email";
  const email = "[email protected]";
  const file_name = "name.pdf";
  var file = DriveApp.getFilesByName(file_name);

  if (!file.hasNext()) 
  {
    console.error("Could not open file " filename);
    return;
  }


  GmailApp.sendEmail(email,subject,body, { attachments: [file.next().getAs(MimeType.PDF)]});

}

Based on my test, the part that you need to update is:

 attachements: file

for:

attachments: [file.getAs(MimeType.PDF)]

Reference:

  • Related