【问题标题】:Send email with image attachment in node.js在 node.js 中发送带有图像附件的电子邮件
【发布时间】:2017-12-29 14:32:57
【问题描述】:

目前我可以使用以下代码在 node.js 中发送电子邮件:

var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
   service: "Gmail",
   auth: {
       user: "gmail.user@gmail.com",
       pass: "gmailpass"
   }
});

smtpTransport.sendMail({
   from: "My Name <me@example.com>", // sender address
   to: "Your Name <you@example.com>", // comma separated list of receivers
   subject: "Hello ✔", // Subject line
   text: "Hello world ✔" // plaintext body
}, function(error, response){
   if(error){
       console.log(error);
   }else{
       console.log("Message sent: " + response.message);
   }
});

如何在此电子邮件中发送来自 html 表单 的上传图片的附件?另外,我可以在电子邮件中发送图像而不将其上传到服务器吗?如果没有,那也没关系。这是我的 html 表单:

<form id="mainForm">
    <input type="file" id="fileUpload">
    <input type="submit" id="submit" name="submit">
</form>

如何获取文件并将其包含在使用 node.js 发送的电子邮件中?

【问题讨论】:

  • 不只是因为我需要从html表单上传图片
  • 保存图像然后附加它,如链接问题中所述。
  • 您使用的是 Express 吗?如果是这样,请尝试 Multer 解析表单/多部分 POST 请求并获取文件。
  • 所以我必须上传到服务器然后附加它?

标签: javascript node.js email file-upload nodemailer


【解决方案1】:

你可以试试这样的。使用 busboy 获取文件,然后在获取文件后将其转换为 base64 并将其添加到您的邮件选项的附件属性中。唯一的事情是我不知道文件参数是否作为缓冲区返回。如果不是,您只需将该文件转换为 base 64 即可将其作为附件发送

var app = express();
var Busboy = require('busboy');
var nodemailer = require("nodemailer");

var smtpTransport = nodemailer.createTransport("SMTP",{
    service: "Gmail",
     auth: {
         user: "gmail.user@gmail.com",
         pass: "gmailpass"
     }
});

app.post('/email', function(req, res){
    var busboy = new Busboy({ headers: req.headers });
    var attachments = [];

    var mailOptions = {
        from: "My Name <me@example.com>", // sender address
        to: "Your Name <you@example.com>", // comma separated list of receivers
        subject: "Hello ✔", // Subject line
        text: "Hello world ✔" // plaintext body
    };

    busboy
        .on('file', function(fieldname, file, filename, encoding, mimetype){
            attachments.push({
               filename: filename,
               content: file.toString('base64'),
               encoding: 'base64'
            });
        })
        .on('finish', function() {
            mailOptions.attachments = attachments;
            smtpTransport.sendMail(mailOptions, function (err, info) {
               if (err) {
                   //handle error
               }
                // email sent
           });
        });
});

【讨论】:

  • 我知道这是旧的,但我有一个问题。仅供参考,我正在使用multer npm,这与这种方法非常相似。但是,如果附件不是图像类型,是否可以阻止发送电子邮件。 (例如,阻止发送 .docx 文件)?
  • 您可以检查文件的 mimetype 并验证它是否与您支持的文件之一匹配
猜你喜欢
  • 2012-10-05
  • 2018-03-09
  • 2023-03-22
  • 2015-09-09
  • 2013-06-01
  • 2011-11-22
相关资源
最近更新 更多