Code Monkey home page Code Monkey logo

mailjet-apiv3-nodejs's Introduction

alt text

Mailjet NodeJs Wrapper

Build Status Current Version

Overview

Welcome to the Mailjet official NodeJs API wrapper!

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

Table of contents

Compatibility

This library officially supports the following Node.js versions:

  • v4.1
  • v4.0
  • v5.0.0
  • v6.11.1

Installation

First, create a project folder:

mkdir mailjet-project && cd $_

Then use the following code to install the wrapper:

npm install node-mailjet

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

Authentication

The Mailjet Email API uses your API and Secret keys for authentication. Grab and save your Mailjet API credentials.

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

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.

Initialize your Mailjet Client:

const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)

Make your first call

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

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": "[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)
    })

Client / Call configuration specifics

To instantiate the library you can use the following constructor:

const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .METHOD(RESOURCE, {OPTIONS})
  • MJ_APIKEY_PUBLIC : public Mailjet API key
  • MJ_APIKEY_PRIVATE : private Mailjet API key
  • METHOD - the method you want to use for this call (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)

Options

API Versioning

The Mailjet API is spread among three distinct versions:

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

Since most Email API endpoints are located under v3, it is set 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. For example, if using Send API 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'})

For additional information refer to our API Reference.

Base URL

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

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

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

Request timeout

You are able to set a timeout for your request using the timeout parameter. The API request timeout is set in milliseconds:

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

Use proxy

The proxyUrl parameter allows you to set a HTTPS proxy URL to send the API requests through:

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

The proxy URL is passed directly to superagent-proxy.

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 setting the perform_api_call parameter to false:

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

Request examples

POST Request

Use the post method of the Mailjet Client:

const request = mailjet
  .post($RESOURCE, {$OPTIONS})
  .id($ID)
  .request({$PARAMS})

.request 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')
	.connect(process.env.MJ_APIKEY_PUBLIC, 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 mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.post("contact")
	.id($contact_ID)
	.action("managecontactslists")
	.request({
    "ContactsLists": [{
			"ListID": 987654321,
			"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, {$OPTIONS})
 .id($ID)
 .request({$PARAMS})

.request 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')
	.connect(process.env.MJ_APIKEY_PUBLIC, 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')
	.connect(process.env.MJ_APIKEY_PUBLIC, 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 ID :
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.get("contact")
	.id(Contact_ID)
	.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, {$OPTIONS})
 .id($ID)
 .request({$PARAMS})

You need to define .id to specify the object you need to edit. .request 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.

Here's an example of a PUT request:

/**
 *
 * Update the contact properties for a contact:
 *
 */
const mailjet = require ('node-mailjet')
    .connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
    .put("contactdata")
    .id($CONTACT_ID)
    .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, {$OPTIONS})
 .id($ID)
 .request()

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

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

Here's an example of a DELETE request:

/**
 *
 * Delete : Delete an email template.
 *
 */
const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_APIKEY_PUBLIC, process.env.MJ_APIKEY_PRIVATE)
const request = mailjet
	.delete("template")
	.id(Template_ID)
	.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.

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

Example request

Here's an example SMS API request:

const mailjet = require ('node-mailjet')
	.connect(process.env.MJ_TOKEN)
const request = mailjet
    .post("sms-send", {'version': 'v4'})
    .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)
	})

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.

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

mailjet-apiv3-nodejs's People

Contributors

mskochev avatar eboisgon avatar p-j avatar arnaudbreton avatar katafractari avatar yankovanov-sc avatar timaschew avatar ceer avatar emmanuelgautier avatar jordaaash avatar nickewansmith avatar ngarnier avatar fadomire avatar farvilain avatar

Watchers

James Cloos avatar

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.