Vercel部署的Next.js项目使用Resend无法收邮件的解决方法
解决Next.js+Resend部署到Vercel后邮件不发送的问题
核心问题分析
你的代码存在两个关键问题,直接导致了部署到Vercel后的异常:
- 未等待异步操作完成:
resend.emails.send()是异步函数,你直接调用却没加await,导致API路由提前返回200成功响应,但邮件发送的Promise还没执行完就被Vercel的无服务器函数终止了,既不会生成Resend日志,也无法捕获发送错误。 - 无效的错误判断:
if (!resend)这段逻辑完全没用,resend是已经初始化好的实例,永远不会为假,根本检测不到发送失败的情况。
修复步骤及代码修改
1. 修复异步调用逻辑
给resend.emails.send()加上await,确保等待邮件发送完成后再返回响应,这样才能正确捕获发送过程中的成功或失败状态。
2. 移除无效判断
删掉if (!resend)这段毫无意义的代码,换成基于Resend返回结果的错误判断。
3. 验证Vercel环境变量
登录Vercel控制台,进入你的项目,在Settings > Environment Variables中确认RESEND_API_KEY已正确配置,并且勾选了Production环境(或同时勾选Production和Preview)。
修复后的完整代码
import { NextApiRequest, NextApiResponse } from 'next'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== 'POST') { return res.status(405).json({ message: 'Method Not Allowed' }); } try { const formData = req.body; console.log('Received form data:', formData); // 关键:添加await等待邮件发送完成 const response = await resend.emails.send({ from: 'dws@resend.dev', to: 'myemail@gmail.com', subject: 'New Contact Form Message', html: `<p>This is an Email to DWS from Contact Form. the name of the person is: ${formData.name}, the referrer is ${formData.referrer}, and the email is ${formData.email}. The message is: (${formData.message})</p>` }); // 根据Resend返回结果判断是否发送成功 if (response.error) { console.error('Resend API error:', response.error); return res.status(500).json({ message: 'Failed to send email' }); } console.log('Message sent successfully:', response); return res.status(200).json({ success: true }); } catch (error) { console.error('Error sending message:', error); return res.status(500).json({ message: 'Internal Server Error' }); } }
额外排查点
- 查看Vercel函数实时日志:进入Vercel控制台的Functions页面,找到对应的API路由,查看请求时的日志输出,确认是否有未捕获的错误信息。
- 验证Resend发件邮箱:如果后续仍有问题,确认
dws@resend.dev是否已在Resend控制台完成验证(测试邮箱可能无需验证,生产环境建议使用自己域名下的已验证邮箱)。
内容的提问来源于stack exchange,提问作者Burner
相关产品推荐
相关产品推荐

