Node + Express + nodemailer实现发送邮件功能

2024-08-03 11:12:10 | 后端Number of visitors 366

1、安装nodemailer依赖

npm install nodemailer

2、路由文件中引入

// index.js
var express = require("express");
const nodemailder = require("nodemailer");
var router = express.Router();
const config = require("../config/config");

// 创建实例
const transPort = nodemailder.createTransport({
	service: "qq", // 使用内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/
	host: "smtp.qq.com",
	port: 456, // SMTP 端口
	secure: true, // 安全方式发送, 建议加上
	auth: {
		pass: config.mailConfig.pass, // 发送邮件的授权码, 需要去QQ邮箱开启SMTP服务获取
		user: config.mailConfig.user, //发送邮件的qq邮箱
	},
});

// 测试路由
router.post("/sendEmail", function (req, res, next) {
    const sendConfig = {
		to: '2xxxx@qq.com', // 接收邮件的邮箱
		from: config.mailConfig.user, // 发送邮件的邮箱
		subject: "新的消息", // 标题
		html: "<h1>你有一个新的消息待查看!!!</h1>", //内容, 字段可以是text, 纯文本
	};
	transPort.sendMail(sendConfig, (error, result) => {
	    if(!error){
	        res.json({
	            code: 200,
	            msg: '发送成功',
	            data: null
	        })
	    }	
	});
})

3、如何在QQ邮箱中开启SMTP服务

1、登录QQ邮箱


2、右上角点击账号与安全


3、安全设置中找到 — POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务栏,,选择IMAP/SMTP服务开启选项,记得记录你的授权码,填入pass中

4、config中的配置

// config.js
module.exports = {
	mailConfig: {
		pass: "xxxxxxx", // QQ邮箱中SMTP服务生成的授权码
		user: "2xxxxx2@qq.com",
	},
};










send发送