Vì sao ở đây dùng REST thay cho SMTP
Phần lớn bản triển khai Next.js chạy trên hàm serverless hoặc edge, nơi kết nối SMTP gửi ra kéo dài không ổn định hoặc bị chặn hẳn. Một lệnh HTTPS POST duy nhất từ Server Action tránh được hoàn toàn vấn đề này.
Server Action cho form liên hệ
// app/actions.ts
'use server';
export async function sendContactMessage(formData: FormData) {
const email = formData.get('email') as string;
const message = formData.get('message') as string;
const res = await fetch('https://graph.sendcorex.com/v3.0/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SENDCOREX_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: 'you@yourdomain.com',
from: 'hello@yourdomain.com',
replyTo: email,
subject: 'New contact message',
text: message,
}),
});
if (!res.ok) throw new Error('Could not send message');
}
Hoặc Route Handler, nếu bạn muốn gọi từ client
// app/api/contact/route.ts
export async function POST(request: Request) {
const { email, message } = await request.json();
const res = await fetch('https://graph.sendcorex.com/v3.0/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.SENDCOREX_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ to: 'you@yourdomain.com', from: 'hello@yourdomain.com', replyTo: email, subject: 'New contact message', text: message }),
});
return Response.json({ ok: res.ok }, { status: res.ok ? 200 : 502 });
}
Render bằng React Email
Với nội dung phong phú hơn một chuỗi thuần, render component React Email sang HTML bằng @react-email/render rồi truyền kết quả làm html trong body request — giữ template dưới dạng component thay vì nối chuỗi.
Checklist
- Giữ
SENDCOREX_API_KEYchỉ ở server — không bao giờ để lộ quaNEXT_PUBLIC_. - Đặt
replyTolà địa chỉ của khách truy cập; giữfromtrên tên miền đã xác minh. - Giới hạn tần suất cho route, nếu không bot sẽ dùng form của bạn để gửi cho bạn hàng nghìn tin nhắn.