我用nodejs给朋友发送了一封邮件
配置 node
- 需要电脑上有node.js(官网下载即可)
- 需要用到nodemailer
// 1. 配置环境
npm init
npm install nodemailer --save
写代码
// 引入nodemailer模块
const nodemailer = require('nodemailer');
// 开启一个 SMTP 连接池
let transporter = nodemailer.createTransport({
host: 'smtp.qq.com', //qq的host
secureConnection: true, // use SSL
port: 465,
secure: true, // secure:true for port 465, secure:false for port 587
auth: {
user: 'xxx@qq.com',
pass: 'xxxxxxxxxx' // QQ邮箱需要使用授权码
}
});
// 设置邮件内容(谁发送什么给谁)
let mailOptions = {
from: '"xxx" <xxx@qq.com>', // 发件人
to: 'xxxx@qq.com', // 收件人
subject: '测试邮件', // 主题
text: '这是一封来自 Node.js 的测试邮件', // plain text body
html: '<b>这是一封来自 Node.js 的测试邮件</b>', // html body
};
// 使用先前创建的传输器的 sendMail 方法传递消息对象
transporter.sendMail(mailOptions, (error, info) => {
// 发送失败
if (error) {
return console.log(error);
}
// 发送成功
console.log(`Message: ${info.messageId}`);
console.log(`sent: ${info.response}`);
});
成功后终端显示的内容
朋友收到的邮件: