You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Function(JavaScript)中用SendGrid发送带附件的邮件?

在Azure Function(JavaScript)中使用SendGrid发送带附件的邮件

既然你已经完成了SendGrid API密钥的应用设置和输出绑定配置,接下来只需要在邮件消息对象中添加attachments数组,就能实现带附件的邮件发送了。下面是完整的实现代码和关键细节说明:

完整函数代码示例

const fs = require('fs');
const path = require('path');

module.exports = function (context, myQueueItem) {
    // 示例:读取函数目录下的本地文件并转为Base64编码
    // 如果你是从其他来源获取附件内容(比如Blob存储),替换这部分逻辑即可
    const attachmentPath = path.join(context.executionContext.functionDirectory, 'sample.pdf');
    const attachmentContent = fs.readFileSync(attachmentPath).toString('base64');

    const message = {
        personalizations: [
            {
                to: [{ email: "testto@test.com" }]
            }
        ],
        from: { email: "testfrom@test.com" },
        subject: "Azure news",
        content: [{ type: 'text/plain', value: myQueueItem }],
        // 核心:添加附件配置
        attachments: [
            {
                content: attachmentContent, // Base64编码的文件内容
                filename: "sample.pdf", // 收件人看到的文件名
                type: "application/pdf", // 文件的MIME类型
                disposition: "attachment" // 指定为附件类型
            }
        ]
    };

    // 将消息赋值给SendGrid输出绑定
    context.bindings.sendGridMessage = message;
    context.done();
};

关键细节说明

  • 附件内容编码:SendGrid要求附件内容必须是Base64编码的字符串,所以不管你的附件来自哪里(本地文件、Blob、数据库等),都需要先转成这种格式。
  • MIME类型:根据你发送的文件类型填写对应的MIME类型,比如文本文件用text/plain,图片用image/png,Excel文件用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet等。
  • 文件路径:如果是读取本地文件,使用context.executionContext.functionDirectory可以定位到当前函数的根目录,确保文件已经随函数一起部署(比如通过Zip部署、GitHub Actions等方式上传)。

确认输出绑定配置

为了确保代码能正常工作,再检查下你的function.json里的SendGrid输出绑定配置是否正确:

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "你的队列名称",
      "connection": "AzureWebJobsStorage"
    },
    {
      "type": "sendGrid",
      "name": "sendGridMessage", // 这个名称要和代码里context.bindings的键一致
      "direction": "out",
      "apiKey": "%SendGridApiKey%", // 对应你创建的应用设置名称
      "from": "testfrom@test.com"
    }
  ]
}

内容的提问来源于stack exchange,提问作者user2700254

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:43:54