# Mailtrap Node.js Client ## Introduction Mailtrap is an official Node.js SDK that provides comprehensive integration with the Mailtrap.io email infrastructure platform. It enables developers to send transactional and bulk emails, test email workflows in sandbox environments, and manage email contacts and templates through a clean, type-safe API. The package is built with TypeScript and supports both direct API access and Nodemailer transport integration. The SDK offers three main operational modes: production email sending through verified domains, bulk email campaigns, and sandbox testing for development environments. It provides complete CRUD operations for contacts, email templates, suppression lists, and testing resources including projects, inboxes, and messages. With built-on error handling, automatic buffer encoding for attachments, and persistent HTTP connections, the SDK is optimized for both single-email and high-volume sending scenarios. ## API Reference ### Send Basic Email Send a simple transactional email with text content to a single recipient. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; const RECIPIENT_EMAIL = "recipient@example.com"; const client = new MailtrapClient({ token: TOKEN }); client .send({ from: { name: "Mailtrap Test", email: SENDER_EMAIL }, to: [{ email: RECIPIENT_EMAIL }], subject: "Hello from Mailtrap!", text: "Welcome to Mailtrap Sending!", }) .then((response) => { console.log("Success:", response.success); console.log("Message IDs:", response.message_ids); }) .catch((error) => { console.error("Error sending email:", error.message); }); ``` ### Send Email with HTML and Attachments Send an email with HTML content, custom variables, reply-to address, and inline attachments. ```typescript import fs from "node:fs"; import path from "node:path"; import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; const RECIPIENT_EMAIL = "recipient@example.com"; const REPLY_TO_EMAIL = "replyto@example.com"; const client = new MailtrapClient({ token: TOKEN }); const welcomeImage = fs.readFileSync(path.join(__dirname, "welcome.png")); client .send({ category: "transactional", custom_variables: { user_id: 12345, campaign: "welcome_series", environment: "production", }, from: { name: "Mailtrap Test", email: SENDER_EMAIL }, to: [{ email: RECIPIENT_EMAIL }], subject: "Hello from Mailtrap!", reply_to: { email: REPLY_TO_EMAIL }, html: `

Welcome to Our Service!

We're excited to have you on board.

Welcome

Get started by exploring our features.

`, attachments: [ { filename: "welcome.png", content_id: "welcome.png", disposition: "inline", content: welcomeImage, }, ], }) .then((response) => { console.log("Email sent successfully"); console.log("Message IDs:", response.message_ids); }) .catch((error) => { console.error("Failed to send email:", error.message); }); ``` ### Send Email Using Template Send an email using a pre-created Mailtrap template with dynamic variables. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; const RECIPIENT_EMAIL = "recipient@example.com"; const client = new MailtrapClient({ token: TOKEN }); client .send({ from: { name: "Mailtrap Test", email: SENDER_EMAIL }, to: [{ email: RECIPIENT_EMAIL }], template_uuid: "813e39db-c74a-4830-b037-0e6ba8b1fe88", template_variables: { user_name: "John Doe", account_type: "Premium", activation_link: "https://example.com/activate/abc123", }, }) .then((response) => { console.log("Template email sent"); console.log("Message IDs:", response.message_ids); }) .catch((error) => { console.error("Template send failed:", error.message); }); ``` ### Batch Send Emails Send multiple emails in a single API call with shared base properties and individual customizations. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; const client = new MailtrapClient({ token: TOKEN }); client .batchSend({ base: { from: { name: "Mailtrap Test", email: SENDER_EMAIL }, subject: "Important Update", text: "Hello {{name}}, we have an important update for you.", category: "notification", }, requests: [ { to: [{ email: "user1@example.com", name: "Alice Smith" }], custom_variables: { user_id: 1001, name: "Alice", }, }, { to: [{ email: "user2@example.com", name: "Bob Johnson" }], custom_variables: { user_id: 1002, name: "Bob", }, }, { to: [{ email: "user3@example.com", name: "Carol White" }], custom_variables: { user_id: 1003, name: "Carol", }, subject: "Urgent Update", // Override base subject }, ], }) .then((response) => { console.log("Batch send completed:", response.success); response.responses.forEach((result, index) => { if (result.success) { console.log(`Email ${index + 1} sent:`, result.message_ids); } else { console.error(`Email ${index + 1} failed:`, result.errors); } }); }) .catch((error) => { console.error("Batch send error:", error.message); }); ``` ### Send to Sandbox Testing Inbox Send emails to a sandbox testing inbox for development and debugging without actual email delivery. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const TEST_INBOX_ID = 123456; const SENDER_EMAIL = "sender@yourdomain.com"; const RECIPIENT_EMAIL = "recipient@example.com"; const client = new MailtrapClient({ token: TOKEN, sandbox: true, testInboxId: TEST_INBOX_ID, }); client .send({ from: { name: "Mailtrap Test", email: SENDER_EMAIL }, to: [{ email: RECIPIENT_EMAIL }], subject: "Testing Email Flow", text: "This email will be captured in the test inbox.", html: "

Test Email

This is for testing purposes.

", }) .then((response) => { console.log("Test email captured in inbox:", response.success); console.log("Message IDs:", response.message_ids); }) .catch((error) => { console.error("Sandbox send failed:", error.message); }); ``` ### Nodemailer Transport Integration Use Mailtrap as a Nodemailer transport for seamless integration with existing Nodemailer-based applications. ```typescript import { readFileSync } from "fs"; import Nodemailer from "nodemailer"; import { MailtrapTransport } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; const RECIPIENT_EMAIL = "recipient@example.com"; const REPLY_TO_EMAIL = "replyto@example.com"; const transport = Nodemailer.createTransport( MailtrapTransport({ token: TOKEN, }) ); transport .sendMail({ text: "Welcome to Mailtrap Sending!", to: { address: RECIPIENT_EMAIL, name: "John Doe", }, from: { address: SENDER_EMAIL, name: "Mailtrap Test", }, replyTo: REPLY_TO_EMAIL, subject: "Hello from Mailtrap!", html: `

Congrats for sending test email with Mailtrap!

Inspect it using the tabs you see above.

Inspect with Tabs
`, attachments: [ { filename: "welcome.png", content: readFileSync("./welcome.png"), cid: "welcome.png", contentDisposition: "inline", }, ], }) .then((info) => { console.log("Email sent via Nodemailer transport"); console.log("Message info:", info); }) .catch((error) => { console.error("Transport send failed:", error.message); }); ``` ### Manage Contacts Create, retrieve, update, and delete contacts in your Mailtrap account. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const ACCOUNT_ID = 12345; const client = new MailtrapClient({ token: TOKEN, accountId: ACCOUNT_ID, }); const contactData = { email: "john.smith@example.com", fields: { first_name: "John", last_name: "Smith", company: "Acme Corp", phone: "+1234567890", }, list_ids: [101, 102], // Add to specific lists }; // Create contact client.contacts .create(contactData) .then(async (createResponse) => { console.log("Contact created:", createResponse.data); const contactId = createResponse.data.id; // Get contact by email const getResponse = await client.contacts.get(contactData.email); console.log("Contact retrieved:", getResponse.data); // Update contact const updateResponse = await client.contacts.update(contactId, { email: contactData.email, fields: { first_name: "Johnny", last_name: "Smith", company: "New Acme Corp", }, }); console.log("Contact updated:", updateResponse.data); // Delete contact await client.contacts.delete(contactId); console.log("Contact deleted successfully"); }) .catch((error) => { console.error("Contact operation error:", error.message); }); ``` ### Manage Email Templates Create, list, retrieve, update, and delete email templates for reusable email content. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const ACCOUNT_ID = 12345; const client = new MailtrapClient({ token: TOKEN, accountId: ACCOUNT_ID, }); async function templatesFlow() { try { // Create a new template const newTemplate = await client.templates.create({ name: "Welcome Email", subject: "Welcome to Our Service, {{user_name}}!", category: "Promotional", body_html: "

Welcome, {{user_name}}!

Thank you for joining {{service_name}}.

", body_text: "Welcome, {{user_name}}! Thank you for joining {{service_name}}.", }); console.log("Created template:", newTemplate); // Get all templates const allTemplates = await client.templates.getList(); console.log("All templates count:", allTemplates.length); // Get a specific template const template = await client.templates.get(newTemplate.id); console.log("Template details:", template); // Update the template const updatedTemplate = await client.templates.update(newTemplate.id, { name: "Updated Welcome Email", subject: "Welcome to Our Amazing Service, {{user_name}}!", body_html: "

Welcome, {{user_name}}!

Thank you for joining our amazing {{service_name}}.

", }); console.log("Updated template:", updatedTemplate); // Delete the template await client.templates.delete(newTemplate.id); console.log("Template deleted successfully"); } catch (error) { console.error("Template operation failed:", error.message); } } templatesFlow(); ``` ### Manage Suppressions List and delete email suppressions (bounces, complaints, unsubscribes) to maintain sender reputation. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const ACCOUNT_ID = 12345; const client = new MailtrapClient({ token: TOKEN, accountId: ACCOUNT_ID, }); async function suppressionsFlow() { try { // Get all suppressions (up to 1000 per request) const suppressions = await client.suppressions.getList(); console.log("Total suppressions:", suppressions.length); suppressions.forEach((suppression) => { console.log( `Email: ${suppression.email}, Reason: ${suppression.reason}, Domain: ${suppression.domain_name}` ); }); // Get suppressions filtered by email const filteredSuppressions = await client.suppressions.getList({ email: "test@example.com", }); console.log("Filtered suppressions:", filteredSuppressions.length); // Delete a specific suppression by ID if (suppressions.length > 0) { const suppressionToDelete = suppressions[0]; await client.suppressions.delete(suppressionToDelete.id); console.log(`Suppression ${suppressionToDelete.id} deleted successfully`); } else { console.log("No suppressions found to delete"); } } catch (error) { console.error("Suppression operation failed:", error.message); } } suppressionsFlow(); ``` ### Manage Testing Inboxes Create and manage sandbox testing inboxes for email development and debugging. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const TEST_INBOX_ID = 123456; const ACCOUNT_ID = 12345; const client = new MailtrapClient({ token: TOKEN, testInboxId: TEST_INBOX_ID, accountId: ACCOUNT_ID, }); const projectsClient = client.testing.projects; const inboxesClient = client.testing.inboxes; projectsClient .getList() .then(async (projects) => { if (projects && projects.length > 0) { const firstProjectId = projects[0].id; console.log("Using project ID:", firstProjectId); // Create a new inbox await inboxesClient.create(firstProjectId, "test-inbox-name"); console.log("Inbox created"); // Get all inboxes const inboxes = await inboxesClient.getList(); console.log("Total inboxes:", inboxes.length); if (inboxes && inboxes.length > 0) { const firstInboxId = inboxes[0].id; // Get inbox attributes const attributes = await inboxesClient.getInboxAttributes(firstInboxId); console.log("Inbox attributes:", attributes); // Update inbox await inboxesClient.updateInbox(firstInboxId, { name: "updated-inbox-name", emailUsername: "custom-username", }); console.log("Inbox updated"); // Clean inbox (delete all messages) await inboxesClient.cleanInbox(firstInboxId); console.log("Inbox cleaned"); // Mark all messages as read await inboxesClient.markAsRead(firstInboxId); console.log("Messages marked as read"); // Reset inbox credentials await inboxesClient.resetCredentials(firstInboxId); console.log("Credentials reset"); // Enable email address for inbox await inboxesClient.enableEmailAddress(firstInboxId); console.log("Email address enabled"); // Reset email address const response = await inboxesClient.resetEmailAddress(firstInboxId); console.log("New email address:", response); } } }) .catch((error) => { console.error("Inbox management error:", error.message); }); ``` ### Send Bulk Emails Send bulk email campaigns to large recipient lists with optimized delivery. ```typescript import { MailtrapClient } from "mailtrap"; const TOKEN = "your_api_token_here"; const SENDER_EMAIL = "sender@yourdomain.com"; // Initialize client in bulk mode const client = new MailtrapClient({ token: TOKEN, bulk: true, }); client .send({ from: { name: "Marketing Team", email: SENDER_EMAIL }, to: [ { email: "subscriber1@example.com", name: "Subscriber One" }, { email: "subscriber2@example.com", name: "Subscriber Two" }, { email: "subscriber3@example.com", name: "Subscriber Three" }, ], subject: "Monthly Newsletter - December 2024", category: "newsletter", html: `

This Month's Highlights

Check out our latest products and updates.

Unsubscribe `, text: "This Month's Highlights. Check out our latest products and updates.", }) .then((response) => { console.log("Bulk email sent successfully"); console.log("Message IDs:", response.message_ids); }) .catch((error) => { console.error("Bulk send failed:", error.message); }); ``` ## Summary The Mailtrap Node.js SDK serves as a comprehensive email infrastructure solution for modern applications, supporting transactional emails, bulk campaigns, and sandbox testing workflows. Its primary use cases include sending order confirmations and password resets in e-commerce platforms, delivering newsletters and marketing campaigns, testing email templates in development environments before production deployment, and managing contact lists with custom fields for personalized communications. The SDK's template system enables teams to separate email design from application logic, while the suppression list management helps maintain sender reputation and comply with anti-spam regulations. Integration patterns range from simple drop-in replacements for existing email solutions to complex multi-stream architectures. Developers can use the SDK directly for full API control, integrate it as a Nodemailer transport for compatibility with existing codebases, or leverage the sandbox mode during development while seamlessly switching to production sending. The batch sending API optimizes performance for high-volume scenarios, while the comprehensive testing API enables automated email workflow validation. With TypeScript support, automatic retry logic, persistent connections, and detailed error reporting, the SDK provides a production-ready foundation for email functionality in Node.js applications of any scale.