提问者:小点点

Azure Function (JS) 使用 SendGrid 和附件


我想使用 SendGrid 从 Azure 函数 (Javascript) 发送带有附件的电子邮件。我已经做了以下工作

>

  • 为发送网格 API 密钥创建了一个新的应用设置
  • Azure 函数的发送网格输出绑定集
  • 以下是我的 Azure 函数

    module.exports = function (context, myQueueItem) {
    var message = {
     "personalizations": [ { "to": [ { "email": "testto@test.com" } ] } ],
    from: { email: "testfrom@test.com" },        
    subject: "Azure news",
    content: [{
        type: 'text/plain',
        value: myQueueItem
    }]
    };
    context.done(null, {message});
    };
    

    电子邮件正在正确发送。但是如何添加附件?


  • 共1个答案

    匿名用户

    您可以尝试从 Sendgrid API 中使用以下代码片段:

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: 'recipient@example.org',
      from: 'sender@example.org',
      subject: 'Hello attachment',
      html: '<p>Here’s an attachment for you!</p>',
      attachments: [
        {
          content: 'Some base 64 encoded attachment content',
          filename: 'some-attachment.txt',
          type: 'plain/text',
          disposition: 'attachment',
          contentId: 'mytext'
        },
      ],
    };
    

    所以在你的上下文中:

    module.exports = function (context, myQueueItem) {
    var message = {
     "personalizations": [ { "to": [ { "email": "testto@test.com" } ] } ],
    from: { email: "testfrom@test.com" },        
    subject: "Azure news",
    content: [{
        type: 'text/plain',
        value: myQueueItem
    }],
    attachments: [
        {
          content: 'Some base 64 encoded attachment content',
          filename: 'some-attachment.txt',
          type: 'plain/text',
          disposition: 'attachment',
          contentId: 'mytext'
        },
      ]
    };
    context.done(null, {message});
    };