这里以QQ邮箱为例,网易邮箱类似.
设置->账号



- const express = require('express')
- const router = require('./router');
- const app = express()
-
- // 使用路由文件
- app.use('/',router);
-
- app.listen(3000, () => {
- console.log('server running ...');
- })
- const express = require('express');
- const router = express.Router();
- const {createSixNum,send}=require('./utils')
-
- //发送邮件
- router.get('/getemail', async (req, res) => {
- try {
- const { mail } = req.query; //获取前端传过来的邮箱
-
- let code = createSixNum(); // 随机生成6位验证码
-
- send(mail, code) //发送邮件的函数,传入邮箱和6位验证码
- .then(() => {
- res.json({ msg: '验证码发送成功' });
- })
- .catch((err) => {
- console.error(err);
- res.json({ msg: '验证码发送失败' });
- });
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: '邮件发送失败' });
- }
- });
安装nodemailer
npm i nodemailer
- const nodemailer = require('nodemailer')
-
- // 随机产生六位验证码
- function createSixNum() {
- let Num = "";
- for (var i = 0; i < 6; i++) {
- Num += Math.floor(Math.random() * 10);
- }
- return Num;
- }
-
- // 创建一个SMTP客户端对象
- let transporter = nodemailer.createTransport({
- host: "smtp.qq.com", // 发送方邮箱 qq 通过lib/wel-konw
- port: 465,
- secure: true, // true for 465, false for other ports
- auth: {
- user: '2580578725@qq.com', // 发送方邮箱地址
- pass:***** // mtp 验证码 这个有了才可以发送邮件,可以qq邮箱去查看自己的码
- }
- })
-
-
- //发送邮件
- function send(mail,code) {
- const mailContent = `
-
尊敬的用户:
-
您好!
-
***为您提供了以下验证码,用于完成您的操作:
-
${code}
-
请注意,此验证码的有效期为5分钟。
-
感谢您的使用和支持!
-
祝您一天愉快!
- `;
- // 邮件信息
- let mailobj = {
- from: '<2580578725@qq.com>', // 发送方地址自定义
- to: mail, // 接收方地址
- subject: "注册验证码", // 主题内容
- html: mailContent // 使用html属性设置HTML内容
- }
- return new Promise((reslove, reject) => {
- // 发送邮件
- transporter.sendMail(mailobj, (err, data) => {
- if (err) {
- reject()
- } else {
- reslove()
- }
- })
- })
- }
-
- module.exports = { createSixNum ,send}
至此发送邮件的后端核心就完成了,接下来我们要将验证码缓存5分钟,给用户进行操作,过了5分钟,验证码会自动失效.
安装node-cache
npm i node-cache
- ...
- const NodeCache = require("node-cache");
- const myCache = new NodeCache();
-
- ...
- let code = createSixNum(); // 随机验证码
-
- // 将code存入缓存
- myCache.set("code", code, 300); // 缓存5分钟
-
- send(mail, code) //发送邮件的函数,传入邮箱和6位验证码
- .then(() => {
- res.json({ msg: '验证码发送成功' });
- })
- .catch((err) => {
- console.error(err);
- res.json({ msg: '验证码发送失败' });
- });
-
-
-
至此后端的服务搭建完毕,我们可以配合登录或者注册来使用.假如是邮箱验证注册,我们在验证码缓存的时候,可以在注册的接口中获取验证码
myCache.get("code");
来与前端传过来的验证码进行比对,完成注册.如果比对成功可以用
myCache.del("code");
清空缓存,优化性能.
后面我会出一期完整的邮箱验证注册和登录模块.包括密码加密,JWT生成token,用户信息存储到数据库,Cookie实现无感登录和时效性.
由于是从项目中扣出来的,这里的axios请求我进行了封装,单个请求封装就有些多余.大家可以改改,能够将邮箱发过去就好了
- import axios from "axios";
-
- const http = axios.create({
- baseURL: 'http://127.0.0.1:3000', // 注意这里的双斜杠
- timeout: 5000
- });
-
- // 请求拦截器
- http.interceptors.request.use(config => {
- return config;
- }, error => {
- return Promise.reject(error);
- });
-
- // 响应拦截器
- http.interceptors.response.use(response => {
- return response.data;
- }, error => {
- return Promise.reject(error);
- });
-
- export default http;
- import http from '@/utils/http';
- //email
- export async function getEmailAPI(mail) {
-
- const response = await http({
- url: 'getemail',
- method:'get',
- params: {mail}
- });
-
- return response; // 返回响应数据
-
- }
这里我传的是params参数,如果你是axios.get('..',mail)... 后端记得修改为req.body
- import {getEmailAPI} from './api'
- //邮件
- function sendemail(){
- //邮件正则
- const qqEmailRegex = /^[1-9]\d{4,10}@qq\.com$/;
- if (qqEmailRegex.test(email.value)) {
- getEmailAPI(email.value) //email.value input的值
- .then(response=>{
- console.log(response)
- })
- .catch(error=>{
- console.log(error)
- })
- } else {
- console.log('邮件格式不正确')
- }
-
- }
后续再加上冷却,多长时间才可以发下一封.以及进行下面的操作.
如果有不对或者优化的地方可以指正,如果使用时出现了问题,可以留言评论,大家一起解决!