0

我想使用电子表格发送带有独特附件的批量谷歌邮件。在这个电子表格中,我输入了电子邮件地址、内容模板和相应的附件 URL。我有以下代码,它帮助我从我的收件箱成功发送带有独特附件的电子邮件。

但是,我想更改此代码,以便从我已经在我的 Gmail 设置中设置的别名(例如:alias@gmail.com)发送电子邮件,并请让我知道我应该做的所有更改我的 gmail 收件箱设置,以便从别名发送电子邮件。如果有人能告诉我如何更改下面的代码来做到这一点,我将不胜感激。提前致谢!

var EMAIL_SENT = "EMAIL_SENT";

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;
  var numRows = 3;
  var dataRange = sheet.getRange(startRow, 1, numRows, 5);
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[2];
    var subject = "Attachments";
    var message = row[4];
    var fileId = row[3].split("/")[5];
    var emailSent = row[0];
    try {
      var file = DriveApp.getFileById(fileId);
      if (emailSent != EMAIL_SENT) {
        GmailApp.sendEmail(emailAddress, subject, message, { attachments: [file.getBlob()] });
        sheet.getRange(startRow + i, 1).setValue(EMAIL_SENT);
        // SpreadsheetApp.flush(); // I think that this might not be required to be used.
      }
    } catch(e) {
      console.log("File of " + row[3] + "cannot be retrieved. Error message is " + e.message);
    }
  }
}
4

1 回答 1

1

GmailApp 在文档中对此提供了支持

sendEmail功能:

https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient,-subject,-body,-options

getAliases功能:

https://developers.google.com/apps-script/reference/gmail/gmail-app#getaliases

您需要确保您拥有 GmailApp 可以读取的别名,因此请尝试上述链接中的此代码段以查看您拥有哪些别名:

// Log the aliases for this Gmail account and send an email as the first one.
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases();
Logger.log(aliases);
if (aliases.length > 0) {
  GmailApp.sendEmail(me, 'From an alias', 'A message from an alias!', {'from': aliases[0]});
} else {
  GmailApp.sendEmail(me, 'No aliases found', 'You have no aliases.');
}

您需要准确地选择这些值之一才能使用该{'from': alias}参数

修改后的脚本

var EMAIL_SENT = "EMAIL_SENT";

function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;
  var numRows = 3;
  var dataRange = sheet.getRange(startRow, 1, numRows, 5);
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[2];
    var subject = "Attachments";
    var message = row[4];
    var fileId = row[3].split("/")[5];
    var emailSent = row[0];
    try {
      var file = DriveApp.getFileById(fileId);
      if (emailSent != EMAIL_SENT) {
        GmailApp.sendEmail(emailAddress, subject, message, { attachments: [file.getBlob()] , 'from': 'alias@gmail.com'});
        sheet.getRange(startRow + i, 1).setValue(EMAIL_SENT);
        // SpreadsheetApp.flush(); // I think that this might not be required to be used.
      }
    } catch(e) {
      console.log("File of " + row[3] + "cannot be retrieved. Error message is " + e.message);
    }
  }
}

参考

于 2021-03-09T11:06:58.057 回答