Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Mailtrap Node.js Client
https://github.com/mailtrap/mailtrap-nodejs
Admin
The official Mailtrap Node.js client provides an SDK to seamlessly integrate Mailtrap's email
...
Tokens:
8,427
Snippets:
27
Trust Score:
5.7
Update:
4 months ago
Context
Skills
Chat
Benchmark
75.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# 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, contact lists, custom contact fields, email templates, sending domains, suppression lists, and testing resources including projects, inboxes, and messages. Advanced features include contact import/export, event tracking, batch sending, and domain verification management. 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: ` <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body style="font-family: sans-serif;"> <div style="display: block; margin: auto; max-width: 600px;" class="main"> <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px"> Welcome to Our Service! </h1> <p>We're excited to have you on board.</p> <img alt="Welcome" src="cid:welcome.png" style="width: 100%;"> <p>Get started by exploring our features.</p> </div> </body> </html> `, 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: "<h1>Test Email</h1><p>This is for testing purposes.</p>", }) .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: ` <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body style="font-family: sans-serif;"> <div style="display: block; margin: auto; max-width: 600px;"> <h1 style="font-size: 18px; font-weight: bold; margin-top: 20px"> Congrats for sending test email with Mailtrap! </h1> <p>Inspect it using the tabs you see above.</p> <img alt="Inspect with Tabs" src="cid:welcome.png" style="width: 100%;"> </div> </body> </html> `, 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 Contact Lists Create and manage contact lists to organize your contacts into groups for targeted campaigns. ```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 contactListsFlow() { try { // Create a new contact list const newList = await client.contactLists.create({ name: "Premium Subscribers", }); console.log("Created contact list:", newList); // Get all contact lists const allLists = await client.contactLists.getList(); console.log("All contact lists:", allLists); // Get a specific contact list const list = await client.contactLists.get(newList.id); console.log("Contact list details:", list); // Update a contact list const updatedList = await client.contactLists.update(newList.id, { name: "VIP Premium Subscribers", }); console.log("Updated contact list:", updatedList); // Delete a contact list await client.contactLists.delete(newList.id); console.log("Contact list deleted successfully"); } catch (error) { console.error("Contact list operation failed:", error.message); } } contactListsFlow(); ``` ### Manage Contact Fields Create custom fields to store additional contact information beyond standard email addresses. ```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 contactFieldsFlow() { try { // Create a new contact field const newField = await client.contactFields.create({ name: "subscription_tier", field_type: "string", }); console.log("Created contact field:", newField); // Get all contact fields const allFields = await client.contactFields.getList(); console.log("All contact fields:", allFields); // Get a specific contact field const field = await client.contactFields.get(newField.id); console.log("Contact field details:", field); // Update a contact field const updatedField = await client.contactFields.update(newField.id, { name: "membership_level", }); console.log("Updated contact field:", updatedField); // Delete a contact field await client.contactFields.delete(newField.id); console.log("Contact field deleted successfully"); } catch (error) { console.error("Contact field operation failed:", error.message); } } contactFieldsFlow(); ``` ### Manage Sending Domains Verify and manage domains for sending production emails through Mailtrap. ```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 sendingDomainsFlow() { try { // Create a new sending domain const newDomain = await client.sendingDomains.create({ domain_name: "mail.yourdomain.com", }); console.log("Created sending domain:", newDomain); // Get all sending domains const allDomains = await client.sendingDomains.getList(); console.log("All sending domains:", allDomains); // Get a specific sending domain const domain = await client.sendingDomains.get(newDomain.id); console.log("Sending domain details:", domain); // Send setup instructions to email await client.sendingDomains.sendSetupInstructions( newDomain.id, "admin@yourdomain.com" ); console.log("Setup instructions sent to admin email"); // Delete a sending domain await client.sendingDomains.delete(newDomain.id); console.log("Sending domain deleted successfully"); } catch (error) { console.error("Sending domain operation failed:", error.message); } } sendingDomainsFlow(); ``` ### 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: "<h1>Welcome, {{user_name}}!</h1><p>Thank you for joining {{service_name}}.</p>", 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: "<h1>Welcome, {{user_name}}!</h1><p>Thank you for joining our amazing {{service_name}}.</p>", }); 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: ` <html> <body> <h1>This Month's Highlights</h1> <p>Check out our latest products and updates.</p> <a href="https://example.com/unsubscribe">Unsubscribe</a> </body> </html> `, 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. Additional capabilities include contact list segmentation, custom field management for advanced contact data, sending domain verification and management, and comprehensive contact import/export functionality for data migration. 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. The contact management suite provides full CRUD operations for contacts, lists, custom fields, and events, enabling sophisticated audience segmentation and personalization strategies. 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.
Mailtrap Node.js Client (mailtrap/mailtrap-nodejs) | Context7