ส่งอีเมลจาก Node.js ได้ด้วย fetch ที่มีมาในตัว ไม่ต้องติดตั้งไลบรารีเพิ่ม ปัญหาส่วนใหญ่มาทีหลัง คือตอนเครือข่ายสะดุดแล้ว retry จนลูกค้าได้อีเมลสองฉบับ หรือ error แล้วเงียบจนอีเมลหาย
เตรียมก่อนเริ่ม
- ยืนยันโดเมนที่จะใช้เป็นผู้ส่งใน Dashboard
- สร้าง API key แล้วเก็บเป็น environment variable ชื่อ BYTESMS_API_KEY
- ห้ามใส่ API key ในโค้ดฝั่งเบราว์เซอร์ ต้องเรียกจากฝั่งเซิร์ฟเวอร์เท่านั้น
ส่งอีเมลฉบับแรก
const res = await fetch("https://api.bytesms.com/api/v1/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Your Shop <[email protected]>",
to: ["[email protected]"],
subject: "ยืนยันคำสั่งซื้อ #1024",
html: "<p>ขอบคุณที่สั่งซื้อกับเรา</p>",
}),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.name}: ${data.message}`);
console.log(data.id); // เก็บ id ไว้คู่กับคำสั่งซื้อ
ถ้าให้แค่ html ระบบสร้างส่วน text/plain ให้อัตโนมัติ ซึ่งช่วยเรื่องการเข้ากล่องจดหมาย
Retry อย่างปลอดภัยด้วย Idempotency-Key
ถ้าเครือข่ายหลุดหลังส่งคำขอ คุณจะไม่รู้ว่าอีเมลถูกรับไปแล้วหรือยัง ใส่ header Idempotency-Key ที่ผูกกับเหตุการณ์นั้น เช่น order-1024-confirmation แล้ว retry ด้วย key เดิม ระบบจะรับอีเมลแค่ครั้งเดียวและตอบ id เดิมทุกครั้ง key จำไว้ 24 ชั่วโมง
async function sendOnce(payload, key, attempts = 3) {
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch("https://api.bytesms.com/api/v1/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(payload),
});
if (res.status === 429 || res.status >= 500) {
const wait = Number(res.headers.get("retry-after") ?? 2 ** i);
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
return await res.json();
} catch {
await new Promise((r) => setTimeout(r, 2 ** i * 1000));
}
}
throw new Error("send failed after retries");
}
Next.js: ส่งจาก Route Handler
// app/api/contact/route.ts
export async function POST(req: Request) {
const { email, message } = await req.json();
const res = await fetch("https://api.bytesms.com/api/v1/emails", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.BYTESMS_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
from: "Website <[email protected]>",
to: ["[email protected]"],
reply_to: email,
subject: "ข้อความใหม่จากหน้าเว็บ",
text: message,
}),
});
return Response.json(await res.json(), { status: res.status });
}
Error ที่ควรจัดการ
| สถานะ | name | ความหมาย |
|---|---|---|
| 401 | unauthorized | API key ผิดหรือหมดอายุ |
| 403 | invalid_from_address | From ไม่ได้อยู่บนโดเมนที่ยืนยันแล้ว |
| 409 | idempotency_key_conflict | ใช้ key เดิมกับเนื้อหาอื่น ให้ใช้ key ใหม่ |
| 422 | validation_error | ข้อมูลไม่ครบหรือรูปแบบผิด ดูรายละเอียดใน message |
| 429 | rate_limit_exceeded | ส่งเร็วเกินไป รอตาม retry-after |
| 429 | daily_quota_exceeded | ใช้โควตารายวันของแพ็กเกจหมดแล้ว |
ให้ตัดสินจาก name และสถานะ ไม่ใช่ข้อความใน message ซึ่งอาจเปลี่ยนได้ ถ้าต้องส่งหลายฉบับพร้อมกัน ใช้ POST /api/v1/emails/batch ส่งได้ครั้งละ 100 ฉบับ



