前置条件
-
两个邮箱
-
发送邮件的邮箱要开通SMTP服务
- 手机邮件应用配置过邮箱或者电脑电脑应用配置过邮箱->应该配置过SMTP服务(客户端软件需要权限才可以使用邮箱功能)
- 例如:qq邮箱左上角设置 - > 账号 - > 开通下方服务 - > 拿到授权码
-
然后创建一个文件夹
- 文件夹里创建一个email.js
- 终端执行
- npm init -y
- npm i nodemailer
引入第三方模块
- NODEMAILER
- 功能挺多的,自己有兴趣可以都玩下
用法
消息配置
- 消息配置
- 大部分电子邮件看起来很像,仅使用几个基本字段
var message = { from: "[email protected]", to: "[email protected]", subject: "Message title", text: "Plaintext version of the message", html: "<p>HTML version of the message</p>" };
SMTP传输-配置运输对象
- SMTP传输
- transport是传输配置对象
let options={ service: "QQ",//根据发件箱选择 host: "smtp.qq.com",//根据发件箱选择 auth: { user: "[email protected]",//发件箱 pass: "xxxxx",//发件箱的授权码,不是邮箱密码 }, }; let transporter = nodemailer.createTransport(options[, defaults])
- options –是定义连接数据的对象(有关详细信息,请参见下文)
- defaults–是将要合并到每个消息对象中的对象。这使您可以指定共享选项,例如为每条消息从地址设置相同的选项
- 常规选项
- port – is the port to connect to (defaults to 587 if is secure is false or 465 if true)
- host – is the hostname or IP address to connect to (defaults to ‘localhost’)
- auth(定义认证数据) – defines authentication data (see authentication section below)
- auth is the authentication object(身份验证对象)
- type indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’
- user is the username(用户名)
- pass is the password for the user if normal login is used(上文提到的授权码,不是邮箱密码)
- auth is the authentication object(身份验证对象)
- authMethod – defines preferred authentication method, defaults to ‘PLAIN’
发送邮件
- 一旦有了运输对象,就可以随其发送邮件
transporter.sendMail(data[, callback])
- 数据定义了邮件内容(请参阅消息配置 以获取可能的选项)
- 回调是可选的回调函数,可在传递消息或消息失败后运行
- 如果消息失败,则err为错误对象
- 信息包括结果,确切的格式取决于所使用的传输机制
- info.messageId大多数传输应返回与此属性一起使用的最终Message-Id值
- info.envelope包含邮件的信封对象
- info.accepted是SMTP传输返回的数组(包括服务器接受的收件人地址)
- info.rejected是SMTP传输返回的数组(包括服务器拒绝的收件人地址)
- info.pending是直接SMTP传输返回的数组。包括与服务器响应一起被暂时拒绝的收件人地址
- 响应是SMTP传输返回的字符串,包括来自服务器的最后一个SMTP响应
最终代码
- 终端运行 node email.js
var nodemailer = require("nodemailer");
//消息配置
var mailOptions = {
from: "[email protected]",//发件箱
to: "[email protected]",//收件箱
subject: "测试node发送邮件",
text: "Plaintext version of the message",
html: "<p>HTML version of the message</p>",
};
//SMTP传输-配置运输对象
var transporter = nodemailer.createTransport({
service: "QQ",//根据发件箱选择
host: "smtp.qq.com",//根据发件箱选择
auth: {
user: "[email protected]",//发件箱
pass: "xxxxx",//发件箱的授权码,不是邮箱密码
},
});
//发送邮件
transporter.sendMail(mailOptions, function (error, info) {
console.log("发送中...", info);
if (error) {
console.log("发送失败", error);
throw error;
}
console.log("发送成功", info.response);
});