在 node.js 中使用 sendgrid 在电子邮件中发送嵌入图像
我想使用 sendgrid 从节点 js 发送带有嵌入图像的电子邮件。我使用以下代码
var base64Img = require('base64-img');
const sgMail = require('@sendgrid/mail');
var base64str = base64_encode("logo.png");
function base64_encode(file) {
var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString("base64");
}
sendMail(["[email protected]"],base64str);
function sendMail(emails,data)
{
sendgrid.send({
to: emails[0],
from: '[email protected]',
subject: 'Test Mail',
attachments: [
{
filename: "logo.png",
type : "image/png",
content: data,
content_id: "myimagecid",
disposition : "inline"
}
],
html:"Please look on the image <img src='content_id:myimagecid' alt='no image found'/>",
}, function (err) {
if (err) {
response.json({ message: 'Selected but Mail not sended and Error is'+err });
console.log("Mail error",err);
} else {
console.log("Success Mail sended ");
response.json({ message: 'Selected and Mail sended' });
}
});
}
这里我使用了disposition : "inline" 但图像仍然作为附件发送。谁能帮帮我吗?
回答如下:您将文件定义为附件,因此它最终就是这样。 相反,您需要将其定义为一个文件,然后在您的 html 代码中调用它。
如果你通读这篇文章...
https://sendgrid/blog/embedding-images-emails-facts/ ,
...你会发现这实际上不是推荐的方法。相反,您可能希望将 base64 图像直接嵌入到您的 html 中。