Giter Club home page Giter Club logo

mailjet-apiv3-nodejs's Introduction

alt text

Mailjet JS

Build Status Current Version

Overview

Welcome to the Mailjet official JavaScript SDK built with webpack, babel & es5.
This can be used in node or in the browser.

Check out all the resources and JS code examples in the official Mailjet Documentation.

NOTE:
If used in the browser, at the moment a proxy is required to communicate with the Mailjet API due to CORS limitations.
Also, do not publish your private api key in frontend code.

Table of contents

Documentation

Compatibility

This library officially supports the following Node.JS versions:

  • >= v12.x

Install

Install the SDK use the following code:

npm install node-mailjet

Setup Client

Authentication

The Mailjet Email API uses your public and secret keys for authentication.

export MJ_APIKEY_PUBLIC='your API key'
export MJ_APIKEY_PRIVATE='your API secret'

export MJ_API_TOKEN='your API token'

Note:
For the SMS API the authorization is based on a Bearer token.
See information about it in the SMS API section of the readme.

Basic setup

Next, require the module and initialize your Mailjet client:

const Mailjet = require('node-mailjet');

For EMAIL API and SEND API:

const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC || 'your-api-key',
  apiSecret: process.env.MJ_APIKEY_PRIVATE || 'your-api-secret'
});

For SMS API:

const mailjet = new Mailjet({
  apiToken: process.env.MJ_API_TOKEN || 'your-api-token'
});

API Setup

For EMAIL API and SEND API you can use static method apiConnect:

const mailjet = Mailjet.apiConnect(
    process.env.MJ_APIKEY_PUBLIC,
    process.env.MJ_APIKEY_PRIVATE,
    {
      config: {},
      options: {}
    } 
);

SMS Setup

For SMS API you can use static method smsConnect:

const mailjet = Mailjet.smsConnect(
    process.env.MJ_API_TOKEN,
    {
      config: {},
      options: {}
    } 
);

Make your first call

Here's an example on how to send an email:

const Mailjet = require('node-mailjet');
const mailjet = Mailjet.apiConnect(
    process.env.MJ_APIKEY_PUBLIC,
    process.env.MJ_APIKEY_PRIVATE,
);

const request = mailjet
        .post('send', { version: 'v3.1' })
        .request({
          Messages: [
            {
              From: {
                Email: "[email protected]",
                Name: "Mailjet Pilot"
              },
              To: [
                {
                  Email: "[email protected]",
                  Name: "passenger 1"
                }
              ],
              Subject: "Your email flight plan!",
              TextPart: "Dear passenger 1, welcome to Mailjet! May the delivery force be with you!",
              HTMLPart: "<h3>Dear passenger 1, welcome to <a href=\"https://www.mailjet.com/\">Mailjet</a>!</h3><br />May the delivery force be with you!"
            }
          ]
        })

request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })

Configuration

To instantiate the library you can use the following constructor:

const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE,
  config: CONFIG,
  options: OPTIONS
});

const request = mailjet
    .METHOD(RESOURCE, CONFIG)
    .request(DATA, PARAMS, PERFORM_API_CALL)
  • METHOD: the method you want to use for this call (one of: post, put, get, delete)
  • RESOURCE: the API endpoint you want to call
  • OPTIONS: associative array describing the connection options (see Options bellow for full list)
  • CONFIG: associative array describing the connection config (see Config bellow for full list)
  • DATA: is the data to be sent as the request body (only for post, put, delete methods)
  • PARAMS: are the URL parameters to be sent with the request
  • PERFORM_API_CALL: is the Boolean parameter that determine need make local or real request

Options

options have this structure:

  • headers - associative array describing additional header fields which you can pass to the request
  • timeout - specifies the number of milliseconds before the request times out
  • proxy - defines the hostname, port, and protocol of the proxy server to redirect all requests (Node only option)
  • maxBodyLength - defines the max size of the http request content in bytes allowed (Node only option)
  • maxContentLength - defines the max size of the http response content in bytes allowed (Node only option)

You can pass options on init client and this options will use for each request:

const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE,
  options: {
    timeout: 1000,
    maxBodyLength: 1500,
    maxContentLength: 100,
    headers: {
      'X-API-Key': 'foobar',
    },
    proxy: {
      protocol: 'http',
      host: 'www.test-proxy.com',
      port: 3100,
    }
  }
});

For more detailed information visit this doc.

Request timeout

You are able to set a timeout for your request using the timeout parameter.

The timeout parameter describe the number of milliseconds before the request times out.
If the request takes longer than timeout, the request will be aborted.

const mailjet = new Mailjet({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE,
    options: {
        timeout: 100
    }
});

const request = mailjet
    .post('send', { version: 'v3.1' })

Request headers

You are able to set an additional headers for your request using the headers parameter.

const mailjet = new Mailjet({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE,
    options: {
      headers: {
        Accept: 'application/json',
        'API-Key': 'foobar', 
        'Content-Type': 'application/json'
      }
    }
});

const request = mailjet
    .post('send', { version: 'v3.1' })

Request max body length

You are able to set the max allowed size of the http request content in bytes for your request using the maxBodyLength parameter.

const mailjet = new Mailjet({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE,
    options: {
      maxBodyLength: 100
    }
});

const request = mailjet
    .post('send', { version: 'v3.1' })

NOTE:
This parameter worked only on the NodeJS side

Response max content length

You are able to set the max allowed size of the http response content in bytes using the maxContentLength parameter.

const mailjet = new Mailjet({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE,
    options: {
      maxContentLength: 50
    }
});

const request = mailjet
    .post('send', { version: 'v3.1' })

NOTE:
This parameter worked only on the NodeJS side

Use proxy

The proxy parameter allows you to define the hostname, port, auth, and protocol of the proxy server for send the API requests through it:

const mailjet = new Mailjet({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE,
    options: {
      proxy: {
        protocol: 'https',
        host: '127.0.0.1',
        port: 8080,
        auth: {
          username: 'test',
          password: 'password'
        }
      }
    }
});

const request = mailjet
    .post('send', { version: 'v3.1' })

NOTE:
This parameter worked only on the NodeJS side

Config

config have this structure:

  • host - sets custom host URL
  • version - sets required version of API for determinate endpoint (set of v3, v3.1, v4)
  • output - indicates the type of data that the server will respond with

You can pass config on init client and this config will use for each request:

const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE,
  config: {
      host: 'api.mailjet.com',
      version: 'v3',
      output: 'text',
  }
});

And for each request manually (this config will have more precedence than passed in client):

const request = mailjet
    .post('send', {
        host: 'api.mailjet.com',
        version: 'v3.1',
        output: 'json',
    })

API Versioning

The Mailjet API is spread among three distinct versions:

  • v3 - The Email API
  • v3.1 - The Email Send API v3.1, which is the latest version of our Send API
  • v4 - The SMS API

Since most Email API endpoints are located under v3, it sets as the default one and does not need to be specified when making your request.
For the others you need to specify the version using version parameter.

For example, if using Send API v3.1:

const request = mailjet
    .post('send', { version: 'v3.1' })

For additional information refer to our API Reference.

Host URL

The default base host name for the Mailjet API is api.mailjet.com.
You can modify this host URL by setting a value for host in your call:

const request = mailjet
    .post('send', { version: 'v3.1', host: 'api.us.mailjet.com' })

If your account has been moved to Mailjet's US architecture, the host value you need to set is api.us.mailjet.com.

Response output

The default response output for the Mailjet API is json.
You can modify this response output data by setting a value for output in your call:

const request = mailjet
    .post('send', { version: 'v3.1', output: 'arraybuffer' })

The output parameter allowing you to specify the type of response data:

  • arraybuffer
  • document
  • json (Default)
  • text
  • stream
  • blob (Browser only option)

Disable API call

By default, the API call parameter is always enabled.
However, you may want to disable it during testing to prevent unnecessary calls to the Mailjet API.

This is done by passing the performAPICall argument with value false to .request(data, params, performAPICall) method:

const request = mailjet
    .post('send', { version: 'v3.1' })
    .request({}, {}, false)

TypeScript

Current library based on TypeScript and provide full cover for Mailjet types.
All types can be exported from main entrypoint 'node-mailjet':

import { 
  Contact,
  SendEmailV3, 
  SendEmailV3_1,
  Message,
  Segmentation,
  Template,
  SendMessage,
  Webhook
} from 'node-mailjet';

As well library has a generic method Request.request<TResult>(data, params, performAPICall) that could use with these types.

Send Email example

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: '[email protected]',
        },
        To: [
          {
            Email: '[email protected]',
          },
        ],
        TemplateErrorReporting: {
          Email: '[email protected]',
          Name: 'Reporter',
        },
        Subject: 'Your email flight plan!',
        HTMLPart: '<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with you!',
        TextPart: 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
      },
    ],
  };

  const result: LibraryResponse<SendEmailV3_1.Response> = await mailjet
          .post('send', { version: 'v3.1' })
          .request(data);

  const { Status } = result.body.Messages[0];
})();

And response will have this shape:

{
    response: Response;
    body: {
      Messages: Array<{
        Status: string;
        Errors: Array<Record<string, string>>;
        CustomID: string;
        ...
      }>;
    }
}

Send Message Example

import * as Mailjet from 'node-mailjet'; // another possible importing option

const mailjet = new Mailjet.Client({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

(async () => {

    const body: Mailjet.SendMessage.Body = {
        From: '[email protected]',
        To: '[email protected]',
        Text: 'Test'
    };

    const result: Mailjet.LibraryResponse<Mailjet.SendMessage.Response> = await mailjet
        .post('contact', { version: 'v3' })
        .request(body);
    

    const { Status } = result.body;
})();

And response will have this shape:

{
    response: Response;
    body: {
      From: string;
      To: string;
      Text: string;
      MessageID: string | number;
      SMSCount: number;
      CreationTS: number;
      SentTS: number;
      Cost: {
        Value: number;
        Currency: string;
      };
      Status: {
        Code: number;
        Name: string;
        Description: string;
      };
    }
}

Get Contact Example

import { Client, Contact, LibraryResponse } from 'node-mailjet'

const mailjet = new Client({
    apiKey: process.env.MJ_APIKEY_PUBLIC,
    apiSecret: process.env.MJ_APIKEY_PRIVATE
});

(async () => {
  const queryData: Contact.GetContactQueryParams = {
    IsExcludedFromCampaigns: false,
    Campaign: 2234234,
  };

  const result: LibraryResponse<Contact.GetContactResponse> = await mailjet
    .get('contact', { version: 'v3' })
    .request({}, queryData);

  const ContactID = result.body.Data[0].ID;
})();

And response will have this shape:

{
    response: Response;
    body: {
      Count: number;
      Total: number;
      Data: Array<{
        ID: number;
        IsExcludedFromCampaigns: boolean;
        Name: string;
        CreatedAt: string;
        DeliveredCount: number;
        Email: string;
        ...
      }>;
    }
}

Our external Typings

For earlier versions (3.*.* and low) of library you can use @types/node-mailjet dependency.

The types are published in npm and ready for use.
Here is the npm page.

Feel free to request changes if there is something missing, or you just suggest an improvement.

The main repository is here.
And here is the file with our types.


Browser Demo

For demo to work, you'll need to install and run http-proxy locally.

Install it with:

npm install -g http-proxy

Then run the following command from the mailjet-apiv3-nodejs directory:

http-server -p 4001 --proxy="https://api.mailjet.com"

Demo should be up and running at http://0.0.0.0:4001/examples/


App examples

List of basic applications that was built in different environments:

  1. Browser - Basic app that using RequireJS and provide page where you can make some requests
  2. Node - Basic app that contain simple scripts with some requests
  3. Sendmail - ExpressJS based app that allows to retrieve list of contacts and send email to some person
  4. ReactJS - ReactJS based app that provides page where you can make some requests
  5. Firebase - Firebase based app that provides Firebase Functions for sending hello world email and sending email based on dynamic query string data

NOTE: For browser side examples at the moment a proxy is required to communicate with the Mailjet API due to CORS limitations.


Request examples

Basic API

POST Request

Use the post method of the Mailjet client:

const request = mailjet
  .post($RESOURCE, $CONFIG)
  .id($ID)
  .request($DATA, $PARAMS, $PERFORM_API_CALL)

.request parameter $DATA will contain the body of the POST request.
You need to define .id if you want to perform an action on a specific object and need to identify it.

Simple POST request

Create a new contact:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .post('contact')
        .request({
          Email: "[email protected]",
          IsExcludedFromCampaigns: true,
          Name: "New Contact"
        })

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })
Using actions

Manage the subscription status of a contact to multiple lists:

const { Client } = require('node-mailjet') // another importing option using destructuring
const mailjet = new Client({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .post('contact')
        .id($contactID)
        .action('managecontactslists')
        .request({
          ContactsLists: [
            {
              ListID: $listID,
              Action: "addnoforce"
            }
          ]
        })

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })

GET Request

Use the get method of the Mailjet client:

const request = mailjet
 .get($RESOURCE, $CONFIG)
 .id($ID)
 .request($DATA, $PARAMS, $PERFORM_API_CALL)

.request parameter $PARAMS will contain any query parameters applied to the request.
You need to define .id if you want to retrieve a specific object.

Retrieve all objects

Retrieve all contacts:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .get('contact')
        .request()

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })
Use filtering

Retrieve all contacts that are not in the campaign exclusion list:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .get('contact')
        .request({}, { IsExcludedFromCampaigns: false })

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })
Retrieve a single object

Retrieve a specific contact by ID:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .get('contact')
        .id($contactID)
        .request()

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })

PUT Request

Use the put method of the Mailjet client:

const request = mailjet
    .put($RESOURCE, $CONFIG)
    .id($ID)
    .request($DATA, $PARAMS, $PERFORM_API_CALL)

You need to define .id to specify the object that you need to edit.
.request parameter $DATA will contain the body of the PUT request.

A PUT request in the Mailjet API will work as a PATCH request - the update will affect only the specified properties.
The other properties of an existing resource will neither be modified, nor deleted.
It also means that all non-mandatory properties can be omitted from your payload.

Update the contact properties for a contact:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .put('contactdata')
        .id($contactID)
        .request({
          Data: [
            {
              first_name: "John",
              last_name: "Smith"
            }
          ]
        })

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })

DELETE Request

Use the delete method of the Mailjet client:

const request = mailjet
 .delete($RESOURCE, $CONFIG)
 .id($ID)
 .request($DATA, $PARAMS, $PERFORM_API_CALL)

You need to define .id to specify the object you want to delete.
.request parameter $DATA should be empty.

Upon a successful DELETE request the response will not include a response body, but only a 204 No Content response code.

Delete an email template:

const Mailjet = require('node-mailjet')
const mailjet = new Mailjet({
  apiKey: process.env.MJ_APIKEY_PUBLIC,
  apiSecret: process.env.MJ_APIKEY_PRIVATE
});

const request = mailjet
        .delete('template')
        .id($templateID)
        .request()

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })

SMS API

Token authentication

Authentication for the SMS API endpoints is done using a Bearer token.
The Bearer token is generated in the SMS section of your Mailjet account.

const Mailjet = require('node-mailjet');
const mailjet = Mailjet.smsConnect(process.env.MJ_API_TOKEN);

Example request

Here's an example SMS API request:

const Mailjet = require('node-mailjet');
const mailjet = Mailjet.smsConnect(process.env.MJ_API_TOKEN, {
  config: {
    version: 'v4'
  }
});

const request = mailjet
        .post('sms-send')
        .request({
          Text: "Have a nice SMS flight with Mailjet !",
          To: "+33600000000",
          From: "MJPilot"
        })

request
        .then((result) => {
          console.log(result.body)
        })
        .catch((err) => {
          console.log(err.statusCode)
        })

Development

Mailjet loves developers. You can be part of this project!
This SDK is a great introduction to the open source world, check out the code!

Feel free to ask anything, and contribute:

  • Fork the project.
  • Create a new branch.
  • Implement your feature or bug fix.
  • Add documentation to it.
  • Commit, push, open a pull request and voila.

If you have suggestions on how to improve the guides, please submit an issue in our Official API Documentation repo.

Requirements

  • Requires Node.JS >= 4.x

Init package with:

npm run init

Where the init script contain all essential init steps:

  1. npm install - install all dependencies
  2. npm run ts:patch - patch TS compiler for correct building TypeScript declaration files
  3. npm run pkg:prepare - husky install for git hooks

Build

Build for release purposes (include minimizing):

npm run build

Build for dev purposes (without minimizing):

npm run build:dev && npm run build:prepublish

Build for watching and hot-reload:

npm run build:watch

Tests

Execute all tests:

npm run test

Watch tests with:

npm run test:watch

Receive coverage of tests with:

npm run cover

To test new functionality locally using npm link please use npm script npm run pkg:link.
This is needed for correct exporting d.ts files.

Merging changes

Before PR merge check that commits info will be correctly added to the CHANGELOG.md file:

npm run release:dry

As well that allow to see that package version was correct increased for SemVer convention.

And then run:

npm run release

IMPORTANT: if package version was increased incorrect you should manually use this scripts:

  • npm run release:patch
  • npm run release:minor
  • npm run release:major

CI process isn't working currently, so please manually run npm run test

Release Process

Releases occur after feature branches have been tested and merged into master.

First, checkout master and pull the latest commits.

git checkout master
git pull

Next, run npm run release.

After that, cd ./dist and then run npm login and npm publish to publish changes on npm.

mailjet-apiv3-nodejs's People

Contributors

acestudiooleg avatar ai-wintermute avatar andrii-y avatar andrii-yelis avatar arnaudbreton avatar ceer avatar dependabot[bot] avatar eboisgon avatar emmanuelgautier avatar fadomire avatar farvilain avatar highlycaffeinated avatar joedimarzio avatar jordaaash avatar katafractari avatar kush avatar latanasov avatar mskochev avatar ngarnier avatar nickewansmith avatar olexandr-mazepa avatar omazepa avatar p-j avatar scroll17 avatar timaschew avatar trejgun avatar yankovanov-sc avatar zeefarmer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mailjet-apiv3-nodejs's Issues

Help with "Ouch! Something went wrong on our side and we apologize!" Error

Hi Guys,

I've been using the MailJet v3.1 API to send status reports for our app.

We compose a basic email and attach a PDF file. The PDF file itself is not very big (649 KB) and has images. When I try and run this I get the "Ouch! Something went wrong on our side and we apologize!". The full error is here:

{ Error: Unsuccessful
    at /Users/markpaul/Documents/Source/Software/reporting-service/node_modules/node-mailjet/mailjet-client.js:220:23
    at Request.callback (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/index.js:718:3)
    at parser (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/index.js:906:18)
    at IncomingMessage.res.on.e (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/parsers/json.js:19:7)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
From previous event:
    at MailjetClient.httpRequest (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/node-mailjet/mailjet-client.js:200:10)
    at MailjetResource.result (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/node-mailjet/mailjet-client.js:311:17)
    at MailjetResource.request (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/node-mailjet/mailjet-client.js:384:15)
    at /Users/markpaul/Documents/Source/Software/reporting-service/actionHtmlEmailReports.js:183:14
    at next (native)
    at onFulfilled (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/co/index.js:65:19)
    at runCallback (timers.js:672:20)
    at tryOnImmediate (timers.js:645:5)
    at processImmediate [as _immediateCallback] (timers.js:617:5)
From previous event:
    at next (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/co/index.js:100:51)
    at onFulfilled (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/co/index.js:69:7)
    at /Users/markpaul/Documents/Source/Software/reporting-service/node_modules/co/index.js:54:5
    at co (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/co/index.js:50:10)
    at Object.module.exports.handler (/Users/markpaul/Documents/Source/Software/reporting-service/actionHtmlEmailReports.js:51:3)
    at [eval]:1:40
    at ContextifyScript.Script.runInThisContext (vm.js:25:33)
    at Object.runInThisContext (vm.js:97:38)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:570:32)
    at evalScript (bootstrap_node.js:354:27)
    at run (bootstrap_node.js:123:11)
    at run (bootstrap_node.js:390:7)
    at startup (bootstrap_node.js:122:9)
    at bootstrap_node.js:505:3
  ErrorMessage: 'Ouch! Something went wrong on our side and we apologize! Please contact our support team whoโ€™ll be able to help you on this',
  statusCode: 500,
  response: 
   Response {
     domain: null,
     _events: {},
     _eventsCount: 0,
     _maxListeners: undefined,
     res: 
      IncomingMessage {
        _readableState: [Object],
        readable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 4,
        _maxListeners: undefined,
        socket: [Object],
        connection: [Object],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Object],
        trailers: {},
        rawTrailers: [],
        upgrade: false,
        url: '',
        method: null,
        statusCode: 500,
        statusMessage: 'Internal Server Error',
        client: [Object],
        _consuming: true,
        _dumped: false,
        req: [Object],
        text: '{"ErrorIdentifier":"e777ae92-621b-440e-91f5-b37ed5341719","StatusCode":500,"ErrorMessage":"Ouch! Something went wrong on our side and we apologize! Please contact our support team whoโ€™ll be able to help you on this"}',
        read: [Function] },
     request: 
      Request {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _agent: false,
        _formData: null,
        method: 'POST',
        url: 'https://api.mailjet.com/v3.1/send',
        _header: [Object],
        header: [Object],
        writable: true,
        _redirects: 0,
        _maxRedirects: 5,
        cookies: '',
        qs: {},
        _query: [],
        qsRaw: [],
        _redirectList: [],
        _streamRequest: false,
        _data: [Object],
        req: [Object],
        protocol: 'https:',
        host: 'api.mailjet.com',
        _endCalled: true,
        _callback: [Function],
        res: [Object],
        response: [Circular],
        called: true },
     req: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 3,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedHeader: [Object],
        _contentLength: 866406,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'POST /v3.1/send HTTP/1.1\r\nHost: api.mailjet.com\r\nAccept-Encoding: gzip, deflate\r\nuser-agent: mailjet-api-v3-nodejs/3.2.1\r\nContent-type: application/json\r\nAuthorization: Basic codehereremovedforgithub=\r\nContent-Length: 866406\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/v3.1/send',
        _ended: true,
        parser: null,
        res: [Object] },
     text: '{"ErrorIdentifier":"e777ae92-621b-440e-91f5-b37ed5341719","StatusCode":500,"ErrorMessage":"Ouch! Something went wrong on our side and we apologize! Please contact our support team whoโ€™ll be able to help you on this"}',
     body: 
      { ErrorIdentifier: 'e777ae92-621b-440e-91f5-b37ed5341719',
        StatusCode: 500,
        ErrorMessage: 'Ouch! Something went wrong on our side and we apologize! Please contact our support team whoโ€™ll be able to help you on this' },
     files: undefined,
     buffered: true,
     headers: 
      { 'content-length': '218',
        'content-type': 'application/json; charset=UTF-8',
        date: 'Tue, 13 Mar 2018 04:00:04 GMT',
        connection: 'close' },
     header: 
      { 'content-length': '218',
        'content-type': 'application/json; charset=UTF-8',
        date: 'Tue, 13 Mar 2018 04:00:04 GMT',
        connection: 'close' },
     statusCode: 500,
     status: 500,
     statusType: 5,
     info: false,
     ok: false,
     redirect: false,
     clientError: false,
     serverError: true,
     error: 
      { Error: cannot POST /v3.1/send (500)
          at Response.toError (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/response.js:94:15)
          at ResponseBase._setStatusProperties (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/response-base.js:123:16)
          at new Response (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/response.js:41:8)
          at Request._emitResponse (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/index.js:742:20)
          at parser (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/index.js:906:38)
          at IncomingMessage.res.on.e (/Users/markpaul/Documents/Source/Software/reporting-service/node_modules/superagent/lib/node/parsers/json.js:19:7)
          at emitNone (events.js:91:20)
          at IncomingMessage.emit (events.js:185:7)
          at endReadableNT (_stream_readable.js:974:12)
          at _combinedTickCallback (internal/process/next_tick.js:80:11)
          at process._tickDomainCallback (internal/process/next_tick.js:128:9)
        status: 500,
        text: '{"ErrorIdentifier":"e777ae92-621b-440e-91f5-b37ed5341719","StatusCode":500,"ErrorMessage":"Ouch! Something went wrong on our side and we apologize! Please contact our support team whoโ€™ll be able to help you on this"}',
        method: 'POST',
        path: '/v3.1/send' },
     accepted: false,
     noContent: false,
     badRequest: false,
     unauthorized: false,
     notAcceptable: false,
     forbidden: false,
     notFound: false,
     type: 'application/json',
     charset: 'UTF-8',
     links: {},
     setEncoding: [Function: bound ],
     redirects: [] } }

I use the send email code as per here: https://dev.mailjet.com/guides/#sending-with-attached-files

Specific method:

const request = mailjet
            .post("send", {'version': 'v3.1'})
            .request({
                "Messages":[{
                  "From": {
                    "Email": "from",
                    "Name": "Mark"
                  },
                  "To": [{
                      "Email": toEmail,
                      "Name": `${user.firstName} ${user.lastName}`
                    }],
                  "Subject": `${user.firstName}, here is your Program Report`,
                  "HTMLPart": htmlEmailTemplate(user, program),
                  "Attachments": [ {
                    "ContentType": "application/pdf",
                    "Filename": `${user.firstName}_${user.lastName}_${reportId}.pdf`,
                    "Base64Content": pdfFile.toString('base64')
                  }]
                }]
            });

The PDF is not corrupted as when i write to file it is fine.

I have another email report that gets sent out, also with a PDF which is smaller (35 KB) as there are no images - but this works fine.

Any idea what is wrong?

Thanks,
Mark

Typings for Typescript

Hi, are there any typings available for use with typescript? If not please consider this a feature request :) Would be really great to have!

After release 2.0.0 node-mailjet fails with typings

Hello,
I use node-mailjet with Typescript. After the release with Promise I receive an error and my builds fails constantly without any success of fixing it:

return new Promise((resolve, reject) => {
W20160613-12:16:56.766(8)? (STDERR)                                         ^
W20160613-12:16:56.768(8)? (STDERR) SyntaxError: Unexpected token >

The code hangs at mailjet-client.js in line 172. Could you explain what to do making this package work with typescript?

Thanks

Unsuccessful Error

Hello, just trying to test the API in our app, and I am not able to successfully send any emails. Using the following code:

import mailer from 'server/store/site/mailer'
const mailjet = Mailjet.connect(env('MAILJET_KEY'), env('MAILJET_SECRET'))

export async function sendConfirmationEmail(account, confirmationCode, locale) {
        let link = `${env('PROXY_PROTO')}://${env('PROXY_HOST')}${env('PROXY_PORT').length > 0 ? `:${env('PROXY_PORT')}` : ''}/registration?`
        link += `code=${confirmationCode}`
        link = encodeURI(link)
        return mailjet.post('send').request({
                Messages :[
                        {
                                From: {
                                        Email: "XXXXXX@XXXXXX",
                                        Name: "XXXXXX"
                                },
                                To: [
                                        {
                                                "Email": account.email,
                                                "Name": "New User"
                                        }
                                ],
                                TemplateID: 361710,
                                TemplateLanguage: true,
                                Subject: "XXXXX Registration Confirmation",
                                Variables: {
                                        confirmation_link: link
                                }
                        }
                ]
        })
}

I am getting the following error:

Error
Unsuccessful
Error: Unsuccessful
    at /home/ubuntu/registration-referral/node_modules/node-mailjet/mailjet-client.js:220:23
    at Request.callback (/home/ubuntu/registration-referral/node_modules/superagent/lib/node/index.js:718:3)
    at IncomingMessage.parser (/home/ubuntu/registration-referral/node_modules/superagent/lib/node/index.js:906:18)
    at IncomingMessage.emit (events.js:185:15)
    at IncomingMessage.emit (domain.js:422:20)
    at endReadableNT (_stream_readable.js:1106:12)
    at process._tickCallback (internal/process/next_tick.js:178:19)
From previous event:
    at MailjetClient.httpRequest (/home/ubuntu/registration-referral/node_modules/node-mailjet/mailjet-client.js:200:10)
    at MailjetResource.result (/home/ubuntu/registration-referral/node_modules/node-mailjet/mailjet-client.js:311:17)
    at MailjetResource.request (/home/ubuntu/registration-referral/node_modules/node-mailjet/mailjet-client.js:384:15)
    at _callee2$ (/home/ubuntu/registration-referral/src/server/mailer/index.js:56:30)
    at tryCatch (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
    at Generator.prototype.(anonymous function) [as next] (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
    at step (/home/ubuntu/registration-referral/src/server/mailer/index.js:132:993)
    at /home/ubuntu/registration-referral/src/server/mailer/index.js:132:1223
    at new Promise (<anonymous>)
    at /home/ubuntu/registration-referral/src/server/mailer/index.js:132:904
    at sendConfirmationEmail (/home/ubuntu/registration-referral/src/server/mailer/index.js:73:177)
    at Object._callee2$ (/home/ubuntu/registration-referral/src/server/koa/auth/index.js:143:4)
    at tryCatch (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
    at Generator.prototype.(anonymous function) [as next] (/home/ubuntu/registration-referral/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
    at step (/home/ubuntu/registration-referral/src/server/koa/auth/index.js:511:1601)
    at /home/ubuntu/registration-referral/src/server/koa/auth/index.js:511:1761
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)
---------------------------------------

Frequent ENOTFOUND errors

In my node app (running inside a docker container) I frequently get ENOTFOUND errors when caling mailjet.post('send').request(message).

It is working most of the time, but suddenly failing for no obvious reason with

getaddrinfo ENOTFOUND api.mailjet.com api.mailjet.com:443

In general I have not connectivity issues from this server and when I try manually reaching api.mail.jet.com from the server it always worked so far. And suddenly the issue pops up again in my app. Any idea on what is happening here?

Reorganize and eliminate dependencies

The number of dependencies is just too damn high for what this official wrapper does. We got request + superagent (don't these do equal stuff?), standard that will blow up with chai, eslint, .... Reorganizing the dependencies should be considered.

Here is a little sneak peak at what gets installed:

`-- [email protected] 
  +-- [email protected] 
  +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | | `-- [email protected] 
  | `-- [email protected] 
  +-- [email protected] 
  | `-- [email protected] 
  +-- [email protected] 
  +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | | `-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | | `-- [email protected] 
  | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | `-- [email protected] 
  | | `-- [email protected] 
  | |   `-- [email protected] 
  | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | `-- [email protected] 
  | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | `-- [email protected] 
  | |   +-- [email protected] 
  | |   +-- [email protected] 
  | |   +-- [email protected] 
  | |   | `-- [email protected] 
  | |   +-- [email protected] 
  | |   +-- [email protected] 
  | |   | `-- [email protected] 
  | |   +-- [email protected] 
  | |   +-- [email protected] 
  | |   `-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | | `-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | `-- [email protected] 
  +-- [email protected] 
  | +-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | |   `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | +-- [email protected] 
  | | | | | +-- [email protected] 
  | | | | | | +-- [email protected] 
  | | | | | | | `-- [email protected] 
  | | | | | | +-- [email protected] 
  | | | | | | `-- [email protected] 
  | | | | | |   `-- [email protected] 
  | | | | | +-- [email protected] 
  | | | | | +-- [email protected] 
  | | | | | | `-- [email protected] 
  | | | | | +-- [email protected] 
  | | | | | `-- [email protected] 
  | | | | |   `-- [email protected] 
  | | | | +-- [email protected] 
  | | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | |   +-- [email protected] 
  | | | |   `-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | |   +-- [email protected] 
  | | | |   `-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | +-- [email protected] 
  | | | | | `-- [email protected] 
  | | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | | `-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | `-- [email protected] 
  | |   `-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | +-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | +-- [email protected] 
  | | | `-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | +-- [email protected] 
  | | | `-- [email protected] 
  | | |   `-- [email protected] 
  | | `-- [email protected] 
  | |   `-- [email protected] 
  | `-- [email protected] 
  `-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    | `-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    +-- [email protected] 
    | +-- [email protected] 
    | +-- [email protected] 
    | +-- [email protected] 
    | +-- [email protected] 
    | +-- [email protected] 
    | `-- [email protected] 
    `-- [email protected] 

Es6 Imports

I'm currently using Mailjet in my application.
Then I decided to switch everything to the new ES6 syntax

However, I get the following errors
this.setConfig is not a function
at MailjetClient

import mailjet from 'node-mailjet'
mailjet().connect('key', 'secret')

Request: decrease number of dependecies

Current dependency tree - difficult to keep track of what's safe and what's not. Currently 6.8MB.

โ”œโ”€โ”ฌ [email protected]
โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚ โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚ โ””โ”€โ”ฌ [email protected]
โ”‚   โ””โ”€โ”ฌ [email protected]
โ”‚     โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ””โ”€โ”ฌ [email protected]
โ”‚     โ”‚   โ””โ”€โ”€ [email protected]
โ”‚     โ”œโ”€โ”€ [email protected]
โ”‚     โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”œโ”€โ”€ [email protected]
โ”‚     โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ””โ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚   โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚   โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚   โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚   โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚ โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚ โ””โ”€โ”ฌ [email protected]
โ”‚     โ”‚   โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚   โ”œโ”€โ”ฌ [email protected]
โ”‚     โ”‚   โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚   โ”‚ โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚   โ”‚ โ””โ”€โ”€ [email protected]
โ”‚     โ”‚   โ”œโ”€โ”€ [email protected]
โ”‚     โ”‚   โ””โ”€โ”€ [email protected]
โ”‚     โ””โ”€โ”ฌ [email protected]
โ”‚       โ””โ”€โ”ฌ [email protected]
โ”‚         โ””โ”€โ”€ [email protected]

getting Wrong API version error

I'm trying to add a contact and I keep getting a 400 error response:

var apiKey = process.env.MJ_APIKEY_PUBLIC,
apiSecret = process.env.MJ_APIKEY_PRIVATE,
mailjet = require( 'node-mailjet' ),
mj = mailjet.connect( apiKey, apiSecret );

mj.post( 'contact' )
.request( { Email: '[email protected]' } )
.on( 'success', ( response, body ) => {} )
.on( 'error', ( err, response ) => {
  console.log( response.statusCode );     // 400
  console.log( response.statusMessage );  // Wrong API version
} );

Offset filter not working

Hello,
I'm trying to get all the emails in a specific contact list that has more than 1000 contacts (max limit per request)
So I'm doing a second call with the Offset filter to retrieve the next contacts starting form the filter... and so on
Am I'm doing something wrong?

This is my code, the contact list has ~1270 contacts so this code should return ~270 contacts but instead is returning the same first 1000 results as if Offset filter wasn't presen

return nodeMailjet
            .get('contact')
            .request(
                {
                    "ContactsList": $id,
                    // 0 for max results (1000)
                    "Limit": 0,
                    "Offset": 1001
                }
            )
            .then((result) => {
                console.log(result.body.Data.length);
                console.log(result.body.Data)
            })
            .catch((err) => {
                console.log(err)
                return err;
            });

What does perform_api_call do really ?

I thought perform_api_call would simply return a fake response of some sort.

Instead, it seems the client is simply not responding at all, in which case this option is pointless because it makes my tests timeout.

  var MailJet = require ('node-mailjet');
  var client = MailJet.connect(credentials.user, credentials.pass, {
    url: 'api.mailjet.com',
    version: 'v3',
  });
  // Workaround for https://github.com/mailjet/mailjet-apiv3-nodejs/issues/46
  client.config.perform_api_call = perform;
  
  // API call
  console.log('Calling...');
  client
    .post("contact")
    .request({
      Email: '[email protected]'
    }, function(err, res) {
      console.log(err)
      console.log(res)
      console.log('Done.')
      cb(err);
    });

The code above only displays Calling.... Is there something wrong with it ? Otherwise could you clarify the use of this option ?

Cannot send email from Firebase Functions

I've started using Firebase Functions: https://firebase.google.com/features/functions/
It's basically a node.js server.

When I try to send an email, I get the following error response:

Error sending email: { Error: Unsuccessful
at /user_code/node_modules/node-mailjet/mailjet-client.js:202:23
at Request.callback (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:631:3)
at Stream.<anonymous> (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:795:18)
at emitNone (events.js:86:13)
at Stream.emit (events.js:185:7)
at Unzip.<anonymous> (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/utils.js:112:12)
at emitNone (events.js:91:20)
at Unzip.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
ErrorMessage: 'Internal Server Error',
statusCode: 500,
response: 
Response {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
res: 
IncomingMessage {
_readableState: [Object],
readable: false,
domain: null,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
socket: [Object],
connection: [Object],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Object],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 500,
statusMessage: 'Access violation',
client: [Object],
_consuming: true,
_dumped: false,
req: [Object],
setEncoding: [Function],
on: [Function],
text: '',
read: [Function],
body: undefined },
request: 
Request {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
_agent: false,
_formData: null,
method: 'POST',
url: 'https://api.mailjet.com/v3/send',
_header: [Object],
header: [Object],
writable: true,
_redirects: 0,
_maxRedirects: 5,
cookies: '',
qs: {},
qsRaw: [],
_redirectList: [],
_streamRequest: false,
_data: [Object],
req: [Object],
protocol: 'https:',
host: 'api.mailjet.com',
_callback: [Function],
res: [Object],
_timeout: 0,
response: [Circular],
called: true },
req: 
ClientRequest {
domain: null,
_events: [Object],
_eventsCount: 4,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: [Object],
_contentLength: 229,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'POST /v3/send HTTP/1.1\r\nHost: api.mailjet.com\r\nAccept-Encoding: gzip, deflate\r\nuser-agent: mailjet-api-v3-nodejs/3.0.6\r\nContent-type: application/json\r\nAuthorization: Basic N2EyZWIxOGNmM2I4YjExMGE2MGMyY2IzNjhhMjA2ZjA6NNlYmFhODY1MWUyYmViZjkyOGM0NzJmN2ZkYzA4YjY=\r\nContent-Length: 229\r\nConnection: close\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/v3/send',
_ended: true,
parser: null,
res: [Object] },
links: {},
text: '',
body: {},
files: undefined,
buffered: true,
headers: 
{ server: 'nginx',
date: 'Wed, 15 Mar 2017 07:22:34 GMT',
'content-type': 'text/html',
'content-length': '20',
connection: 'close',
vary: 'Accept-Encoding',
'content-encoding': 'gzip' },
header: 
{ server: 'nginx',
date: 'Wed, 15 Mar 2017 07:22:34 GMT',
'content-type': 'text/html',
'content-length': '20',
connection: 'close',
vary: 'Accept-Encoding',
'content-encoding': 'gzip' },
statusCode: 500,
status: 500,
statusType: 5,
info: false,
ok: false,
redirect: false,
clientError: false,
serverError: true,
error: 
{ Error: cannot POST /v3/send (500)
at Response.toError (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/response.js:106:13)
at Response._setStatusProperties (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/response.js:183:12)
at new Response (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/res

What can I do to fix this? I'm sending emails from the Java API successfully.

Here's the code I'm using to send the email:

const Mailjet = require('node-mailjet').connect(
    functions.config().mj_apikey.public,
    functions.config().mj_apikey.private
);

Mailjet.post('send').request(options).then(() => {
            console.log('Email sent to: ', email);
    }).catch(handleError);

Older Node compatibility

Running in an environment I can't control, which is on an older Node version (AFAIK it's 0.12).

The => syntax doesn't work, at least. Which is the minimum required version of Node?

How to get contact ID from its email ?

Hello,

I'm using the api with the Java SDK and I'm migrating my backend to NodeJS (using the Node SDK).

I can't find out how to get a contactId from its email.

Here is my Java working code :

public Integer getContactId(String email){
    	if(email != null){    			
			MailjetRequest request = new MailjetRequest(Contact.resource, email);    						
			try {
				JSONArray response = get(request);
				if(response.length() > 0){
					JSONObject o = response.getJSONObject(0);
					return (Integer)o.get("ID");
				}
				else{
					return null;
				}			
			} catch (Exception e) {
				e.printStackTrace();
				Logger.error("Error while calling getContactId");
				return null;
			}				
		}
		else{
			return null;
		}  		
    }

and here is my Node non-working code:

public static async getContactId(email: string): Promise<number> {
        if (!_.isNil(email) && email !== "") {
            return MailjetApiService.client()
                .get('contact')
                .request({
                    "Email": email,
                }).then((result) => {  
                    console.log(result.body.Data);                 
                    if (Array.isArray(result.body.Data) && result.body.Data.length > 0) {
                        return result.body.Data[0]["ContactID"];
                    }            
                }).catch((e) => {
                    console.log(e);
                    logger.error(e, "Error while calling getContactId");
                    return null;
                });
        }
        else {
            return null;
        }
    }

Indeed, with Node, the console.log of the output prints the list of the 10 first contacts of my Mailjet account. So the "Email" field is not filtering results.

What did I miss ?
Thank you

superagent: double callback bug

I see some error logs coming from mailjet. What is going on there?

superagent: double callback bug
{ Error: Unsuccessful
    at /srv/www/node_modules/node-mailjet/mailjet-client.js:220:23
    at Request.callback (/srv/www/node_modules/superagent/lib/node/index.js:718:3)
    at ClientRequest.req.once.err (/srv/www/node_modules/superagent/lib/node/index.js:646:10)
    at ClientRequest.g (events.js:292:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at TLSSocket.socketErrorListener (_http_client.js:309:9)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at onwriteError (_stream_writable.js:343:10)
    at onwrite (_stream_writable.js:361:5)
    at WritableState.onwrite (_stream_writable.js:90:5)
    at fireErrorCallbacks (net.js:467:13)
    at TLSSocket.Socket._destroy (net.js:508:3)
    at WriteWrap.afterWrite (net.js:802:10) ErrorMessage: 'write EPIPE', statusCode: null, response: null }

Send email with firebase functions (getaddrinfo ENOTFOUND api.mailjet.com api.mailjet.com:443)

Hi when I try to send an email I have this error :

{ Error: Unsuccessful at /user_code/node_modules/node-mailjet/mailjet-client.js:220:23 at Request.callback (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:688:3) at ClientRequest.<anonymous> (/user_code/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:615:10) at ClientRequest.g (events.js:292:16) at emitOne (events.js:96:13) at ClientRequest.emit (events.js:188:7) at TLSSocket.socketErrorListener (_http_client.js:309:9) at emitOne (events.js:96:13) at TLSSocket.emit (events.js:188:7) at connectErrorNT (net.js:1021:8) at _combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickDomainCallback (internal/process/next_tick.js:128:9) ErrorMessage: 'getaddrinfo ENOTFOUND api.mailjet.com api.mailjet.com:443', statusCode: null, response: null }

Error Handling OverHaul Needed!

I've used a lot of mailing APIs and I have to say this is the most frustrating to use.
The error handling is terribly non-descriptive.

I've been stuck on a "Error: Unsuccessful" (400: bad request) all day even though I have everything on point.
Even if am not, IT SHOULD BE OBVIOUS what I'm missing when looking at the error that comes back from your API. This is very lazy error handling.

I understand you guys use a Go backend. Error handling in Go can be quite involved, but it is possible. Please figure it out.

I'm basically at my last straw before moving to another email service. I'm sure many have done so already, I'm just nice enough to tell you first.

Connect() optional object being ignored?

I'm calling the connect method as in the README example:

// The third argument (the object) is not mandatory. Each configuration key is also optional
const mailjet = require ('node-mailjet')
    .connect(apiKey, apiSecret, {
        version: 'v3.1', // default is '/v3'
        perform_api_call: true // used for tests. default is true
      })

But the reply I get when sending the email has this structure:

{
  "Messages": [
    {
      "Status": "success", ...
      "To": [
        {
          "Email": "...",
          "MessageUUID": "0788ef45-716e-4d87-b735-04d134a59193",
          "MessageID": "70368744204343220",
          "MessageHref": "https://api.mailjet.com/v3/REST/message/70368744204343220"
        }
      ] ...
  ]
}

MessageHref shows a reference to API v3, instead of v3.1.

Also, if I set perform_api_call: false in the connect method (as the example from README), the email is still being delivered.
The API v3.1 reference mentions a different variable though:
https://dev.mailjet.com/guides/?javascript#sandbox-mode
But setting SandboxMode: true has the same effect: none. The email is still being delivered.

Am I doing something wrong? Or is it that the whole optional object is being ignored?
Thanks

Error on sending mails from Google Cloud Functions

Hi,
I am trying to configure mailjet on Google Cloud Functions, but I seem to always get this error:

Error: getaddrinfo ENOTFOUND api.mailjet.com api.mailjet.com:443
    at handleError (/user_code/index.js:15:11)
    at bound (domain.js:280:14)
    at runBound (domain.js:293:12)
    at tryCatcher (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/promise.js:689:18)
    at Async._drainQueue (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/user_code/node_modules/node-mailjet/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:637:20)
    at tryOnImmediate (timers.js:610:5)
    at processImmediate [as _immediateCallback] (timers.js:582:5)

Retrieve campaign title from campaign ID

Hi there,

I've been struggling to find a way to retrieve the campaign title given a campaign ID.

I would have expected to retrieve this property from the /campaign endpoint, but it's not available there (unlike the campaign subject, which is defined together with the campaign title on the UI, so it feels like this propriety has simply been forgotten).

The only place this "campaign title" property can be found is within the /campaignoverview/$ID endpoint, but the path to get there can get really messy. As you have to specify the IDType in addition to the $ID to get the resource, you have to consider the following cases :

  • When you retrieve the campaign from the campaign endpoint, the property "NewsLetterID" is equal to 0. That means you've got a campaign whose IDType is "Campaign", you can then retrieve the campaign title with this call : https://api.mailjet.com/v3/REST/campaignoverview/<CampaignID>?IDType=Campaign. If you get a 404, that means your campaign was actually a test or a transactional campaign.
  • When "NewsLetterID" is different from 0, you can either have an "AX" IDType or a "NL" one. To know in which case we are, we've to issue a request to https://api.mailjet.com/v3/REST/campaignstatistics/<CampaignID>. If the "AXTestingID" field is present, we've got an AX IDType, otherwise it's a NL one. The final request is then either https://api.mailjet.com/v3/REST/campaignoverview/<AXTestingID>?IDType=AX or https://api.mailjet.com/v3/REST/campaignoverview/<NewsLetterID>?IDType=NL

To put it in a nutshell: 2 sequential API calls in the best case scenario, 3 in the worst case. This really feels messy. Did I miss an obvious way of retrieving the campaign title from the campaign ID, or is this the best and only way offered by the API to accomplish this task?

Best regards,

Maxime

No email by template sent if from is empty

Hi,

Faced an issue with transactional emails. When I send an email with non-empty 'TemplateID' and empty 'From' I get the 200 OK response but no email on my mailbox. But all works as expected for the same setup and non-empty 'From' property.

This code doesn't work.

require('node-mailjet').connect('...', '...')
  .post('send', {'version': 'v3.1'})
  .request({
    Messages: [
      {
        To: [
          {
            Email: '...',
            Name: '...'
          }
        ],
        TemplateID: ...,
        TemplateLanguage: true,
        Variables: {
          ...
        }
      }
    ]
  })

But the same with 'From' works. Email, Name and Subject are set for the template.

Thanks!

Attachments

I have this array of attachments

[ { Filename: '2015-07-21-LiqRescateACyDI-InversorCLEAN.docx',
    'Content-type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    content: <Buffer 50 4b 03 04 14 00 08 08 08 00 af 38 3d 47 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 77 6f 72 64 2f 68 65 61 64 65 72 31 2e 78 6d 6c ed 59 5d 72 ... > },
  { Filename: 'Jaja.zip',
    'Content-type': 'application/zip',
    content: <Buffer 50 4b 03 04 14 00 08 08 08 00 dc 61 42 47 00 00 00 00 00 00 00 00 00 00 00 00 26 00 00 00 50 61 74 72 6f 6e 65 73 20 44 65 20 44 69 73 65 6e cc 83 6f ... > } ]

Without attachments, the mail is sent correctly. But with attachments the server respond with 500 status code and body = undefined. Do you have any idea of this?

Impossible to change the email of a contact in a list?

Hi there!

I'm scripting this use-case: "A user wants to change its email" and I want to change the email in our DB and providers all at once.

I just did it with Mailchimp and it was fast & easy but every time I want to do something with Mailjet's API either it's not clear or impossible..
Is that doable?

Can't resolve 'tls' -- Error on Mailjet connection

Hello,
I get this error while trying to connect to mailjet throwgh the node-mailjet library
Can't resolve 'tls'
I also got Can't resolve 'dns'
Anyone know how to resolve this issue ? My internet is working fine...

Thanks

Issue when trying to send variables for template language v3.1

Hi guys,

I have an issue sending template variables with v3.1 API:

So here it is:
I have template stored on your website with button HTML like:

<center>
    <a href="{{ var:userVerificationLink:"www.google.com" }}" class="btn-verify">
       Verify Address
    </a>
</center>

And I am sending API (v3.1, nodejs, npm:"node-mailjet": "3.2.1") request like this one:

"Messages ": [{
	"From ": {
		"Email ": "[email protected]",
		"Name ": "Some name"
	},
	"To": [{
		"Email ": "[email protected]",
		"Name ": "Some second"
	}],
	"TemplateID ": 1,
	"Variables": {
		"userVerificationLink": "http://localhost:8080/verify"
	}
}]

And my button in received HTML doesn't have at all href link, is there something else to add to this API call or?

3.3.0 not published ?

Hi,

3.3.0 is not published on npm.
We can't tests SMS API with this library.

Thanks !

Unable to set FALSE values for MailjetClient config

I wanted to set perform_api_call config variable for client:

require('node-mailjet').connect(apiKey, apiSecret, {
    perform_api_call: false
})

This variable is omitted in setConfig() which results with sending API requests.

Bug is located here:

if (options.url) config.url = options.url
if (options.version) config.version = options.version
if (options.secured) config.secured = options.secured
if (options.perform_api_call) config.perform_api_call = options.perform_api_call

setConfig() method will set values only when they're truthy.

Error: node_modules/json-bigint/lib/parse.js:112

Hi,

I tried this lib with a simple hardcoded exemple like below.
In the exemple I just replace the sensitive info by tokens like .
Trying it with node v4.2.4, I get the following error:

<PROJECT_PATH>/node_modules/node-mailjet/node_modules/json-bigint/lib/parse.js:112
            throw {
            ^
SyntaxError: Unexpected ''

Any idea on this one ?

The code:

var Mailjet = require('node-mailjet').connect('<MJ_APIKEY_PUBLIC>', '<MJ_APIKEY_PRIVATE>');

var emailData = {
  FromEmail: 'server@<MY_DOMAIN>',
  FromName: 'MV Studio',
  Subject: 'Test with the NodeJS Mailjet wrapper',
  'Text-part': 'Hello NodeJs !',
  Recipients: [{ Email: '<MY_EMAIL>' }],
  Attachments: []
};

var sendEmail = Mailjet.post('send');

sendEmail
.request(emailData)
.then(function (response) {
  console.log('Response', response);
})
.catch(function (err) {
  console.error('Error', err);
});

EventEmitter โ‰  Promise

Hi there,

I'm a bit confused with the documentation/readme :

Why would you say Make the same request with a promise or call it a promise when it's clearly not a promise ?

I would suggest to either go with promise and use something like petkaantonov/bluebird to return a thenable or stay with the EventEmitter pattern and stop advertising it as something it isn't.

I've made the required change for a proper Promise implementation (both code & test)
along with consistency fix (code style & line endings).
I've used standardjs as code style because it is what I use, but if you'd rather keep semicolons you can checkout semistandard and LF line endings instead of mixed CR & LF.

If you like it I can make a pull request, I've already bumped the major version in the package.json as moving away from EventEmitter is a breaking change.

Either way, thanks for putting together this package as a starting point for using Mailjet API :-)

global leaks in mailjet-client.js

Just pass it through eslint and you get lot of errors because of no-undef, which means in this case that variables are not declared with a var, let, or const, so they are globale

These variables are affected:

config
url
api_version
secured
perform_api_call

Question : delete a contact

Hi,

I have to sync a contacts list from our db to a MailJet contacts list.

In a specific case, I have to delete a contact from a contacts list.

On your documentation, I've seen the way to do that is to use the listrecipient entity.

But I didn't find what a way to get the listrecipient ID from a contact entity.

Or maybe we can proceed directly from contact entity ?

Thanks for your reply and have a nice day.

Version 3.1 is not ready but published

Version 3.1 is not among releases but is published on npm website. I noticed because of error in mailjet-client:116 where var is missing to initialize config variable.

Attachments

Is it possible to send mails with attachments using the node api?
If yes, could provide an example?

3.1.0 is including breaking changes without error and is a beta endpoint?!

Hi,

I'm really disappointed with the changes in the API, you did breaking changes without telling anybody.

The problem here is that I'm using "To" & "Bcc" old format SMTP style and it's not throwing an error when I use it with the latest v3.1.0 of node-mailjet. I only had people complaining that they didn't receive emails but that was weird for me as the "Bcc" email was sent to me successfully.

I just figured out the problem when I opened the API Guides and found that
https://dev.mailjet.com/beta/#send-api-v3-to-v3-1

To, Cc, Bcc	The SMTP style description of the recipients is replaced by a collection of recipients objects (with Email and Name property), nested in array.

Also the 3.1 is marked as BETA here, this is really confusing, you shouldn't use a BETA endpoint as people are using this library in production and without any notice!

Also the tests are too light for this library, only "Recipients" is tested and not "To" & "Bcc" (See https://dev.mailjet.com/guides/#sending-a-basic-email)

Please do better tests and throw an error if the "To" & "Bcc" are not correct instead of just sending half of the emails...

File Attachment

Hi,
Is there a way to attach a file to mail. I have been trying to follow the docs but was not able to do so.

My use case is, I have a file named- xyz.pdf on disk and I wish to attach this file in the mail and then send it.

const request = mailjet.post("send").request({
    "FromEmail":"[email protected]",
    "FromName":"Dummy",
    "Subject":"Your email flight plan!",
    "Text-part":"Dear passenger, welcome to Mailjet! May the delivery force be with you!",
    "Html-part":"<h3>Dear passenger, welcome to Mailjet!</h3><br />May the delivery force be with 
     you!",
    "To": "[email protected]",
    "Attachments": [{
       "Filename": 'xyz.pdf',
    }]
});

Not able to send email: Unsuccessful:(400)

Hi All,

I tried the demo code provided and I am facing an error.

This error only occurs when I use my paid account instead of test account.

This is my code:
`var mailjet = require ('./mailjet-client')
.connect('XXXXXXXXXXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXX')

function handleError (err) {
console.log(err);
throw new Error(err.ErrorMessage);
}

function newContact (email) {
mailjet.post('contact')
.request({Email: email})
.catch(handleError);
}

function testEmail (text) {
email = {};
email.FromName = 'Your Name';
email.FromEmail = 'Your Sender Address';
email.Subject = 'Test Email';
email.Recipients = [{Email: 'Your email'}];
email['Text-Part'] = text;

mailjet.post('send')
.request(email)
.catch(handleError);
}

testEmail('Hello World!');`

This is my Error:
Error: Unsuccessful at /home/lt-101/Folder/node_modules/node-mailjet/mailjet-client.js:220:23 at Request.callback (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:699:3) at /home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:868:18 at IncomingMessage.<anonymous> (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/parsers/json.js:16:7) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) ErrorMessage: 'Bad Request', statusCode: 400, response: Response { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, res: IncomingMessage { _readableState: [Object], readable: false, domain: null, _events: [Object], _eventsCount: 4, _maxListeners: undefined, socket: [Object], connection: [Object], httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, headers: [Object], rawHeaders: [Object], trailers: {}, rawTrailers: [], upgrade: false, url: '', method: null, statusCode: 400, statusMessage: 'Bad Request', client: [Object], _consuming: true, _dumped: false, req: [Object], text: '{"Errors":[{"ErrorIdentifier":"734c0518-b622-4a7f-999e-099d50cd032a","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromName"]},{"ErrorIdentifier":"7d57ed98-181e-47bb-a886-4a29ed4def91","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromEmail"]},{"ErrorIdentifier":"6a1767e1-6782-47af-a503-cc971d904857","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Subject"]},{"ErrorIdentifier":"7dcda3e0-398a-4b62-ad99-8673d154e4fb","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Recipients"]},{"ErrorIdentifier":"66027d33-1114-4c87-87ed-eb1bb634d841","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Text-Part"]},{"ErrorIdentifier":"6a4b9008-8652-4bc8-b120-b342c1c59c47","ErrorCode":"mj-0003","StatusCode":400,"ErrorMessage":"Missing mandatory property.","ErrorRelatedTo":["Messages"]}],"Messages":null}', read: [Function] }, request: Request { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, _agent: false, _formData: null, method: 'POST', url: 'https://api.mailjet.com/v3.1/send', _header: [Object], header: [Object], writable: true, _redirects: 0, _maxRedirects: 5, cookies: '', qs: {}, _query: [], qsRaw: [], _redirectList: [], _streamRequest: false, _data: [Object], req: [Object], protocol: 'https:', host: 'api.mailjet.com', _endCalled: true, _callback: [Function], res: [Object], response: [Circular], called: true }, req: ClientRequest { domain: null, _events: [Object], _eventsCount: 3, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: 160, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Object], connection: [Object], _header: 'POST /v3.1/send HTTP/1.1\r\nHost: api.mailjet.com\r\nAccept-Encoding: gzip, deflate\r\nuser-agent: mailjet-api-v3-nodejs/3.2.1\r\nContent-type: application/json\r\nAuthorization: Basic NWI2NmU3YmM3ZDQzNzM1ODEyOTA4YzMxMWEyNDI2YmE6NDM0NGU3MzI5YjgzZmM5Yzc5YjcwOTU2YTM0YzI0NjY=\r\nContent-Length: 160\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '/v3.1/send', _ended: true, parser: null, res: [Object] }, text: '{"Errors":[{"ErrorIdentifier":"734c0518-b622-4a7f-999e-099d50cd032a","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromName"]},{"ErrorIdentifier":"7d57ed98-181e-47bb-a886-4a29ed4def91","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromEmail"]},{"ErrorIdentifier":"6a1767e1-6782-47af-a503-cc971d904857","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Subject"]},{"ErrorIdentifier":"7dcda3e0-398a-4b62-ad99-8673d154e4fb","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Recipients"]},{"ErrorIdentifier":"66027d33-1114-4c87-87ed-eb1bb634d841","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Text-Part"]},{"ErrorIdentifier":"6a4b9008-8652-4bc8-b120-b342c1c59c47","ErrorCode":"mj-0003","StatusCode":400,"ErrorMessage":"Missing mandatory property.","ErrorRelatedTo":["Messages"]}],"Messages":null}', body: { Errors: [Object], Messages: null }, files: undefined, buffered: true, headers: { 'content-length': '1049', 'content-type': 'application/json; charset=UTF-8', date: 'Mon, 11 Sep 2017 17:05:58 GMT', connection: 'close' }, header: { 'content-length': '1049', 'content-type': 'application/json; charset=UTF-8', date: 'Mon, 11 Sep 2017 17:05:58 GMT', connection: 'close' }, statusCode: 400, status: 400, statusType: 4, info: false, ok: false, redirect: false, clientError: true, serverError: false, error: { Error: cannot POST /v3.1/send (400) at Response.toError (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/response.js:94:13) at ResponseBase._setStatusProperties (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/response-base.js:122:16) at new Response (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/response.js:40:8) at Request._emitResponse (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:723:20) at /home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/index.js:868:38 at IncomingMessage.<anonymous> (/home/lt-101/Folder/node_modules/node-mailjet/node_modules/superagent/lib/node/parsers/json.js:16:7) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at _combinedTickCallback (internal/process/next_tick.js:74:11) at process._tickCallback (internal/process/next_tick.js:98:9) status: 400, text: '{"Errors":[{"ErrorIdentifier":"734c0518-b622-4a7f-999e-099d50cd032a","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromName"]},{"ErrorIdentifier":"7d57ed98-181e-47bb-a886-4a29ed4def91","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["FromEmail"]},{"ErrorIdentifier":"6a1767e1-6782-47af-a503-cc971d904857","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Subject"]},{"ErrorIdentifier":"7dcda3e0-398a-4b62-ad99-8673d154e4fb","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Recipients"]},{"ErrorIdentifier":"66027d33-1114-4c87-87ed-eb1bb634d841","ErrorCode":"send-0001","StatusCode":400,"ErrorMessage":"Not a valid property.","ErrorRelatedTo":["Text-Part"]},{"ErrorIdentifier":"6a4b9008-8652-4bc8-b120-b342c1c59c47","ErrorCode":"mj-0003","StatusCode":400,"ErrorMessage":"Missing mandatory property.","ErrorRelatedTo":["Messages"]}],"Messages":null}', method: 'POST', path: '/v3.1/send' }, accepted: false, noContent: false, badRequest: true, unauthorized: false, notAcceptable: false, forbidden: false, notFound: false, type: 'application/json', charset: 'UTF-8', links: {}, setEncoding: [Function: bound ], redirects: [] } }

Thank you.

Error 408 on sending emails

Hi,

Faced an issue with transactional emails, when I send more than 10 emails. If in my loop I have more than 10 mails, I get error 408. Here is my code:

for (let index in listUsers) {
                var original = listUsers[index];
                const mailjet = require("node-mailjet").connect("xxx", "xxx");
                const userLink = appLink + "welcome-to-fiitli/" + index;

                const request = mailjet
                    .post("send")
                    .request({
                        "FromEmail": "[email protected]",
                        "FromName": "Fiitli",
                        "Subject": "Activez votre compte Fiitli :)",
                        "MJ-TemplateID": "220432",
                        "MJ-TemplateLanguage": "true",
                        "Vars": {
                            "username": original.userMail,
                            "userLink": userLink
                        },
                        "Recipients": [{
                            "Email": original.userMail
                        }]
                    })
                request
                    .then(result => {
                        console.log("Mail send to : " + index + " - " + original.userMail);
                        console.log(result.body);
                    })
                    .catch(err => {
                        console.log(err.statusCode);
                    })

            }

Server : nodejs, firebase functions. (with "Blaze premium")

Do you have any idea to solve this problem?

Thanks !

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.