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

NextJS 13实验性appDir中配置SendGrid邮件服务求助

NextJS 13 App Router 配置 SendGrid 邮件发送解决方案

1. 确认依赖与环境变量

确保已安装最新版 SendGrid SDK:

npm install @sendgrid/mail
# 或
yarn add @sendgrid/mail

在项目根目录的 .env.local 中配置 SendGrid 密钥与发件邮箱(不要给 API 密钥加 NEXT_PUBLIC_ 前缀,防止暴露在客户端):

SENDGRID_API_KEY=your_sendgrid_api_key_here
SENDGRID_FROM_EMAIL=your_verified_from_email@example.com

2. 创建 App Router 风格的 API 路由

在 app/api/sendmail 目录下新建 route.ts 文件(App Router 用 route.ts 定义 API 路由,替代旧版 pages/api 下的独立文件):

import sgMail from '@sendgrid/mail';
import { NextResponse } from 'next/server';

// 初始化 SendGrid
sgMail.setApiKey(process.env.SENDGRID_API_KEY || '');

export async function POST(request: Request) {
  try {
    const { to, subject, text, html } = await request.json();

    // 参数校验
    if (!to || !subject || (!text && !html)) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    const msg = {
      to,
      from: process.env.SENDGRID_FROM_EMAIL || '',
      subject,
      text,
      html,
    };

    await sgMail.send(msg);
    return NextResponse.json({ success: true }, { status: 200 });
  } catch (error: any) {
    console.error('邮件发送失败:', error);
    return NextResponse.json(
      { error: error.response?.body || '发送失败' },
      { status: error.statusCode || 500 }
    );
  }
}

3. 前端调用该 API

在组件的表单提交或触发逻辑中,通过 fetch 请求这个 API:

async function sendEmail() {
  try {
    const response = await fetch('/api/sendmail', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        to: 'recipient@example.com',
        subject: '测试邮件',
        text: '这是一封来自 NextJS 13 App Router 的测试邮件',
        html: '<strong>这是一封来自 NextJS 13 App Router 的测试邮件</strong>',
      }),
    });

    const result = await response.json();
    if (response.ok) {
      console.log('邮件发送成功:', result);
      // 这里添加成功提示逻辑
    } else {
      console.error('邮件发送失败:', result.error);
      // 这里添加错误提示逻辑
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
}

常见问题排查

  • 环境变量未生效:重启开发服务器,确保 .env.local 放在项目根目录。
  • 权限问题:确认 SendGrid API 密钥拥有邮件发送权限,且发件邮箱已在 SendGrid 后台完成验证。
  • 参数格式错误:检查前端传递的 JSON 字段是否完整,避免遗漏 to、subject 等必填项。
  • CORS 问题:跨域请求需在 next.config.js 中配置 CORS 规则,同域请求无需额外设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 21:06:06