在node.js中发送带有图像附件的电子邮件

时间:2015-08-31 23:12:13

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

目前,我可以使用以下代码的代码在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发送的电子邮件中?

2 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情。使用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
           });
        });
});

答案 1 :(得分:0)

Nodemailer是最好在node.js中发送邮件的。我在电子邮件订阅中使用了Nodemailer comparetrap