Welcome to Our Service!
We're excited to have you on board.
Get started by exploring our features.
# 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: `
We're excited to have you on board.
Get started by exploring our features.
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: `Inspect it using the tabs you see above.
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: "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: `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.