ทำไมที่นี่ใช้ REST แทน SMTP
การ deploy Next.js ส่วนใหญ่ทำงานบนฟังก์ชัน serverless หรือ edge ซึ่งการเชื่อมต่อ SMTP ขาออกที่ยาวนานไม่เสถียรหรือถูกบล็อกทั้งหมด การส่ง HTTPS POST ครั้งเดียวจาก Server Action เลี่ยงปัญหานี้ได้ทั้งหมด
Server Action สำหรับฟอร์มติดต่อ
// 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');
}
หรือ Route Handler หากอยากเรียกจากฝั่งไคลเอนต์
// 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 });
}
เรนเดอร์ด้วย React Email
สำหรับเนื้อหาที่มากกว่าข้อความธรรมดา ให้เรนเดอร์คอมโพเนนต์ React Email เป็น HTML ด้วย @react-email/render แล้วส่งผลลัพธ์เป็น html ใน body คำขอ เทมเพลตจะยังเป็นคอมโพเนนต์แทนการต่อสตริง
เช็กลิสต์
- เก็บ
SENDCOREX_API_KEYไว้ฝั่งเซิร์ฟเวอร์เท่านั้น อย่าเปิดเผยผ่านNEXT_PUBLIC_ - ตั้ง
replyToเป็นที่อยู่ของผู้เยี่ยมชม และใช้fromบนโดเมนที่ยืนยันแล้ว - จำกัดอัตราการเรียก route ไม่อย่างนั้นบอตจะใช้ฟอร์มส่งข้อความหาคุณเป็นพันๆ ฉบับ