我正在尝试编写一个脚本,该脚本将从特定的Google云端硬盘文件夹中获取所有文件并将其作为电子邮件附件发送。我需要每个附件都是自己的个人电子邮件。
这是我到目前为止所拥有的:
function sendEmails() {
var files = DriveApp.getFolderById("FolderID").getFilesByType(MimeType.JPEG);
var attachments = [];
while (files.hasNext()) {
var file = files.next();
attachments.push(file.getAs(MimeType.JPEG));
Logger.log(attachments)
var emailAddress = "testest@test.com";
var message = "image attached";
var subject = "test";
var attachment = (attachments)
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: message,
attachments: attachments
})
}
}
此时,脚本正在发送电子邮件,但会连续添加附件。因此,如果文件夹有3个JPEG,它将发送3封电子邮件,其中一封包含1个附件,另一封包含2个,第3封包含所有3个附件。
我对这一切都很陌生,但真的很喜欢乱搞它。我很困惑在获取文件后该怎么做以及如何将它们作为附件链接到他们自己的个人电子邮件。我是否需要为每个附件提供自己的数组?
提前致谢。
答案 0 :(得分:0)
推送 - 将文件添加到堆栈。
pop - 从堆栈中检索并删除文件。
使用推送,您只需将另一个文件添加到当前文件列表中。
attachments.push(file.getAs(MimeType.JPEG));*
您需要做的是从列表中 pop 文件删除它们。所以不要像以下那样抓住整个列表:
var attachment = (attachments)
你应该这样做:
var attachment = attachments.pop()
目前,您的while {...}
语句首先将另一个文件添加到列表中,然后发送整个文件列表而不删除已发送的文件。
所以你的代码应该是这样的:
function sendEmails() {
var files = DriveApp.getFolderById("FolderID").getFilesByType(MimeType.JPEG);
var attachments = [];
while (files.hasNext()) {
var file = files.next();
attachments.push(file.getAs(MimeType.JPEG));
Logger.log(attachments)
var emailAddress = "testest@test.com";
var message = "image attached";
var subject = "test";
var attachment = (attachments.pop())
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: message,
attachments: attachments
})
}
}
就个人而言,我会删除该列表,因为您不需要存储每个文件,您只想将它们发送到单独的邮件中。
function sendEmails() {
var files = DriveApp.getFolderById("FolderID").getFilesByType(MimeType.JPEG);
while (files.hasNext()) {
var file = files.next();
// gets curent file only
var attachments = (file.getAs(MimeType.JPEG));
Logger.log(attachments)
var emailAddress = "testest@test.com";
var message = "image attached";
var subject = "test";
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: message,
attachments: attachments
})
}
}