Azure Function (JS) using SendGrid with attachment

孤街醉人 提交于 2019-12-24 08:26:10

问题


I want to send emails with attachment from an Azure function (Javascript) using SendGrid. I have done the following

  1. created a new AppSettings for SendGrid API Key
  2. SendGrid output binding set of Azure Function
  3. Following is my Azure Function

    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});
    };
    

Email is getting send correctly. But how do i add an attachment?


回答1:


You can try following snippet from 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'
    },
  ],
};

So in your context:

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});
};


来源:https://stackoverflow.com/questions/50041375/azure-function-js-using-sendgrid-with-attachment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!