1
votes

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": "[email protected]" } ] } ],
    from: { email: "[email protected]" },        
    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

1 Answers

1
votes

You can try following snippet from Sendgrid API:

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: '[email protected]',
  from: '[email protected]',
  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": "[email protected]" } ] } ],
from: { email: "[email protected]" },        
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});
};