简体   繁体   English

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

[英]Fail to Send an email with attachment using Google Apps Script

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
}

I have a Google Spreadsheet with a list of emails. 我有一个带有电子邮件列表的Google Spreadsheet。 I want to build a routine that sends email automatically to those email addresses. 我想建立一个例程,将电子邮件自动发送到那些电子邮件地址。 I also want to attach a PDF to this email. 我也想在此电子邮件中附加PDF。 The PDF file is located on my Google Drive. PDF文件位于我的Google云端硬盘上。

This does not seem to work 这似乎不起作用

Here are two things that you may want to change in your script. 您可能需要在脚本中更改以下两件事。

  1. getFilesByName() gets a collection of files (as a FileIterator object) with that name. getFilesByName()获得具有该名称的文件集合(作为FileIterator对象)。 If there is just one such file, you'll need to change that line to 如果只有一个这样的文件,则需要将该行更改为
    var attachmentBody = DriveApp.getFilesByName("THE ROOM SCRIPT.pdf").next; // To get the first such file

Ref doc here . 参考文档在这里

  1. As @ross said, the sendMail() function needs to include the attachment like so: 正如@ross所说, sendMail()函数需要包含附件,如下所示:
    MailApp.sendEmail(currentEmail, subjectLine, messageBody, {
        attachments: [attachmentBody.getAs(MimeType.PDF)]
    });

Ref doc here . 参考文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM