使用nodemailer将内联图像移动到附件中



我有一个节点应用程序使用nodemailer成功发送电子邮件。我正在发送代码类似于此的电子邮件:

const emailRequest = {
from: { name: "Sender name", address: "sender@example.com" },
to: [/* recipients */],
subject: "Email subject",
text: "Some email text",
html: '<p>Some email text</p><p><img src="data:image/png;base64,{base64_image_content}">',
} as SendMailOptions;
const ses = new SES();
const transporter = nodemailer.createTransport({
SES: ses,
sendingRate: MAX_SEND_RATE,
});
transporter.sendMail(emailRequest, sendMailResponseHandler);

问题是,有时电子邮件正文包含这样格式的内联图像,其中{base64_image_content}是包含图像的实际数据:

<img src="data:image/png;base64,{base64_image_content}">

Gmail不支持内联图像数据。当我选择";显示原始"在Gmail中,但该图像不会出现在Gmail网络客户端中,而是在Gmail移动客户端中显示为损坏的图像。

我无法控制内联图像,所以我希望找到一种方法来提取内联图像数据,并将其作为附件添加到电子邮件中,并在调用transporter.sendMail之前使用cid引用电子邮件正文中的这些附件。

我想从以下内容更改HTML:

<p>Some email text</p><p><img src="data:image/png;base64,{base64_image_content}">

到此:

<p>Some email text</p><p><img src="cid:myImageCid">

并将图像添加为附件:

const emailRequest = {
// other things
attachments: [{ cid: "myImageCid", content: base64_image_content }]
} as SendMailOptions;

我需要帮助的部分是从原始电子邮件HTML中提取图像数据,并将其替换为cid引用。有什么办法我能做到吗?

require("fs").writeFile("out.png", (some_email_html.split("img")[1]).replace('">',"").split(",")[1], 'base64', function(err) {
console.log(err); 
});

上面的代码将从html中提取一个图像,假设someemailhtml是邮件的主体,并将其保存为out.png,您可以将名称更改为其他名称,并在发送电子邮件时删除。请注意,代码假设您需要一个图像,您可以修改以提取更多图像,或者如果您也需要帮助,请告诉我。

我最终听从了akisoft的建议,自己提取了图像数据。我是这样做的:

extractImages = (html: string) => {
// Match all image tags with data in their src
const regex = /<img src="data:.+?">/gs;
const images = html.match(regex) ?? [];
const attachments = images.map((originalImageTag) => {
// Parse out the image data and meta info
const imageSrc = (originalImageTag.match(/<img src="data:(.+?)">/s) ?? [])[1];
const [imageMeta, content] = imageSrc.split(",");
const [imageType, encoding] = imageMeta.split(";");
const fileType = imageType.split("/")[1];
const filename = `image.${fileType}`;
const cid = uuid();
const newImageTag = `<img src="cid:${cid}">`;
// Replace the image tags with ones that reference attached content
html = html.replace(originalImageTag, newImageTag);
// Collect attachment data to be passed to nodemailer
return {
filename,
cid,
encoding,
content,
contentDisposition: "inline",
} as Attachment;
});
// Return the modified HTML and the attachments
return { html, attachments };
};

我将原始电子邮件的HTML传递到该函数中,它会返回修改后的HTML和我可以直接传递给nodemailer的附件列表。

通过邮件发送附件,您可以在请求中提供附件。

const emailRequest = {
from: { name: "Sender name", address: "sender@example.com" },
to: [/* recipients */],
subject: "Email subject",
attachment: [{
path: filePath, //"public/data/somefile.png"
filename: filename,
cid: filename + "@"
}],
text: "Email text",
html: "Email HTML",
} as SendMailOptions;

相关内容

  • 没有找到相关文章

最新更新