|
| 1 | +import { MailtrapClient } from "mailtrap"; |
| 2 | + |
| 3 | +const TOKEN = "<YOUR-TOKEN-HERE>"; |
| 4 | +const ACCOUNT_ID = "<YOUR-ACCOUNT-ID-HERE>"; |
| 5 | + |
| 6 | +const client = new MailtrapClient({ |
| 7 | + token: TOKEN, |
| 8 | + accountId: Number(ACCOUNT_ID), |
| 9 | +}); |
| 10 | + |
| 11 | +async function emailLogsFlow() { |
| 12 | + try { |
| 13 | + // List email logs (paginated) |
| 14 | + const list = await client.emailLogs.getList(); |
| 15 | + console.log("Email logs:", list.messages.length, "messages, total:", list.total_count); |
| 16 | + if (list.messages.length > 0) { |
| 17 | + console.log("First message:", list.messages[0].message_id, list.messages[0].subject); |
| 18 | + } |
| 19 | + |
| 20 | + // List with filters (date range, category, status). Filter values can be single or array. |
| 21 | + const now = new Date(); |
| 22 | + const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000); |
| 23 | + const filtered = await client.emailLogs.getList({ |
| 24 | + filters: { |
| 25 | + sent_after: twoDaysAgo.toISOString(), |
| 26 | + sent_before: now.toISOString(), |
| 27 | + subject: { operator: "not_empty" }, |
| 28 | + to: { operator: "ci_equal", value: "recipient@example.com" }, |
| 29 | + category: { operator: "equal", value: ["Welcome Email", "Forget Password"] }, |
| 30 | + }, |
| 31 | + }); |
| 32 | + console.log("Filtered logs:", filtered.messages.length); |
| 33 | + |
| 34 | + // Next page (use search_after from previous response next_page_cursor) |
| 35 | + if (list.next_page_cursor) { |
| 36 | + const nextPage = await client.emailLogs.getList({ |
| 37 | + search_after: list.next_page_cursor, |
| 38 | + }); |
| 39 | + console.log("Next page:", nextPage.messages.length, "messages"); |
| 40 | + } |
| 41 | + |
| 42 | + // Get a single message by ID |
| 43 | + if (list.messages.length > 0) { |
| 44 | + const messageId = list.messages[0].message_id; |
| 45 | + const message = await client.emailLogs.get(messageId); |
| 46 | + console.log("Single message:", message.subject, "events:", message.events?.length ?? 0); |
| 47 | + } |
| 48 | + } catch (error) { |
| 49 | + console.error("Error in emailLogsFlow:", error instanceof Error ? error.message : String(error)); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +emailLogsFlow(); |
0 commit comments