发送带有内嵌图像和文本的电子邮件

时间:2020-03-20 16:22:47

标签: google-apps-script

我正在使用此代码发送包含嵌入式图像和一些文本(均从工作表标签中提取)的电子邮件。该脚本运行良好,但调试不干净。您能帮我找到更好的语法吗?

我得到的错误是:

“在获取方法或属性getBlob时发生意外错误 对象DriveApp.File。”

谢谢

function sendEmails() {

  var ss = SpreadsheetApp.getActive().getSheetByName('SendMail')
  var lr = ss.getLastRow();

  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 send.");
  } else {



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


      var currentEmail = ss.getRange(i, 1).getValue();
      var currentSubject = ss.getRange(i, 2).getValue();
      var templateText = ss.getRange(i, 3).getValue();
      var currentname = ss.getRange(i, 4).getValue();
      var reply = ss.getRange(i, 5).getValue();

      var image = DriveApp.getFileById(ss.getRange(i, 6).getValue()).getBlob();
      var message = templateText.replace("{name}",currentname);

      message += "<br/><br/><img src=\"cid:sampleImage\">";


      //Logger.log(currentEmail);

      MailApp.sendEmail({

        to: currentEmail,
        replyTo: reply,
        subject: currentSubject,
        htmlBody: message,
        inlineImages: {sampleImage: image},

      });

    } //close for loop

  } //close else statement

} //close sendEmails`

1 个答案:

答案 0 :(得分:0)

该错误表示:

No item with the given ID could be found, or you do not have permission to access it.

或者换句话说:

ss.getRange(i, 6).getValue()没有有效的文件ID。

出于调试目的,在检索映像之前添加以下两个日志并观察结果:

...
Logger.log("Cell: " + ss.getRange(i, 6).getA1Notation());
Logger.log("Image: "+ DriveApp.getFileById(ss.getRange(i, 6).getValue()));
var image = DriveApp.getFileById(ss.getRange(i, 6).getValue()).getBlob();
...

如何确保包含图像ID的单元格不为空?

执行if语句,以验证单元格是否为空白。如果是这样,请继续进行下一个循环迭代:

...
if(ss.getRange(i, 6).isBlank()){
  continue;
}
var image = DriveApp.getFileById(ss.getRange(i, 6).getValue()).getBlob();
...