Express REST API多类型邮件请求接收与处理问题
解决Express中基于Query参数的多类型邮件发送问题
1. Query参数传递方式
每个邮件类型对应单独请求,直接在URL后拼接type参数即可,示例:
- 重置密码:
GET /api/send-email?type=reset_password - 注册验证:
GET /api/send-email?type=signup_auth - 登录验证:
GET /api/send-email?type=sign_in_auth
若需传递邮箱、验证码、重置链接等额外数据,直接追加Query参数:GET /api/send-email?type=reset_password&email=user@example.com&resetUrl=https://your-domain.com/reset
2. Express中接收并处理type参数
通过req.query.type获取参数值,建议用映射对象替代if-else判断,提升代码可维护性:
const express = require('express'); const router = express.Router(); const nodemailer = require('nodemailer'); const ejs = require('ejs'); const path = require('path'); // 初始化邮件发送器(自行修改服务商及认证信息) const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'your-app-email@example.com', pass: 'your-app-specific-password' } }); // 邮件类型与模板、主题的映射配置 const emailConfigMap = { reset_password: { template: 'reset-password.ejs', subject: '重置你的账户密码' }, signup_auth: { template: 'signup-auth.ejs', subject: '验证你的注册账户' }, sign_in_auth: { template: 'signin-auth.ejs', subject: '你的登录验证码' } };
3. EJS模板渲染与内容填充
先在Express主文件中配置视图引擎及模板路径:
// app.js 中添加配置 app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views/emails')); // 模板统一放在views/emails目录下
然后在路由中完成模板渲染与邮件发送:
router.get('/send-email', async (req, res) => { const { type, email, code, resetUrl } = req.query; // 参数合法性校验 if (!type || !emailConfigMap[type]) { return res.status(400).json({ error: '无效的邮件类型' }); } if (!email) { return res.status(400).json({ error: '缺少收件人邮箱' }); } const { template, subject } = emailConfigMap[type]; try { // 渲染EJS模板,传入动态数据 const emailHtml = await ejs.renderFile( path.join(__dirname, 'views/emails', template), { resetUrl, verificationCode: code, userName: email.split('@')[0] // 示例:从邮箱提取用户名 } ); // 发送邮件 await transporter.sendMail({ from: '你的应用 <your-app-email@example.com>', to: email, subject, html: emailHtml }); res.status(200).json({ success: true, message: '邮件发送成功' }); } catch (err) { console.error(err); res.status(500).json({ error: '邮件发送失败' }); } });
4. EJS模板示例(以重置密码为例)
views/emails/reset-password.ejs:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>重置密码</title> </head> <body> <h3>你好 <%= userName %>,</h3> <p>点击下方链接重置你的密码,链接24小时内有效:</p> <a href="<%= resetUrl %>" style="padding: 8px 16px; background: #2563eb; color: white; text-decoration: none;">立即重置密码</a> <p>如果不是你发起的操作,请忽略此邮件。</p> </body> </html>
关键注意事项
- 必须校验
type参数合法性,避免非法值导致模板查找失败 - 动态数据(如验证码、重置链接)需从Query参数中传递,确保模板能获取对应变量
- 邮件发送为异步操作,需用
async/await或Promise处理,避免回调地狱 - 建议将邮件模板集中存放,便于后续维护和修改
内容的提问来源于stack exchange,提问作者andy399
相关产品推荐
相关产品推荐

