Google AppScript邮件附件问题:无法附加表格文件,仅生成PDF并抛异常
问题
我编写了一段Google AppScript用于自动生成电子表格并发送邮件,但邮件始终只能附加PDF格式文件,无法添加表格格式文件。尝试使用getAs(MimeType.GOOGLE_SHEETS)或微软/开源办公格式时,抛出以下异常:
Exception: Blob object must have non-null data for this operation. generateEmailToSupplier @ GenerateEmailToSuppliers.gs:18 (anonymous) @ Main.gs:61 Main @ Main.gs:55
生成的电子表格已填充数据且可正常访问,相关代码如下:
/** * Generate and send email to supplier * * params: * - _supplier : String[] ===> [name of supplier, contact name, contact email] * - orderSheetId : Spreadsheet ===> file id forspreadsheet containing items to order */ function generateEmailToSupplier(_supplier, _orderSheetId){ const email = MailApp; const testEmailAddress = "fake@email.com"; const _orderSheet = DriveApp.getFileById(_orderSheetId) Logger.log(`mimetype email : ${_orderSheet.getMimeType()}`) email.sendEmail({ to: testEmailAddress, subject: ` Order Needed from ${_supplier[0]}`, htmlBody: `<p>Hey ${_supplier[1]} at ${_supplier[2]} ,<br><br> ` + "Attached is an excel sheet showing what products we would like to get an order for. <br>"+ "You can also log into the app for reference or make changes.<br><br>" + "This is an automated, weekly email.<br>"+ "Feel free to reach out to us with any questions.<br><br>"+ "Regards,<br><br>", attachments: [_orderSheet.getAs(MimeType.GOOGLE_SHEETS)] });
解决方案
问题根源
DriveApp.getFileById()获取的文件对象调用getAs()转换非PDF格式时会失败——Google Drive原生文件(如Google Sheets)无法直接通过这种方式导出为对应格式的Blob,必须使用SpreadsheetApp提供的专属导出方法。
修复步骤
- 替换文件获取方式:用
SpreadsheetApp.openById()获取电子表格对象,而非DriveApp的File对象 - 使用专属导出方法:通过Spreadsheet对象的
getBlob()方法,生成指定格式的可附加Blob文件
修正后的代码
/** * 生成并发送给供应商的邮件 * * 参数: * - _supplier : String[] ===> [供应商名称, 联系人姓名, 联系邮箱] * - orderSheetId : String ===> 包含待订购商品的电子表格ID */ function generateEmailToSupplier(_supplier, _orderSheetId){ const email = MailApp; const testEmailAddress = "fake@email.com"; // 改用SpreadsheetApp获取表格对象 const orderSpreadsheet = SpreadsheetApp.openById(_orderSheetId); // 导出为Excel格式的Blob,可替换为其他支持的MIME类型 const attachmentBlob = orderSpreadsheet.getBlob().setName(`订单_${_supplier[0]}.xlsx`); email.sendEmail({ to: testEmailAddress, subject: `需向${_supplier[0]}订购商品`, htmlBody: `<p>您好,${_supplier[1]}(${_supplier[2]}):<br><br> ` + "附件是我们需要订购的商品清单表格。<br>"+ "您也可以登录系统查看详情或修改内容。<br><br>" + "这是每周自动发送的邮件。<br>"+ "如有疑问,请随时联系我们。<br><br>"+ "此致<br><br>", attachments: [attachmentBlob] }); }
可选支持的MIME类型
- 微软Excel格式:
MimeType.MICROSOFT_EXCEL(对应.xlsx,兼容性最优) - Google Sheets格式:
MimeType.GOOGLE_SHEETS - OpenDocument表格格式:
MimeType.OPENDOCUMENT_SPREADSHEET
内容的提问来源于stack exchange,提问作者Cambo
相关产品推荐
相关产品推荐

