2

I am using Sendgrid API v3 in a node.js and express environment.

I am using email dynamic templates and easily I can send custom text to the email templates.

But I need also to add attachments and I can't find documentation about that. I need to add attachments in 2 different ways:

  1. There are email that need to have always the same attachments and it would be good for the email template to have its own attachments that is send to the customer inbox not matter what is the server data sent to sendgrid.
  2. If a clinet buys an ebook, this file should be sent by the server, together with the rest of {{{data}}} to Sendgrid and this specific file should be delivered to the client as an attachments.

Can anyone say how to add attachments this way?

Thanks

Pikk
  • 2,343
  • 6
  • 25
  • 41

2 Answers2

0

Not sure if you still need it. But you can send emails using Dynamic Template and Attachments. Reference with their API Doc.

Sample code:


const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const fs = require("fs");

pathToAttachment = `${__dirname}/attachment.pdf`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");

const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with SendGrid is Fun',
  templateId: "d-11111111111111111111111111",
  attachments: [
    {
      content: attachment,
      filename: "attachment.pdf",
      type: "application/pdf",
      disposition: "attachment"
    }
  ]
};

sgMail.send(msg).catch(err => {
  console.log(err);
});

For your 2 cases, why not build a function to send emails with parameters of dynamic template ID and attachments?

sendEmail(
    templateId: string, 
    attachments: Attachment

)
-1

Sendgrid attachments are limited to 30mb which might be too small for what you are trying to do. Sendgrid let's you use the digioh api to send files up to 2gb. https://digioh.com/sendgrid

An alternative solution would be to send a callback url as text in the email that is linked to an endpoint on your express server that let's users download the data. In this case you would need some additional setup to make sure only users who purchased the items can download them.