# **163邮箱为例**
## 邮箱开通授权
![](https://img.kancloud.cn/9a/c2/9ac2ac0e72d90f5330483ddfb783ff5d_779x348.png)
## **后端**
### **依赖**
```
npm i nodemailer --save
```
### **创建发送邮件公共方法**
在util问价加下新增mail.js文件
```
const nodemailer = require("nodemailer"); //引入依赖
/**
* 发送邮件
* @param {string} to 收件方邮箱
* @param {string} title 内容标题
* @param {string} content 邮件内容
* @param {Function} callback 回调函数(内置参数)
*
*/
function mail(to, title, content, callback) {
/**
* 详细配置文件地址: node_modules/lib/well-known/services
*/
let transporter = nodemailer.createTransport({
host: "smtp.163.com",
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: "your-email@163.com", //发送方邮箱
pass: "123123", //发送方邮箱的授权码,一般去邮箱设置里面找,应该可以找到
},
});
let options = {
from: "your-email@163.com", //发送方邮箱
to: to,
subject: title,
text: content,
//html: '<h1>这里内容</h1>',text和html任选其一即可
};
//发送邮件
transporter.sendMail(options, (err, data) => {
callback &&
callback(err, data, () => {
transporter.close; //成功之后,关闭连接
});
});
}
module.exports = mail; //导出函数
```
### **创建路由**
routers文件夹中新增mailRouter.js文件
```
const express = require("express");
const router = express.Router();
const mail = require("../util/mail");
router.get("/getcode", (req, res) => {
const to = "to@163.com";
let code = Math.floor(Math.random() * 900000) + 100000; //随机生成 6位数的验证码
if (!req.session.mailCode) {
req.session.mailCode = {};
}
req.session.mailCode[to] = code;// 将指定邮箱的code记录到session中
mail(
to,
"欢迎使用",
"您的验证码为:" + code + ",请妥善保管!",
(err, data, successCallback) => {
if (err) {
res.json({ code: 0, msg: err });
} else {
res.json({ code: 200, msg: "验证码发送成功" });
successCallback();
}
}
);
});
module.exports = router;
```
### **app.js中导入**
```
const mailRouter = require("./routes/mailRouter");
app.use(mailRouter);
```
## **前端调用**
```
html
<el-button type="primary" size="default" @click="sendEmailCode">
给邮箱发送验证码
</el-button>
js
const sendEmailCode = () => {
axios.get("/api/getcode").then((res) => {
if (res.data.code === 200) {
ElMessage.success(res.data.msg);
} else {
ElMessage.error(res.data.msg);
}
});
};
```