Reputation: 2753
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:
Can anyone say how to add attachments this way?
Thanks
Upvotes: 5
Views: 5715
Reputation: 86
Send emails using Dynamic Template and Attachments. There are examples in the Sendgrid Email API Docs.
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: '[email protected]',
from: '[email protected]',
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
)
If you need to include that image in the html of the Dynamic Template, add attachments.content_id
(also in the docs).
From the docs:
content ID...is used when the disposition is set to “inline”
For instance, your code might include this snippet:
attachments: [
{
content: attachment,
filename: "my_cool_image.png",
type: "image/png",
disposition: "inline",
content_id: "my_cool_image"
}
]
and in your Dynamic Template:
<img src="cid:my_cool_image" alt="cool" title="cool"/>
Upvotes: 4
Reputation: 71
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.
Upvotes: 0