tefra / mailjet-apiv3-nodejs

[API v3] Official Mailjet API v3 NodeJS wrapper

Home Page:https://dev.mailjet.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

alt text

Build Status Current Version

Mailjet NodeJs Wrapper

Welcome to the Mailjet official NodeJS API wrapper!

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

(Please refer to the Mailjet Documentation Repository, in case you want to contribute to the documentation)

Getting started

First, create a project folder:

mkdir mailjet-project && cd $_

Installation

npm install node-mailjet

If you want to do a global installation, add the -g flag.

Show me the code

To authenticate, go get your API Key and API Secret here. Then open your favorite text editor and import the Mailjet module:

var Mailjet = require('node-mailjet').connect('api key', 'api secret');

Additional connection options may be specified as a third argument. The supported values are:

  • proxyUrl: HTTP proxy URL to send the API requests through
  • timeout: API request timeout in milliseconds
  • url (default: api.mailjet.com): Base Mailjet API URL
  • version: API version to use in the URL
    • v3 - The Email API
    • v3.1 - Email Send API v3.1, which is the latest version of our Send API
    • v4 - SMS API
  • perform_api_call (default: true): controls if the must call must be performed to Mailjet API or not (dry run)
// The third argument (the object) is not mandatory. Each configuration key is also optional
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE, {
        url: 'api.mailjet.com', // default is the API url
        version: 'v3.1', // default is '/v3'
        perform_api_call: true // used for tests. default is true
      })

On top of that, you can also pass those options locally to a request:

// the second argument (the object) is not mandatory. Each configuration key is also optional
const request = mailjet
    .post("send", {
      url: 'api.mailjet.com', version: 'v3.1', perform_api_call: false
    })
    .request({
        "Messages":[
                {
                "From": {
                        "Email": "pilot@mailjet.com",
                        "Name": "Mailjet Pilot"
                },
                "To": [
                        {
                        "Email": "passenger1@mailjet.com",
                        "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 Mailjet!</h3><br />May the delivery force be with you!"
                }
        ]
    })

The proxy URL is passed directly to superagent-proxy.

Get cozy with Mailjet

Save and use your API Keys

echo 'export MJ_APIKEY_PUBLIC=MY_API_KEY' >> ~/.zshrc

echo 'export MJ_APIKEY_PRIVATE=MY_API_SECRET' >> ~/.zshrc

source ~/.zshrc

Replace zshrc with bash_profile if you are simply using bash.

Then use it in your projects:

var apiKey = process.env.MJ_APIKEY_PUBLIC,
  apiSecret = process.env.MJ_APIKEY_PRIVATE;

Store a Mailjet resource

// GET resource
var user = Mailjet.get('user');

// POST resource
var sender = Mailjet.post('sender');

Request your resource with a callback function

user.request(function (error, response, body) {
  if (error)
    console.log ('Oops, something went wrong ' + response.statusCode);
  else
    console.log (body);
});

Make the same request with a Promise

user.request()
  .then(function (result) {
    // do something with the result
    // result structure is {response: {...}, body: {...}}
  })
  .catch(function (reason) {
    // handle the rejection reason
    console.log(reason.statusCode)
  })

Pass data to your requests

sender.request({ Email: 'mr@mailjet.com' })
  .then(handleData)
  .catch(handleError);

Pass parameters as well as a callback

var getContacts = Mailjet.get('contact');

getContacts.request({Limit: 3}, handleContacts);

Request a resource with an ID

getContacts.id(2).request(handleSingleContact)

Request a ressource with an Action

var postContact = Mailjet.post('contact');

postContact.action('managemanycontacts').request({
  ContactLists: MyContactListsArray,
    Contacts: MyContactsArray,
}, handlePostResponse)

Send an Email

var sendEmail = Mailjet.post('send', {'version': 'v3.1'});

var emailData = {
    "Messages":[{
        "From": {
            "Email": "pilot@mailjet.com",
            "Name": "Mailjet Pilot"
          },
        "To": [{
            "Email": "passenger1@mailjet.com",
            "Name": "passenger 1"
          }],
        'Subject': 'Test with the NodeJS Mailjet wrapper',
        'Text-part': 'Hello NodeJs !',
        'Attachments': [{
            "Content-Type": "text-plain",
            "Filename": "test.txt",
            "Content": "VGhpcyBpcyB5b3VyIGF0dGFjaGVkIGZpbGUhISEK", // Base64 for "This is your attached file!!!"
          }]
    }]    
}

sendEmail
  .request(emailData)
    .then(handlePostResponse)
    .catch(handleError);

You can also use the previous version of Mailjet's Send API (v3). You can find the documentation explaining the overall differences and code samples here.

Send two Emails

var sendEmail = Mailjet.post('send', {'version': 'v3.1'});

const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .post("send", {'version': 'v3.1'})
    .request({
        "Messages":[
                {
                "From": {
                        "Email": "pilot@mailjet.com",
                        "Name": "Mailjet Pilot"
                },
                "To": [
                        {
                        "Email": "passenger1@mailjet.com",
                        "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 Mailjet!</h3><br />May the delivery force be with you!"
                },
                {
                "From": {
                        "Email": "pilot@mailjet.com",
                        "Name": "Mailjet Pilot"
                },
                "To": [
                        {
                        "Email": "passenger2@mailjet.com",
                        "Name": "passenger 2"
                        }
                ],
                "Subject": "Your email flight plan!",
                "TextPart": "Dear passenger 2, welcome to Mailjet! May the delivery force be with you!",
                "HTMLPart": "<h3>Dear passenger 2, welcome to Mailjet!</h3><br />May the delivery force be with you!"
                }
        ]
    })
request
    .then((result) => {
        console.log(result.body)
    })
    .catch((err) => {
        console.log(err.statusCode)
    })

Have Fun !

var mailjet = require ('./mailjet-client')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)

function handleError (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!');

SMS API

IMPORTANT

In mailjet-client v4 we have introduced a new Bearer Token authentication method for the SMS API. You can generate a token from the SMS Dashboard in the Mailjet app.

var Mailjet = require('node-mailjet').connect('api token');

Additional connection options may be passed as a second argument. The supported values are:

  • proxyUrl: HTTP proxy URL to send the API requests through
  • timeout: API request timeout in milliseconds
  • url (default: api.mailjet.com): Base Mailjet API URL
  • version (default: v3): API version to use in the URL
  • perform_api_call (default: true): controls if the must call must be performed to Mailjet API or not (dry run)
// The second argument (the object) is not mandatory. Each configuration key is also optional
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_API_TOKEN, {
        url: 'api.mailjet.com', // default is the API url
        version: 'v4', // default is '/v3'
        perform_api_call: true // used for tests. default is true
      })

We kept all other functionalities unchanged

Get cosy with Mailjet SMS

Save your API_TOKEN:

echo 'export MJ_API_TOKEN=MY_API_TOKEN' >> ~/.zshrc

source ~/.zshrc

replace zshrc with bash_profile if you are simply using bash

And use it in your projects

var apiToken = process.env.MJ_API_TOKEN;

Store SMS resource

// GET resource
var sms = Mailjet.get('sms');

// POST resource
var sendSms = Mailjet.post('sms-send');

Send SMS

var smsSend = Mailjet.post('sms-send');

var smsData = {
    'Text': 'Have a nice SMS flight with Mailjet !',
    'To': '+33600000000',
    'From': 'MJPilot'
}

smsSend
  .request(smsData)
    .then(handlePostResponse)
    .catch(handleError);

Run Test

npm test

Node.js compatibility

Officially supported Node.js versions:

  • v0.12.0 (deprecated)
  • v4.1
  • v4.0
  • v5.0.0
  • v6.11.1

Contribute

Mailjet loves developers. You can be part of this project!

This wrapper 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.

TODO:

  • Extend Error class to create Api errors

About

[API v3] Official Mailjet API v3 NodeJS wrapper

https://dev.mailjet.com

License:MIT License


Languages

Language:JavaScript 100.0%