如何在Google Apps Script中条件化设置Gmail邮件附件
解决Google Apps Script中Gmail附件的条件化设置问题
在Google Apps Script插件的邮件发送功能中,通过开关变量emailAttach控制是否附加文件时,直接设置attachments: [file]会在开关关闭(file为空)时触发Non valid argument: attachments错误。尝试[file] || []这类写法无效,当前用if/else实现但代码冗余,可通过以下两种方式优化为单个createDraft调用:
方法1:提前构建配置对象,按需添加附件属性
先创建基础配置对象,再根据开关状态决定是否追加attachments属性:
// 构建基础邮件配置 let mailOptions = { name: emailSender || 'My Company', cc: emailSpecific, bcc: emailBCC, replyTo: emailReplyTo, htmlBody: emailBodyMessage }; // 若开启附件,则获取文件并添加到配置 if (emailAttach) { const attachmentFile = DriveApp.getFileById(fileID); mailOptions.attachments = [attachmentFile]; } // 单次调用创建草稿并发送 const mailId = GmailApp.createDraft(address, emailSubject, '', mailOptions).send().getId();
方法2:利用对象展开语法实现条件属性
通过对象展开运算符...,仅在开关开启时注入attachments属性:
// 仅在开启附件时获取文件,否则为null const attachmentFile = emailAttach ? DriveApp.getFileById(fileID) : null; // 单次调用创建草稿并发送,条件性添加附件 const mailId = GmailApp.createDraft(address, emailSubject, '', { name: emailSender || 'My Company', cc: emailSpecific, bcc: emailBCC, replyTo: emailReplyTo, htmlBody: emailBodyMessage, // 仅当emailAttach为真时,才添加attachments属性 ...(emailAttach && { attachments: [attachmentFile] }) }).send().getId();
原写法失效原因
当开关关闭时,file为null,[file]会生成[null]数组——这个数组本身是“真值”,不会被|| []替换为空数组,而Gmail API不接受包含null的附件数组,因此触发错误。
内容的提问来源于stack exchange,提问作者alsanmph
相关产品推荐
相关产品推荐

