【问题标题】:Nodemailer send base64 data URI as attachment. How?Nodemailer 发送 base64 数据 URI 作为附件。如何?
【发布时间】:2021-05-06 19:50:50
【问题描述】:

基本上我有一个使用 Canvas 创建的图像,它位于 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。我该如何解决这个问题? 谢谢。

【问题讨论】:

    标签: node.js nodemailer


    【解决方案1】:

    不需要缓冲区。你可以把从base64编码前缀后面开始的字符串放进去:

    var cat = "...base64 encoded image...";
    var mailOptions = {
      ...
      attachments: [
        {   // encoded string as an attachment
          filename: 'cat.jpg',
          content: cat.split("base64,")[1],
          encoding: 'base64'
        }
      ]
    };
    

    您可以在此处找到更多详细信息:https://github.com/nodemailer/nodemailer#attachments

    【讨论】:

      【解决方案2】:

      变量cat 可能包含'data:image/jpeg;base64,' 部分。你不应该把那个位传递给Buffer.from

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

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

      您甚至可以取回一个有效的缓冲区。缓冲区是损坏的图像(或者更确切地说,它不是以图像标题开头)。

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

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

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

      【讨论】:

      • 现在可以使用了。我只是好奇,你知道这个还是你测试过?
      • 不确定我是否正确解释了您的问题,但是:我知道 Nodemailer 想要一个有效的图像缓冲区,我测试 new Buffer(stringWithPrefix)创建损坏的图像,new Buffer(stringWithoutPrefix) 不会。我可以看到构造函数不会导致错误,并且两个缓冲区没有以相同的字节开头(如预期的那样)。将文件写入磁盘并检查其完整性。这能回答你的问题吗?
      【解决方案3】:

      您可以简单地使用包nodemailer-base64-to-s3

      安装包:

      npm install -s nodemailer-base64-to-s3
      

      使用 nodemailer 配置它:

      var base64ToS3 = require('nodemailer-base64-to-s3');
      var nodemailer = require('nodemailer');
      
      var transport = nodemailer.createTransport({});
      transport.use('compile', base64ToS3(opts));
      

      https://github.com/ladjs/nodemailer-base64-to-s3

      【讨论】:

        【解决方案4】:

        您可以直接使用path,而无需任何额外操作:

            let attachments = [
                {
                    filename: "image.gif",
                    path: "data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
                }
            ]
        

        这里是相关documentation的链接

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-08-05
          • 2022-01-16
          • 2016-03-30
          • 2022-07-15
          • 2017-11-26
          • 1970-01-01
          • 2020-09-03
          相关资源
          最近更新 更多