无法使用Google Apps脚本发送带有附件的电子邮件

时间:2019-08-10 13:31:46

标签: javascript google-sheets email-attachments

function SendEmails() {


  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Name List").activate();

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  var lr = ss.getLastRow(); 

  var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email Template").getRange(1, 1).getValue();

  var quotaLeft = MailApp.getRemainingDailyQuota();
  //Logger.log(quotaLeft);
  if ((lr-1) > quotaLeft){
     Browser.msgBox("You have " + quotaLeft + " left and you're trying  to send " + (lr-1) + "emails. Emails were not sent.");
     } else {

  for (var i = 2;i<=lr;i++){

       var currentName = ss.getRange(i, 1).getValue();
       var currentAppNo = ss.getRange(i, 2).getValue();
       var currentEmail = ss.getRange(i, 3).getValue();

       var messageBody = templateText.replace("{First Name}",currentName).replace("{App No}",currentAppNo);
       var subjectLine = "CONGRATULATION ON YOUR VAL APPROVAL " + currentName
       var attachmentBody = DriveApp.getFilesByName("THE ROOM SCRIPT.pdf");


      MailApp.sendEmail(currentEmail, subjectLine, messageBody)

    } //close for loop

          } //close else statement
}

我有一个带有电子邮件列表的Google Spreadsheet。我想建立一个例程,将电子邮件自动发送到那些电子邮件地址。我也想在此电子邮件中附加PDF。 PDF文件位于我的Google云端硬盘上。

这似乎不起作用

1 个答案:

答案 0 :(得分:0)

您可能需要在脚本中更改两件事。

  1. getFilesByName()获取具有该名称的文件集合(作为FileIterator对象)。如果只有一个这样的文件,则需要将该行更改为
    var attachmentBody = DriveApp.getFilesByName("THE ROOM SCRIPT.pdf").next; // To get the first such file

Ref doc here

  1. 正如@ross所说,sendMail()函数需要包含附件,如下所示:
    MailApp.sendEmail(currentEmail, subjectLine, messageBody, {
        attachments: [attachmentBody.getAs(MimeType.PDF)]
    });

Ref doc here