前段时间有个很普通的项目须要发邮件的功能,并且是刚开始学nodejs,因此只是搜索了下用什么好的库能实现,就找到了nodemailer了。这篇文章主要是记录一下使用的过程和经验。
这里就先上配置javascript
nodejs: v6.9.4html
npm: 3.10.10java
nodemailer: ^4.1.0node
const params = { host: 'smtp.163.com', // 设置服务 port: 465, // 端口 sercure: true, // 是否使用TLS,true,端口为465,不然其余或者568 auth: { user: config.user, // 邮箱和密码 pass: config.emailPwd } } // 邮件信息 const mailOptions = { from: config.user, // 发送邮箱 to: config.emailTo, // 接受邮箱 subject: config.title, // 标题 html: config.html // 内容 } // 发送邮件 const transporter = nodemailer.createTransport(params) transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log('Message %s sent: %s', info.messageId, info.response); // success // ... })
按照这个格式,发送成功是没什么问题的。不过在密码这里要注意,不是邮箱的登陆密码。npm
163邮箱的话,要开启POP3/SMTP服务,在设置 --> POP3/SMTP/IMAP页面,设置。开通后会有个受权码的,配置里的密码,就是用这个受权码api
qq邮箱的话,一样也要开启这个服务,设置 --> 帐户 --> POP3服务,点击开启,就会有个受权码,若是忘了记录,在开启服务下面有个“生成受权码”的,能够获取到的。安全
这样qq和163就能开启了服务器
若是是Gmail的话,这个就有点麻烦了,在nodemailer官网也有说到:app
Gmail either works well or it does not work at all. It is probably easier to switch to an alternative service instead of fixing issues with Gmail. If Gmail does not work for you then don't use it.less
我这里用本身的谷歌邮箱试了下,在上面的配置修改一下
const params = { service: 'Gmail', // 注意,host修改成service port: 465, // 端口 sercure: true, // 是否使用TLS,true,端口为465,不然其余或者568 auth: { user: config.user, // 邮箱和密码 pass: config.emailPwd } }
若是这样不行的话,打开这个连接,开启谷歌容许不够安全应用
若是还不行的话,就要配置谷歌的XOAuth2了
就算使用了这种方法,也未必可能成功
在这里建立一个凭据,选择OAuth客户端ID,应用类型选择“网页应用”,而后填写名称,重定向URI要记得填写,我填写的是这个"https://developers.google.com/oauthplayground"
而后记录下id和密钥
填写以前的id和密钥
而后就是step1,选择api
到step2,点击'Exchange authorization code for tokens'按钮,生成token,这样就完成了。
回到nodejs,重写下配置
const params = { service: 'Gmail', auth: { type: 'OAuth2', user: config.user, clientId: config.clientId, clientSecret: config.clientSecret, refreshToken: config.refreshToken, accessToken: config.accessToken } }
我这里测试是成功的(本地服务器),若是还不成功的话,这个你只能在搜搜有什么解决方法了。
这里列出我本身用过的功能,nodemailer
看官方介绍,貌似是不少功能的
// 在配置发送信息的时候 const mailOptions = { from: config.user, // 发送邮箱 to: config.emailTo + ', ' + config.emailTo2 // 用', '分隔 }
const mailOptions = { .... html: config.html // 这里能够是html字符串 }
能够同时发送多个
const mailOptions = { ... attachments: [{ filename: 'test.txt', content: 'hello world!' },{ filename: 'test.txt', content: 'hello world!', contentType: 'text/plain' }] }
若是直接在图片上写上图片地址,在 qq 和谷歌邮箱都是无法直接显示的。qq 邮箱有一个查看图片的按钮,点击后才能显示。
若是使用附件的形式,是能够直接显示图片的。
// 伪代码 var img = require("fs").readFileSync('./images/1.jpeg') attachments: [ { filename: '1.jpeg', content: img, cid: '00000001' } ] html: `<img src='cid:00000001' />`
官方给出的配置
刚使用nodemailer
踩了很多坑,弄了我一天,Gmail
不怎么稳定,后面主管就叫换成qq
了,听说qq
企业邮箱发送邮件的次数比较多。这篇文章就是记录下使用nodemailer
的一些经验。