使用Resend.com发送个性化邮件异常:仅Player1收到邮件
解决Resend发送个性化邮件的问题
问题分析
当前代码串行调用两次resend.emails.send,但仅player1能收到邮件,大概率是第二个请求出现错误但未被精准捕获,导致无法得知具体失败原因;同时批量发送会暴露收件人隐私,不符合需求,因此需要保留单独发送的逻辑,同时优化请求处理和错误排查能力。
正确实现方式
通过Promise.all并行发送两个邮件请求,既能提升效率,又能分别追踪每个请求的结果(成功/失败),同时优化错误处理逻辑,避免单个请求失败导致整体结果被覆盖。
修改后的代码示例
import type { NextApiRequest, NextApiResponse } from "next"; import { EmailTemplate } from "../../components/emails/EmailTemplate"; import { Resend } from "resend"; import { supabase } from "../../../initSupabase"; const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_KEY); export default async (req: NextApiRequest, res: NextApiResponse) => { try { const { player1, player2, player1Email, player2Email } = req.body; // 并行发起两个邮件发送请求 const [player1Data, player2Data] = await Promise.all([ resend.emails.send({ from: "Acme <onboarding@resend.dev>", to: [player1Email], subject: "Hello player 1", react: EmailTemplate({ firstName: player1, secondName: player1Email }), }), resend.emails.send({ from: "Acme <onboarding@resend.dev>", to: [player2Email], subject: "Hello player 2", react: EmailTemplate({ firstName: player2, secondName: player2Email }), }), ]); // 单独检查每个请求的错误 const errors = []; if (player1Data.error) errors.push({ target: "player1", error: player1Data.error }); if (player2Data.error) errors.push({ target: "player2", error: player2Data.error }); if (errors.length > 0) { return res.status(400).json({ errors, player1Data, player2Data }); } res.status(200).json({ player1Data, player2Data }); } catch (error) { res.status(500).json({ generalError: error }); } };
关键优化点
- 并行发送:使用
Promise.all同时发起请求,避免串行等待可能引发的超时或未处理异常。 - 精准错误排查:分别校验每个请求返回结果中的
error字段,能明确定位哪一封邮件发送失败及具体原因(如API权限问题、邮箱格式错误、Resend发送限制等)。 - 隐私保护:保持单个请求单独指定收件人的逻辑,确保用户不会看到彼此的邮箱地址。
额外排查建议
- 查看Resend控制台的发送日志,直接获取第二个请求的状态和错误详情。
- 确认
player2Email格式完全正确,无空格或特殊字符。 - 验证
EmailTemplate接收player2变量时能正常渲染,避免模板报错导致发送失败。
内容的提问来源于stack exchange,提问作者a7dc
相关产品推荐
相关产品推荐

