Next.js 发送邮件 API

1. 安装 Nodemailer

运行以下命令安装 Nodemailer 依赖:

npm install nodemailer

2. 创建 API 路由

app/api/send-email/route.ts 中添加以下代码:

import { NextResponse } from "next/server";
import nodemailer from "nodemailer";

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

    if (!to || !subject || (!text && !html)) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    // 配置邮件发送服务(Gmail 示例)
    const transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: process.env.EMAIL_USER, // 你的 Gmail 地址
        pass: process.env.EMAIL_PASS, // 你的 Gmail 应用专用密码
      },
    });

    // 发送邮件
    const info = await transporter.sendMail({
      from: `"Your Name" <${process.env.EMAIL_USER}>`,
      to,
      subject,
      text,
      html,
    });

    return NextResponse.json({ message: "Email sent successfully", info }, { status: 200 });
  } catch (error) {
    console.error("Email sending error:", error);
    return NextResponse.json({ error: "Failed to send email" }, { status: 500 });
  }
}

3. 配置环境变量

.env.local 文件中添加:

EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password

⚠️ 注意:Gmail 需要使用应用专用密码进行身份验证。

4. 发送邮件请求(前端示例)

async function sendEmail() {
  const response = await fetch("/api/send-email", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      to: "recipient@example.com",
      subject: "Test Email",
      text: "Hello, this is a test email!",
    }),
  });

  const data = await response.json();
  console.log(data);
}

5. 其他邮件服务

如果使用 SendGridSMTP,可以修改 nodemailer.createTransport() 的配置以适配不同的邮件服务提供商。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值