You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据请求类型选择并发送对应邮件模板?

解决方案

核心思路

用配置映射对象将请求类型(type)与对应的EJS模板路径、邮件主题等关联,既清晰又方便后续扩展新的邮件类型。同时增加参数校验,避免非法类型导致的错误。

完善后的mailer函数代码

const transporter = require("./transporter");
const ejs = require('ejs');
const path = require('path');

// 建立type与模板、主题的映射配置
const templateMap = {
  reset_password: {
    templatePath: path.join(__dirname, "../reset_password.ejs"),
    subject: "密码重置通知",
    plainText: "请点击邮件中的链接重置您的密码"
  },
  signup: {
    templatePath: path.join(__dirname, "../signup.ejs"),
    subject: "欢迎注册",
    plainText: "感谢您的注册,欢迎加入我们"
  }
};

const mailer = async (type, to) => {
  // 校验type是否合法
  if (!templateMap[type]) {
    throw new Error(`不支持的邮件类型:${type}`);
  }

  const { templatePath, subject, plainText } = templateMap[type];
  
  // 渲染对应EJS模板
  const htmlContent = await ejs.renderFile(templatePath, { to });

  const mailOptions = {
    from: '你的邮箱 <your-email@example.com>', // 建议替换为真实发件人格式
    to: to,
    text: plainText,
    subject: subject,
    html: htmlContent
  };

  return transporter.sendMail(mailOptions);
};

module.exports = mailer;

路由层调用示例(以Express为例)

const express = require('express');
const mailer = require('./path/to/mailer');
const app = express();

app.get('/sendmail', async (req, res) => {
  const { apiKey, type, to } = req.query;

  // 校验API密钥
  if (apiKey !== 'test') {
    return res.status(403).send('无效的API密钥');
  }

  // 校验必填参数
  if (!type || !to) {
    return res.status(400).send('缺少必要参数:type或to');
  }

  try {
    await mailer(type, to);
    res.status(200).send('邮件发送成功');
  } catch (err) {
    res.status(500).send(`邮件发送失败:${err.message}`);
  }
});

app.listen(3000, () => {
  console.log('服务运行在http://localhost:3000');
});

关键说明

  1. 映射配置:templateMap集中管理所有邮件类型的资源,新增类型只需在对象中添加对应项,无需修改核心逻辑。
  2. 参数校验:提前判断type是否在映射范围内,避免渲染不存在的模板文件。
  3. 模板渲染:ejs.renderFile仅需传入对应模板路径和渲染数据(这里是收件人to),无需同时传入多个模板路径。
  4. 邮件内容优化:为不同类型的邮件设置对应的纯文本内容和主题,提升用户体验。

内容的提问来源于stack exchange,提问作者amedio3999

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:09:21