用nodejs发送电子邮箱,首先需安装nodemailer
npm install nodemailer
var mail = require('nodemailer');
SMTP
nodemailer.SMTP = {
host: 'smtp.example.com',
port: 25,
use_authentication: false,
user: '',
pass: ''
}
参数详解:
host: 'smtp.example.com', //定义用来发送邮件的邮箱服务器,一般是QQ(smtp.qq.com),gmail(smtp.gmail.com)这些的 port:25, //定义服务器端口,一般是25 ,如果是使用SSL端口一般为465如果使用TLS/STARTTLS (port 587) ssl:false, //默认为false,表示不用SSL,如果为true,则port为465, user: 'my@example.com', //邮箱用户名,只有当use_authentication: true时才用 pass:'**********' //输入邮箱密码,只有当use_authentication: true时才用
send_mail
mail.send_mail( { sender:'me@example.com', //发送邮件的地址 to:'you@example.com', //发给谁 subject:'测试', //主题 body:'发送邮件成功', //发送的内容 html:'<p>hello</p>', //如果要发送html attachments: attachment //如果要发送附件 }, //回调函数,用户判断发送是否成功,如果失败,输出失败原因。 function(error,success){ if(!error){ console.log('message success'); }else{ console.log('failed'+error); } }
如果要发送的附件,附件的定义格式如下
var fs = require('fs'); //需要用到fs var img = fs.readFileSync(__dirname+"/img.png"); //导入图片 var attachment_list = [ { 'filename': 'attachment1.txt', //这里只是给附件取名称,而不是导入文件内容 'contents': 'contents for attachment1.txt' //引入附件 }, { 'filename': 'аттачмент2.bin', 'contents': new Buffer('binary contents', 'binary'); }, { 'filename': "img.png", 'contents': img //导入图片文件 } ];
附件可是嵌入HTML的图像。要使用此功能,你需要设置附加属性的附件 -CID(文件的唯一标识符)
var cid_value = Date.now() + '.image.jpg'; var html = 'Embedded image: <img src="cid:' + cid_value + '" />'; var attachments = [{ filename: 'image.png', contents: IMAGE_CONTENTS, cid: cid_value }];
更详细的信息参见: http://www.nodemailer.org/