สรุปสั้นๆ: หากต้องการส่งอีเมลด้วย REST API ใน Node.js ให้ส่งคำขอ POST ด้วย fetch (มีในตัวตั้งแต่ Node 18) ไปยัง endpoint ส่งของผู้ให้บริการ ใส่ API key ใน header Authorization และ body JSON ที่มี from, to, subject และ html ไม่ต้องใช้ SDK ดูโค้ดเต็มในตัวเลือกที่ 2
มีสองวิธีที่ดีในการส่งอีเมลจาก Node.js: ผ่าน SMTP ด้วย Nodemailer หรือการเรียก fetch ธรรมดาไปยัง REST API ใช้ Node.js 18 ขึ้นไปก็พอสำหรับทั้งสองแบบ คุณยังต้องมีบัญชี Sendcorex และโดเมนส่งที่ยืนยันแล้ว (เผยแพร่ระเบียน SPF, DKIM และ DMARC ที่แดชบอร์ดให้ไว้ก่อนส่งจริง)
ตัวเลือกที่ 1: Nodemailer (SMTP)
npm install nodemailer
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: 'smtp.sendcorex.com',
port: 587,
secure: false, // STARTTLS on 587
auth: { user: process.env.SENDCOREX_API_KEY, pass: process.env.SENDCOREX_API_KEY },
});
const info = await transporter.sendMail({
from: '"Your App" <hello@yourdomain.com>',
to: 'customer@example.com',
subject: 'Welcome!',
text: 'You are in.',
html: '<h1>You are in.</h1>',
});
console.log('Sent:', info.messageId);
ตัวเลือกที่ 2: REST API ด้วย fetch
ไม่มี dependency ใช้ได้ในรันไทม์ serverless และ edge ที่มักบล็อก SMTP ขาออก:
const response = 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: 'customer@example.com',
from: 'hello@yourdomain.com',
subject: 'Welcome!',
html: '<h1>You are in.</h1>',
}),
});
if (!response.ok) throw new Error(`Send failed: ${response.status}`);
ข้อผิดพลาดและการลองใหม่
| อาการ | วิธีแก้ |
|---|---|
Invalid login | ไม่มี API key หรือผิด ตรวจว่าตัวแปรสภาพแวดล้อมถูกโหลดและไม่มีช่องว่างเกิน |
ETIMEDOUT | โฮสต์บล็อกพอร์ต SMTP ลอง 587/465 หรือเปลี่ยนไปใช้ REST API |
| เข้าสแปม | ตรวจ SPF/DKIM ใน header ของ Gmail จริง ส่งทั้ง text และ html และเพิ่มปริมาณทีละน้อย |
การตอบกลับ 4xx หมายถึงคำขอผิด อย่าลองใหม่ 429 และ 5xx เป็นแบบชั่วคราว ลองใหม่ด้วย exponential backoff