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. 其他邮件服务
如果使用 SendGrid 或 SMTP,可以修改 nodemailer.createTransport()
的配置以适配不同的邮件服务提供商。