首页 > 解决方案 > 使用谷歌脚本将图片正确附加到电子邮件

问题描述

我正在尝试使用谷歌表格和表格制作一个脚本,以帮助自动化和跟踪我们技术人员在工作现场的照片。

设置是他们拍摄工作现场的照片并填写带有信息的谷歌表格并将图片附在此处。提交表单后,它会运行此脚本以将电子邮件发送到办公室中每个人都可以看到的预定电子邮件。

到目前为止,除了图片之外,我还可以通过电子邮件发送表格中的信息。

所附图片的信息以驱动器 url 的形式出现,该驱动器 url 全部作为字符串转储到一个单元格中。

"https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz"

我将此字符串转换为一个数组,使用 .split(" ,)该数组输出它。

[https://drive.google.com/open?id=xxxxxxxx, https://drive.google.com/open?id=yyyyyyyy, https://drive.google.com/open?id=zzzzzzzz]

然后我遍历数组并使用.slice(33)它来摆脱 url,所以我剩下的就是驱动器 id(可能有更好的方法,但它现在有效)。

[xxxxxxxx, yyyyyyyy, zzzzzzzz]

这是我遇到麻烦的部分。然后我通过该数组迭代 agian 并获取 driveID 并将文件作为 JPEG 获取。然后.push,我将其放入另一个数组中,用于将它们附加到电子邮件中。

问题是我认为我没有正确地执行此步骤,因为没有将正确的东西推入阵列和/或假设MailApp.sendEmail甚至可以将阵列用于附件。我也不完全确定它们是如何[Blobs]工作以及如何正确使用它们,这可能就是我卡住的地方。

同样,这是在很少经验的情况下编写的代码,可能会进一步优化,但目前,我只需要让它正确地附上图片以显示它的工作原理。

function onFormSubmit(e) {
  //for testing purposes
  var values = e.namedValues;
  //gets the form's values
  var pureValues = e.values;

  //sets the values
  var email = pureValues[1];
  var woNum = pureValues[2];
  var firstN = pureValues[3];
  var lastN = pureValues[4];
  var desc = pureValues[5];
  var superDuperRawPics = pureValues[6];

  //splits the picture urls into an array
  var superRawPics = superDuperRawPics.split(", ");

  //slices the url part off to get the drive ID
  var i, rawPics =[]
  for (i = 0; i < superRawPics.length; ++i) {
    rawPics.push(superRawPics[i].slice(33))
       }

  //takes the array of ID's and gets the drive file
  var j, picAttach =[]
  for (j = 0; j < rawPics.length; ++j) {
    var driveID = DriveApp.getFileById(rawPics[j]);
    var drivePic = driveID.getAs(MimeType.JPEG);
    picAttach.push(drivePic);
  }

  //sets the subject of the email to be Jobsite Pictures and the work number
  var subject = "Jobsite Pictures" + " " + woNum;

  //sets the body of the email
  var body = "Technician: " + email + " \n" + 
             "WO#: " + woNum + " \n" + 
             "Customer: " + firstN + " " + lastN + " \n" + 
             "Description: " + desc;

  //for checking if the vars are set correctly
  Logger.log(superDuperRawPics);
  Logger.log(superRawPics);
  Logger.log(rawPics);
  Logger.log(picAttach);
  Logger.log(subject);
  Logger.log(body);

  //sends email to me with the new info
  MailApp.sendEmail('example@domian.com', subject, body, {attachments: [picAttach]});


}

标签: emailgoogle-apps-scriptgoogle-drive-apiblobemail-attachments

解决方案


如果您只想附加它们,请使用选项附件


推荐阅读