如何使用Node.js(SendGrid)从URL附加PDF到邮件?
解决SendGrid邮件附加远程PDF的问题
我看了你的代码,问题主要出在附件字段的错误使用和循环逻辑的小瑕疵上。SendGrid的attachments配置里,path是用来指定本地文件路径的,远程URL得用url字段才行;另外你的循环写法可以更简洁清晰。
问题点拆解
- 你用
path: data指定远程PDF URL是错误的,path仅支持本地文件系统路径,远程资源必须用url字段。 - 循环中每次往
temp数组push附件后判断长度再发送,逻辑可行但不够直观,不如先把所有附件准备好再统一构建邮件。 - 两个附件都用同一个
filename: 'hello.pdf',会导致收件端看到重名附件,建议改成差异化命名避免混淆。
修正后的代码
const sgMail = require('@sendgrid/mail'); sgMail.setApiKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); // 定义要附加的PDF URLs const pdfUrls = [ 'https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf', 'https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf' ]; // 构建附件数组:用url字段替代path,同时设置差异化文件名 const attachments = pdfUrls.map((url, index) => ({ url: url, filename: `sample-${index + 1}.pdf` // 避免重名问题 })); // 构建邮件对象 const msg = { to: 'example@example.com', from: 'example@example.com', subject: 'Test', text: 'this is test', html: '<strong>Hello World</strong>', attachments: attachments }; // 发送邮件并处理结果 sgMail.send(msg) .then(() => console.log('邮件发送成功')) .catch(error => console.error('发送失败:', error.response.body));
额外说明
如果你的需求是先把远程PDF下载到本地再附加,那需要用fs模块读取文件内容,转成base64后放到content字段里,同时设置disposition: 'attachment'。不过直接用url字段是SendGrid官方推荐的远程附件方式,更简洁高效。另外要确保你的SendGrid API Key已完成域名和邮箱验证,避免邮件被拦截。
内容的提问来源于stack exchange,提问作者shahrokh
相关产品推荐
相关产品推荐

