2015-08-31 71 views
1

目前我能夠使用代碼線沿線的發送電子郵件在node.js中圖片附件:發送電子郵件,在Node.js的

var nodemailer = require("nodemailer"); 

var smtpTransport = nodemailer.createTransport("SMTP",{ 
    service: "Gmail", 
    auth: { 
     user: "[email protected]", 
     pass: "gmailpass" 
    } 
}); 

smtpTransport.sendMail({ 
    from: "My Name <[email protected]>", // sender address 
    to: "Your Name <[email protected]>", // 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發送的電子郵件中?

+0

訂閱在電子郵件中使用Nodemailer可能重複的[如何將文件附加到與nodemailer電子郵件](http://stackoverflow.com/questions/21934667/how-to-attach-file-to- an-email-with-nodemailer) – royhowie

+0

不僅因爲我需要從html表格上載圖像 – thenodecoder

+0

保存圖像然後附加它,如鏈接問題中所述。 – royhowie

回答

2

你可以嘗試這樣的事情。使用busboy獲取文件,然後一旦你得到文件將其轉換爲base64並將其添加到附件屬性爲您的郵件選項。唯一的是我不知道如果文件參數回來作爲緩衝區。如果它不,你只需要轉換該文件對於底座64將能夠將其發送作爲一個附件

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

var smtpTransport = nodemailer.createTransport("SMTP",{ 
    service: "Gmail", 
    auth: { 
     user: "[email protected]", 
     pass: "gmailpass" 
    } 
}); 

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

    var mailOptions = { 
     from: "My Name <[email protected]>", // sender address 
     to: "Your Name <[email protected]>", // 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 
      }); 
     }); 
}); 
0

Nodemailer是最好的node.js中發送郵件我已經在電子郵件訂閱comparetrap