nodejs & nodemailer

https://www.npmjs.com/package/nodemailer
上面的連接裏面 有有一個例子; 可以直接拿來用;

  • 安裝依賴,在package.json 中
{
        "name":"nodeEmailer",
    "version":"0.0.1",
    "description":"emailer",
    "dependencies":{
        "nodemailer": "~0.7.1"
    }
}
npm install 
  • 新建一個 email.js 文件
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport("SMTP",{
    service: 'Gmail',
    auth: {
        user: 'yourEmail@gmail.com',
        pass: 'yourPassword'
    }
});

var mailOptions = {
    from: 'sender address', // sender address
    to: 'you want to send email address', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ✔', // plaintext body
    html: '<b>Hello world ✔</b>' // html body
};

transporter.sendMail(mailOptions, function(error, info){
    if(error){
        console.log(error);
    }else{
        console.log('Message sent: ' + info.response);
    }
});

上面的例子中 如果出現

[Error: No transport method defined]

可能的原因為
var transporter = nodemailer.createTransport("SMTP",{} 中的 "SMTP"

添加附件

var fs=require('fs');
var img=fs.readFileSync(__dirname+"/1.png"); //讀取文件(圖片)
var attachment=[{
'filename':'1.png', //文件名稱
'contents':img   //加載文件 圖片
}];
/**/
var mailOptions = {
    from: 'xxxxx@gmail.com', // sender address
    to: '4xxxx2@qq.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ✔', // plaintext body
    html: '<b>Hello world ✔</b>' ,// html body
    attachments:attachment    //添加附件
};
posted on 2015-04-27 13:50  ทดสอบ  阅读(260)  评论(0编辑  收藏  举报