发送含多个动态附件的邮件报错:Exception: Invalid argument: attachments
问题排查与解决
错误原因
MailApp.sendEmail方法的attachments参数要求传入File对象或Blob对象组成的数组,但你的代码中往attach数组里添加的是文件ID字符串,完全不符合参数类型要求,这就是触发"Exception: Invalid argument: attachments"错误的直接原因。
修正方案
只需要去掉代码中.getId()的调用,直接将DriveApp.getFileById()返回的File对象存入数组即可:
修正后的完整代码:
var attach = []; for (ii = 0; ii < 6; ii ++) { if (impiegati[ii][4]) { attach.push(DriveApp.getFileById(impiegati[ii][4])); }; }; MailApp.sendEmail(dest, obj, body, {htmlBody: body, attachments: attach});
额外建议
如果impiegati[ii][4]可能存在无效的文件ID(比如空值、错误ID),可以添加try-catch块捕获异常,避免单个无效ID导致整个邮件发送流程中断:
var attach = []; for (ii = 0; ii < 6; ii ++) { if (impiegati[ii][4]) { try { attach.push(DriveApp.getFileById(impiegati[ii][4])); } catch(e) { console.log(`无效文件ID:${impiegati[ii][4]},跳过该附件`); } }; }; MailApp.sendEmail(dest, obj, body, {htmlBody: body, attachments: attach});
内容的提问来源于stack exchange,提问作者LUCA DELLA GHEZZA
相关产品推荐
相关产品推荐

