MailerSend Node.js SDK

repository·main·Indexed 41 days ago

https://github.com/mailersend/mailersend-nodejs

A Node.js helper module for the MailerSend API (version 3.4.0) that provides a programmatic interface to send emails, SMS, and WhatsApp messages. It allows developers to manage domains, templates, recipients, and inbound routing, with support for features like template-based emails, personalization, attachments, scheduling, and interaction tracking.

Tokens
29.7K
Snippets
81
Records
97
Agent score
51%

What's inside MailerSend

  1. Install the MailerSend Node.js SDK

    main

    To use the MailerSend SDK in your Node.js project, install the mailersend package via npm.

    If you plan to use environment variables for configuration (as shown in the usage examples), it is also recommended to install dotenv to manage your API keys.

    npm install mailersend
    
    # Optional: for environment variable support
    npm install dotenv --save
  2. How to paginate through email lists

    main

    The email list endpoint uses page and limit for pagination. To walk the entire result set, you must request the next page until links.next is null.

    Important Rules:

    • Every request must repeat domain_id, date_from, date_to, and any other filters alongside the page parameter. Dropping any of these returns a 422 error.
    • Keep the limit constant throughout the entire walk to prevent page boundaries from shifting.
    • links.last is always null; do not attempt to calculate the total page count upfront. Use links.next to determine if more data exists.
    • meta provides current_page, current_page_url, from, path, per_page, and to, but does not include total or last_page.
    import 'dotenv/config';
    import { MailerSend } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const queryParams = {
      domain_id: "domain_id",
      date_from: 1443651141,
      date_to: 1443661141,
      limit: 100,
    };
    
    let page = 1;
    let hasMore = true;
    
    while (hasMore) {
      const response = await mailerSend.email.list({ ...queryParams, page });
    
      response.body.data.forEach((email) => console.log(email.id, email.status, email.subject));
    
      hasMore = response.body.links.next !== null;
      page++;
    }
  3. Paginate through email lists

    main

    When fetching lists of emails, the response follows a specific pagination pattern. The API does not provide a total count or a last_page number.

    To iterate through all available email records, you should request the next page sequentially until the links.next field in the EmailListLinks object returns null.

  4. Understand the difference between EmailListItem and Email

    main

    The MailerSend API provides two different ways to view email data depending on whether you are listing multiple emails or viewing a single specific email:

    1. EmailListItem (List View): Returned when fetching a list of emails. To optimize performance, these rows do not contain the recipient or activity data. Additionally, the text and html fields are always null in list rows.
    2. Email (Single View): Returned when using mailerSend.email.single(). This object contains the full details, including the recipient object, the activity array, and the actual text and html content of the email.

    If you need to see the content or recipient details of an email found in a list, you must use the single() method with the email's id.

  5. Configure Inbound filters and comparers

    main

    Inbound email handling uses filters to match or catch emails based on specific criteria.

    InboundFilterType

    Used to specify what part of the email to filter on:

    • catch_all
    • catch_recipient
    • match_all
    • match_sender
    • match_domain
    • match_header

    ComparerType

    Used to define the logic for the filter comparison:

    • equal
    • not-equal
    • contains
    • not-contains
    • starts-with
    • ends-with
    • not-starts-with
    • not-ends-with

    Filter Structures

    • InboundFilter: A basic filter with a comparer and a value.
    • MatchInboundFilter: An extension of InboundFilter that includes an optional key (useful for matching specific headers).
    • CatchFilter: A filter using an InboundFilterType and an optional array of InboundFilter objects.
    • MatchFilter: A filter using an InboundFilterType and an optional array of MatchInboundFilter objects.
  6. Send a basic email

    main

    To send a standard email, initialize the MailerSend client with your API key, define a Sender and an array of Recipient objects, and use EmailParams to set the subject, HTML content, and text content. Finally, call mailerSend.email.send(emailParams).

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setSubject("This is a Subject")
      .setHtml("<strong>This is the HTML content</strong>")
      .setText("This is the text content");
    
    await mailerSend.email.send(emailParams);
  7. Send template-based emails in specific languages

    main

    For template-based emails, you can specify a language using .setLanguage(languageCode). This is ignored for raw HTML/text emails.

    Supported language codes: de, en, es, fr, it, lt, nl, pl, pt-BR.

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setSubject("This is a Subject")
      .setTemplateId('templateId')
      .setLanguage("de");
    
    await mailerSend.email.send(emailParams);
  8. Schedule a message

    main

    To send an email at a later time, use .setSendAt(timestampOrIsoString). This method accepts either a Unix timestamp (integer) or an ISO 8601 date string.

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setSubject("This is a scheduled Subject")
      .setHtml("<strong>This is a scheduled HTML content</strong>")
      .setText("This is a scheduled text content")
      // Accepts a Unix timestamp (integer) or an ISO 8601 date string
      .setSendAt(Math.floor((new Date(Date.now() + 30 * 60 * 1000)).getTime() / 1000)); // Unix timestamp – send in 30 mins
      // .setSendAt("2040-11-21T14:00:00+00:00"); // ISO 8601 alternative
    
    await mailerSend.email.send(emailParams);
  9. Send email with RCPT TO recipients

    main

    rcptTo is intended for SMTP source delivery and accepts a list of Recipient objects.

    Behavior Note: When the to field is empty and rcptTo is provided, the addresses are forwarded as BCC.

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const rcptTo = [
      new Recipient("rcpt@client.com")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setSubject("This is a Subject")
      .setHtml("<strong>This is the HTML content</strong>")
      .setText("This is the text content")
      .setRcptTo(rcptTo);
    
    await mailerSend.email.send(emailParams);
  10. Send email with threading (references)

    main

    Note: The references field is available on paid plan accounts only.

    To enable email threading, use .setInReplyTo(messageId) and .setReferences([messageId1, messageId2]) on EmailParams.

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setSubject("Re: This is a Subject")
      .setHtml("<strong>This is the HTML content</strong>")
      .setText("This is the text content")
      .setInReplyTo("<original-message-id@yourdomain.com>")
      .setReferences([
        "<original-message-id@yourdomain.com>",
        "<another-message-id@yourdomain.com>",
      ]);
    
    await mailerSend.email.send(emailParams);
  11. Send a template-based email

    main

    Instead of providing raw HTML/text, you can use a pre-defined template by calling .setTemplateId('templateId') on EmailParams.

    import 'dotenv/config';
    import { MailerSend, EmailParams, Sender, Recipient } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setSubject("This is a Subject")
      .setTemplateId('templateId');
    
    await mailerSend.email.send(emailParams);
  12. Send email with attachments

    main

    To attach files, create an array of Attachment objects and pass them to .setAttachments(attachments). The Attachment constructor requires the file content as a base64 encoded string, the filename, and the attachment type (e.g., 'attachment' or 'inline').

    import 'dotenv/config';
    import fs from "fs";
    import { MailerSend, EmailParams, Sender, Recipient, Attachment } from "mailersend";
    
    const mailerSend = new MailerSend({
      apiKey: process.env.API_KEY,
    });
    
    const sentFrom = new Sender("you@yourdomain.com", "Your name");
    
    const recipients = [
      new Recipient("your@client.com", "Your Client")
    ];
    
    const attachments = [
      new Attachment(
        fs.readFileSync('/path/to/file.pdf', { encoding: 'base64' }),
        'file.pdf',
        'attachment'
      )
    ]
    
    const emailParams = new EmailParams()
      .setFrom(sentFrom)
      .setTo(recipients)
      .setReplyTo(sentFrom)
      .setAttachments(attachments)
      .setSubject("This is a Subject")
      .setHtml("<strong>This is the HTML content</strong>")
      .setText("This is the text content");
    
    await mailerSend.email.send(emailParams);