我想将网址附加到电子邮件中我使用了一些解决方案,例如根据请求获取pdf网址或将其作为文件读取但是它没有用。
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: 'example@example.com',
from: 'example@example.com',
subject: 'Test',
text: 'this is test',
html: '<strong>Hello World</strong>',
attachments: temp,
};
if ( temp.length == array.length )
sgMail.send(msg);
});
答案 0 :(得分:1)
这是对我有效的解决方案。您可以使用request npm模块从任何来源读取pdf文件,但不要错过{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: 'to@mail.com',
from: 'from@mail.com',
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);
}
});
})
答案 1 :(得分:0)
我们有sendgird github中的示例。注意:内容必须为字符串base64编码
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.pdf',
type: 'application/pdf',
disposition: 'attachment',
contentId: 'mytext'
},
],
};
答案 2 :(得分:0)
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;