Sendcorex
Bài thực hành

Gửi email từ Next.js (App Router và Route Handler)

Cách của App Router: Server Action gọi trực tiếp REST API, không cần client SMTP.

Bởi đội ngũ Sendcorex·Cập nhật 21 thg 9, 2026·8 phút đọc

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_KEY chỉ ở server — không bao giờ để lộ qua NEXT_PUBLIC_.
  • Đặt replyTo là địa chỉ của khách truy cập; giữ from trê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.

Gửi email đầu tiên trong vài phút

Tạo tài khoản miễn phí, xác minh tên miền và dán code ở trên.

Không cần thẻ tín dụng