我的博客原文:https://bxm0927.github.io/201...html
Nodemailer 是 Node.js 应用程序的一个模块,能够方便地发送电子邮件。node
该项目于 2010 年开始,至今已经至关稳定,这也是现在大多数 Node.js 用户默认状况下发送邮件的解决方案。git
# 初始化 pageage.json 文件 $ npm init # 安装依赖 $ npm install nodemailer --save # 运行 node app.js
app.jsgithub
const nodemailer = require('nodemailer'); // 开启一个 SMTP 链接池 let transporter = nodemailer.createTransport({ host: 'smtp.qq.com', secureConnection: true, // use SSL port: 465, secure: true, // secure:true for port 465, secure:false for port 587 auth: { user: '80583600@qq.com', pass: 'xxx' // QQ邮箱须要使用受权码 } }); // 设置邮件内容(谁发送什么给谁) let mailOptions = { from: '"白小明 ?" <80583600@qq.com>', // 发件人 to: 'xx1@qq.com, xx2@qq.com', // 收件人 subject: 'Hello ✔', // 主题 text: '这是一封来自 Node.js 的测试邮件', // plain text body html: '<b>这是一封来自 Node.js 的测试邮件</b>', // html body // 下面是发送附件,不须要就注释掉 attachments: [{ filename: 'test.md', path: './test.md' }, { filename: 'content', content: '发送内容' } ] }; // 使用先前建立的传输器的 sendMail 方法传递消息对象 transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log(`Message: ${info.messageId}`); console.log(`sent: ${info.response}`); });
效果预览npm
实践的时候遇到许多问题,如今列举以下,若未详尽,敬请留言交流。json
首先须要开启邮箱的 POP3/SMTP 服务。app
QQ邮箱须要使用受权码,而不是QQ密码;163 邮箱直接使用163邮箱密码就行。测试
进入QQ邮箱,设置-帐户-开启服务 POP3/SMTP 服务,并生成受权码,如今获取受权码须要验证手机短信。ui
理论上支持全部主流邮箱,但我只测试了 QQ 和 163,都成功了。若其余邮箱出问题请留言交流。spa
Error: Invalid login: 535 Error: authentication failed
认证失败:
多是帐号密码错误
连接资源池时加 ssl:secureConnection: true,
QQ 的 host 是 smtp.qq.com
;163 的 host 是 smtp.163.com
Error: Mail command failed: 553 Mail from must equal authorized user
发件人和认证的邮箱地址不一致
auth.user 须要与 from 中的邮箱一致