mailgun.js

repository·master·Indexed 20 days ago

https://github.com/mailgun/mailgun.js

A universal JavaScript SDK for interacting with the Mailgun API, compatible with Node.js (18.x+) and browser environments. It provides tools for sending emails with attachments and inline images, managing subaccounts, retrieving stored emails, and monitoring message queue status. The SDK supports multiple module systems (CJS, ESM, AMD) and allows the use of the Fetch API for environments without XMLHttpRequest support.

Tokens
72.6K
Snippets
237
Records
384
Agent score
67%

What's inside mailgun.js

  1. Explore Mailgun.js Type Definitions

    master

    The definitions module provides a comprehensive overview of the data structures used throughout the mailgun.js library. This includes namespaces for Enums and Interfaces, as well as various Type Aliases that define the shape of API requests, responses, and configuration objects.

    To understand the specific structure of a response or the required shape of a request for a particular method, you should refer to the specific type definitions listed in the module documentation.

  2. How pagination works in Mailgun.js

    master

    Most methods that return lists support pagination using two different strategies depending on the specific API endpoint.

    1. Using limit and page (Most common)

    Used by methods like mg.domains.domainTags.list(), mg.events.get(), mg.lists.list(), mg.lists.members.listMembers(), mg.validate.list(), and mg.suppressions.list().

    To paginate, include a limit in your initial query. The response will contain a pages object containing navigation links (first, last, next, previous). To fetch the next set of results, take the string value from the page property of the desired navigation object and pass it as the page argument in your next call.

    2. Using limit and skip

    Used by methods like mg.domains.list(), mg.domains.domainCredentials.list(), mg.routes.list(), and mg.webhooks.list().

    To paginate, provide skip (number of records to bypass from the start) and limit (number of records to receive) in the query object.

    // Strategy 1: limit and page
    // first call
    const listMembers = await mg.lists.members.listMembers('your_mailing_list', { limit: 2 });
    
    // second call using the 'page' string from the previous response
    const nextMembers = await mg.lists.members.listMembers('your_mailing_list', {
      limit: 2,
      page: '?page=next&address=test-1%40example.com&limit=2'
    });
    
    // Strategy 2: limit and skip
    const listDomainCredentials = await client.domains.domainCredentials.list(
      'your_domain_name',
      {
        skip: 10,
        limit: 1
      }
    );
  3. Manage Mailing List members with IMailListsMembers

    master

    The IMailListsMembers interface provides methods to manage individual and bulk members within a Mailgun mailing list. You can create, retrieve, update, delete, and list members, or perform bulk uploads via files.

    Key Operations:

    • Single Member Management: Use createMember, getMember, updateMember, and destroyMember to manage a specific user in a list.
    • Bulk Operations: Use createMembers to add multiple members at once or upload to process a file containing member data.
    • Listing Members: Use listMembers to retrieve a list of members for a specific mailing list, or listMembersByAddress to find members associated with a specific email address.
  4. Implement the IRequestProvider interface

    master

    The IRequestProvider interface defines the contract for components responsible for executing HTTP requests within mailgun.js. If you are building a custom request provider (e.g., to use a specific HTTP client or to implement custom proxy logic), you must implement the following three methods:

    1. makeRequest(url, method, data, config?): Executes the actual network request. It must return a Promise that resolves to an APIResponse.
    2. setSubAccountHeader(subAccountId): Sets the header used to identify a Mailgun Sub-Account for subsequent requests.
    3. resetSubAccountHeader(): Clears the Sub-Account header, reverting requests to the primary account context.

    This interface allows users to intercept or replace the default fetching mechanism used by the Mailgun client.

  5. Implement the ILogger interface

    master

    The ILogger interface allows you to provide a custom logging implementation to the Mailgun client. This is useful if you want to redirect Mailgun.js internal warnings to your own logging system (e.g., Winston, Bunyan, or a cloud logging service) instead of using the default console output.

    To implement this interface, you must provide an object that satisfies the warn method signature.

    // Example of a custom logger implementing ILogger
    const myLogger: ILogger = {
      warn: (message: string) => {
        console.warn(`[Mailgun Custom Log]: ${message}`);
      }
    };
  6. Understand Mailgun.js method naming conventions

    master

    The Mailgun.js client follows a consistent naming convention for its service methods, which helps predict the shape of the returned data:

    • get or get{{Item}}: Returns a single object.
    • list or list{{Items}}: Returns a list of objects.
    • create or create{{Item}}: Returns a single object.
    • update or update{{Item}}: Returns an object containing a status message.
    • destroy or destroy{{Item}}: Returns an object containing a status message.
  7. Setup the Mailgun client

    master

    To use the SDK, you must first instantiate a Mailgun object by passing a FormData implementation. Then, call .client() to configure the client with your credentials.

    Important Requirements:

    • FormData: Since version 3.0, you must pass a FormData object to the Mailgun constructor to ensure universal compatibility. In Node.js, you can use the built-in FormData or the form-data library.
    • EU Infrastructure: If you are using Mailgun's EU infrastructure, you must include url: 'https://api.eu.mailgun.net' in your client configuration.
    • Browser Usage: If using the SDK in a browser, a proxy is required due to CORS limitations. Never publish your private API key in frontend code.
    const Mailgun = require('mailgun.js');
    const mailgun = new Mailgun(FormData); // or const formData = require('form-data');
    const mg = mailgun.client({
      username: 'api',
      key: process.env.MAILGUN_API_KEY || 'MAILGUN_API_KEY'
    });
  8. Use Recipient Variables for personalized mass emails

    master

    Recipient Variables allow you to send a single API call that contains personalized content for each recipient. You define custom variables in the recipient-variables property as a JSON string, where keys are the recipient email addresses and values are the data for that specific recipient.

    In your email subject or html body, reference these variables using the %recipient.variable_name% syntax.

    const mailgunData = {
        from: 'Example.com Mailer <mailer@mailer.example.com>',
        to: ['me@example.com', 'you@example.com'],
        subject: 'Recipient - %recipient.title%',
        html: 'Here\'s %recipient.title% and <a href="%recipient.link%">link</a>',
        'recipient-variables': JSON.stringify({
          'me@example.com': {
            title: 'Me',
            link: 'href-var',
          },
          'you@example.com': {
            title: 'You',
            link: 'slug-recipient-var-c',
          },
        }),
      };
    
    try {
      const response = await mailgun.messages.create(DOMAIN_NAME, mailgunData);
    } catch (err) {
      console.error(err);
    }
  9. Development setup and testing

    master

    Requirements

    • Node.js >= 18.x

    Build commands

    • Install dependencies: npm install
    • Build for development (unminified): npm run build
    • Build for release (minified): npm run build:release

    Testing

    • Run all tests: npm run tests
    • Watch tests: npm run watch-tests
    • Link locally for testing new functionality (ensures correct .d.ts exporting): npm run link
    npm install
    npm run build
    npm run tests
  10. Run the Browser Demo locally

    master

    To run the browser demo, you must install and run http-proxy locally to proxy requests to https://api.mailgun.net.

    1. Install http-proxy globally:
      npm install -g http-proxy
    2. Run the proxy server from the mailgun-js directory:
      http-server -p 4001 --proxy="https://api.mailgun.net"
    3. Access the demo at http://0.0.0.0:4001/examples/.
    npm install -g http-proxy
    http-server -p 4001 --proxy="https://api.mailgun.net"