Nodemailer 将 base64 数据 URI 作为附件发送.如何? [英] Nodemailer send base64 data URI as attachment. How?

查看:28
本文介绍了Nodemailer 将 base64 数据 URI 作为附件发送.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个使用 Canvas 创建的图像,它在 base64 编码的数据 URI 中.然后将此数据 URI 附加到电子邮件中.

Basically I have an image created using Canvas and it's in base64 encoded data URI. This data URI is then attached to email.

...,
 attachments:[{
 filename: "cat.jpg",
 contents: new Buffer(cat, 'base64')
}],

已收到电子邮件,但无法查看附件.在 linux 中运行 $ file cat.jpg 返回:

The email is received but the attachment is not viewable. Running $ file cat.jpg in linux returns:

cat.jpg: ASCII text, with very long lines, with no line terminators

为什么是 ASCII?我已经提到过base64.我该如何解决这个问题?谢谢.

Why is this ASCII? I had already mentioned base64. How may I fix this problem? Thank you.

推荐答案

变量 cat 可能包括 'data:image/jpeg;base64,' 部分.您不应该将该位传递给 Buffer.from.

The variable cat probably includes the 'data:image/jpeg;base64,' part. You shouldn't pass that bit to Buffer.from.

看来,如果传入无效数据,Buffer.from() 不会报错:

It seems that if you pass in invalid data, Buffer.from() doesn't complain:

var pixel = "data:image/gif;base64,"
    + "R0lGODlhAQABAIABAP///wAAACH5"
    + "BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
var buffer = Buffer.from(pixel, "base64"); // does not throw an error.

你甚至会得到一个有效的缓冲区.缓冲区是一个损坏的图像(或者更确切地说,它不是以图像标题开头).

You even get back a valid Buffer. The buffer is a corrupt image (or rather, it doesn't begin with an image header).

您必须自己剥离数据 URI 的第一部分:

You have to strip the first part of the data URI yourself:

var buffer = Buffer.from(pixel.split("base64,")[1], "base64");


编辑(2021 年 5 月):将 new Buffer 更改为 Buffer.from,因为前者已弃用.


Edit (may 2021): Changed new Buffer to Buffer.from, as the former is deprecated.

这篇关于Nodemailer 将 base64 数据 URI 作为附件发送.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆