Nhận OTP tự động bằng Node.js với Mailtr API
Bài này dùng Node.js (fetch sẵn có từ Node 18+) để tạo inbox tạm qua Mailtr API và lấy mã OTP tự trích. Đây là bản đối xứng với bài Python, dành cho hệ JavaScript.
Chuẩn bị
Đặt API key vào biến môi trường (lấy trong Tài khoản → API):
export MAILTR_KEY="mk_xxxxxxxxxxxxxxxx" Script lấy OTP
Tạo inbox, dùng địa chỉ để đăng ký dịch vụ cần test, rồi poll tới khi có OTP:
const BASE = "https://mailtr.vn";
const H = { "X-API-Key": process.env.MAILTR_KEY, "content-type": "application/json" };
async function createInbox() {
const r = await fetch(BASE + "/api/v1/inbox", { method: "POST", headers: H, body: "{}" });
return r.json(); // { id, address }
}
async function waitForOtp(inboxId, timeoutMs = 60000) {
const end = Date.now() + timeoutMs;
const seen = new Set();
while (Date.now() < end) {
const list = await (await fetch(BASE + "/api/v1/inbox/" + inboxId + "/messages", { headers: H })).json();
for (const m of list.messages || []) {
if (seen.has(m.id)) continue;
seen.add(m.id);
const full = await (await fetch(BASE + "/api/v1/messages/" + m.id, { headers: H })).json();
if (full.message && full.message.otp) return full.message.otp;
}
await new Promise((r) => setTimeout(r, 3000));
}
throw new Error("Het thoi gian cho OTP");
}
const inbox = await createInbox();
console.log("Inbox:", inbox.address);
console.log("OTP:", await waitForOtp(inbox.id)); Mẹo
Cần realtime thay vì poll? Dùng webhook (xem bài kiến trúc webhook). Chạy nhiều luồng song song thì chú ý quota và rate limit của gói.