Mailjet JavaScript SDK

repository·master·Indexed 42 days ago

https://github.com/mailjet/mailjet-apiv3-nodejs

The official JavaScript SDK (node-mailjet v7.0.0) for interacting with the Mailjet API. Designed for both Node.js and browser environments, it includes integration examples for Firebase Functions, React, and ExpressJS.

Tokens
27.1K
Snippets
96
Records
108
Agent score
51%

What's inside Mailjet

  1. Handle batch sending and partial failures in Send API v3.1

    master

    The Send API v3.1 allows batch sending via the Messages array. Batch sending is not an atomic operation. A 2xx HTTP response only means Mailjet accepted the request; individual messages within the batch can still fail.

    To handle this correctly:

    1. Inspect individual statuses: Check the Status of each entry in result.body.Messages.
      • Status: 'success': Message accepted and being delivered.
      • Status: 'error': Message failed. Check the Errors array for ErrorCode, ErrorMessage, and ErrorIdentifier.
    2. Enable Advanced Error Handling: Set AdvanceErrorHandling: true in the request body to receive one Errors entry per validation problem with machine-readable fields.
    3. Avoid duplicates during retry:
      • Assign a unique CustomID to every message.
      • On failure, only retry messages where Status is 'error'. Never re-include messages that were 'success'.
      • Use the Errors[].StatusCode to decide if a retry is appropriate (e.g., retry on StatusCode >= 500, but not on validation errors).
    import { Client, SendEmailV3_1, LibraryResponse } from 'node-mailjet';
    
    const mailjet = new Client({
      apiKey: process.env.MJ_APIKEY_PUBLIC,
      apiSecret: process.env.MJ_APIKEY_PRIVATE
    });
    
    (async () => {
      const data: SendEmailV3_1.Body = {
        Messages: [
          {
            From: { Email: 'pilot@test.com' },
            To: [{ Email: 'passenger1@test.com' }],
            Subject: 'This message is expected to succeed.',
            TextPart: 'Success message.',
            CustomID: 'order-1001',
          },
          {
            From: { Email: 'pilot@test.com' },
            To: [{ Email: 'not-a-valid-address' }],
            Subject: 'This message is expected to fail.',
            TextPart: 'Failure message.',
            CustomID: 'order-1002',
          },
        ],
        AdvanceErrorHandling: true,
      };
    
      const result: LibraryResponse<SendEmailV3_1.Response> = await mailjet
        .post('send', { version: 'v3.1' })
        .request(data);
    
      const succeeded = result.body.Messages.filter((message) => message.Status === 'success');
      const failed = result.body.Messages.filter((message) => message.Status !== 'success');
    })();
  2. Develop with local library changes using npm link

    master

    The application is configured to use the local version of the node-mailjet library rather than a published version. This is achieved via a file dependency in package.json:

    "node-mailjet": "file:../../dist"

    By pointing to the local dist folder, the application always uses the most recent changes made to the library source code, including local or uncommitted changes, without needing to publish to a registry.

  3. Use local library changes via npm link

    master

    The NodeJS example app is configured to use the local version of the Mailjet library rather than the published version. This is achieved by setting the node-mailjet dependency in package.json to point to the local dist folder:

    "node-mailjet": "file:../../dist"

    This allows you to test the latest changes to the library (including your own local modifications) immediately without needing to publish to a registry.

  4. Link the React demo to local library changes

    master

    The React application is configured to use the local version of the Mailjet library rather than a published npm package. This is achieved via a local file dependency in package.json:

    "node-mailjet": "file:../../dist"

    This setup ensures that the application always uses the most recent code from your local dist folder, allowing you to test your changes to the library immediately within the React demo.

  5. Start using the NodeJS example app

    master

    To run the provided NodeJS scripts, follow these steps:

    1. Install dependencies: Run npm install in the project root.
    2. Configure credentials: Create a .env file in the root directory. Use the existing .env.sample file as a template and replace the placeholders with your actual Mailjet credentials.
    3. Execute scripts: Use the following npm commands to run prepared scripts:
      • npm run start:user: Retrieve user information.
      • npm run start:sender: Retrieve sender information by email.
      • npm run start:contract: Retrieve a list of contacts.
      • npm run start:eventcallbackurl: Retrieve event callback URL information.

    Alternatively, you can run custom scripts directly using node ./src/<filename>.js.

    npm install
    # Create .env from .env.sample
    npm run start:user
  6. Use Mailjet in the browser with RequireJS

    master

    This example demonstrates how to use the Mailjet library directly in a browser environment using RequireJS.

    Important Note on CORS: Because of Cross-Origin Resource Sharing (CORS) limitations, browser-side requests cannot communicate directly with the Mailjet API. You must use a proxy server to facilitate these requests.

    # Mailjet app with using RequireJS
  7. Setup the ReactJS demo with a proxy

    master

    Because of CORS limitations, browser-side examples require a proxy to communicate with the Mailjet API. To run the React demo locally, you must install http-proxy and run a local server that proxies requests to https://api.mailjet.com.

    1. Install http-proxy globally:
      npm install -g http-proxy
    2. From the mailjet-apiv3-nodejs directory, start the proxy server:
      http-server -p 4001 --proxy="https://api.mailjet.com"
    3. The demo will be available at http://0.0.0.0:4001/examples/.
    npm install -g http-proxy
    http-server -p 4001 --proxy="https://api.mailjet.com"
  8. Initialize and build the Mailjet SDK (Development)

    master

    For contributors and developers working on the SDK itself, use the following commands to manage the environment and build process. Requires Node.JS >= 4.x.

    Setup

    • npm run init: Installs dependencies, patches the TypeScript compiler, and installs husky git hooks.

    Building

    • npm run build: Production build (includes minimization).
    • npm run build:dev && npm run build:prepublish: Development build.
    • npm run build:watch: Watch mode for hot-reloading.

    Testing

    • npm run test: Run all tests.
    • npm run test:watch: Watch tests.
    • npm run cover: Run tests with coverage reporting.
    • npm run pkg:link: Use this when testing new functionality locally with npm link to ensure correct .d.ts exporting.
    npm run init
    npm run build
    npm run test
  9. Setup the Mailjet NodeJS and ExpressJS application

    master

    This application is a basic ExpressJS app that allows you to send emails and manage contact lists.

    To set it up:

    1. Install dependencies using npm install.
    2. Create a .env file in the root directory. You should copy the contents of .env.sample and replace the placeholder values with your actual Mailjet credentials.
    3. Start the server using npm run start.

    The server will indicate it is running by printing server Listening on port <port> to the console.

    npm install
    # Create .env from .env.sample with real credentials
    npm run start