Nodemailer发送base64数据URI作为附件。 怎么样?
基本上我有一个使用Canvas创build的图像,它使用base64编码的数据URI。 这个数据URI然后被附加到电子邮件。
..., attachments:[{ fileName: "cat.jpg", contents: new Buffer(cat, 'base64') }],
收到电子邮件,但附件不可见。 在linux中运行$ file cat.jpg
返回:
cat.jpg: ASCII text, with very long lines, with no line terminators
为什么这个ASCII? 我已经提到了base64。 我该如何解决这个问题? 谢谢。
variablescat
可能包含'data:image / jpeg; base64'部分。 你不应该把这个位传递给Buffer
构造函数。
看来如果你传入无效的数据, new Buffer()
不会抱怨:
var pixel = "data:image/gif;base64," + "R0lGODlhAQABAIABAP///wAAACH5" + "BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; var buffer = new Buffer(pixel, "base64"); // does not throw an error.
你甚至可以得到一个有效的缓冲区。 该缓冲区是一个损坏的图像(或者说,它不是以图像头开始)。
您必须自己去除数据URI的第一部分:
var buffer = new Buffer(pixel.split("base64,")[1], "base64");
您可以简单地使用包nodemailer-base64-to-s3
。
安装软件包:
npm install -s nodemailer-base64-to-s3
使用nodemailer进行configuration:
var base64ToS3 = require('nodemailer-base64-to-s3'); var nodemailer = require('nodemailer'); var transport = nodemailer.createTransport({}); transport.use('compile', base64ToS3(opts));
缓冲区是不需要的。 你可以把从base64编码前缀后面开始的string放到里面:
var cat = "...base64 encoded image..."; var mailOptions = { ... attachments: [ { // encoded string as an attachment filename: 'cat.jpg', content: cat.split("base64,")[1], encoding: 'base64' } ] };
更多的细节你可以在这里find: https : //github.com/nodemailer/nodemailer#attachments