Reputation: 142
I want to attach url to Email I used some solutions such as getting pdf url by request or read it as file but it didn't work.
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
var array = [],
temp = [];
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-
link_1.pdf');
array.push('https://www.antennahouse.com/XSLsample/pdf/sample-
link_1.pdf');
array.forEach(function(data) {
temp.push({
path: data,
filename: 'hello.pdf'
});
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Test',
text: 'this is test',
html: '<strong>Hello World</strong>',
attachments: temp,
};
if ( temp.length == array.length )
sgMail.send(msg);
});
Upvotes: 1
Views: 2615
Reputation: 264
const sgMail = require('@sendgrid/mail');
const pdf2base64 = require('pdf-to-base64');
sgMail.setApiKey(apiKey);
const body = await sgMail.send({
to: email,
from,
subject: "subject",
html: "hello welcome",
...(
attachments && attachments.length && {
attachments:attachments.map(attachment=>({
content: attachment,
filename: "attachment.pdf",
type: "application/pdf",
disposition: "attachment"
}))
}
)
});
return body;
Upvotes: 0
Reputation: 49
This is working solution for me. you can use request npm module to read your pdf file from any source but dont miss { encoding: null }.
const sgMail = require('@sendgrid/mail');
var request = require('request');
request.get('https://someurl/output.pdf',{ encoding: null },(err,res) => {
console.log(res);
var base64File = new Buffer(res.body).toString('base64');
sgMail.setApiKey('yourSendgridApiKey');
const msg = {
to: '[email protected]',
from: '[email protected]',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
attachments: [
{
content: base64File,
filename: 'some.pdf',
ContentType: 'application/pdf',
disposition: 'attachment',
contentId: 'mytext'
},
]
}
sgMail.send(msg, (error, data) => {
if (error) {
console.log('error', error)
} else {
console.log('successfully sent email' + data);
}
});
})
Upvotes: 3
Reputation: 3431
We have example from sendgird github. Noted: content must be string base64 encoded
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.pdf',
type: 'application/pdf',
disposition: 'attachment',
contentId: 'mytext'
},
],
};
Upvotes: -1