mailjet/mailjet-apiv3-nodejs
About
[API v3] Official Mailjet API v3 NodeJS wrapper
Productivity & AutomationMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Original
Mailjet JS
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
- Development
Documentation
Compatibility
This library officially supports the following Node.JS versions:
- >=
v12.x
Upgrading to v7
Version 7.0.0 includes breaking changes. See the CHANGELOG for the full list, in short:
package.jsonnow declares anexportsmap. Onlyrequire('node-mailjet')/import ... from 'node-mailjet'are supported entry points — deep imports such asrequire('node-mailjet/dist/mailjet.node.js')will no longer resolve..id()now throws if called after.action()instead of silently building an incorrect URL. Call.id()before.action().PUTrequests to thecontactdataresource now throw synchronously ifDatais missing, not an array, or contains entries withoutName/Valuekeys, instead of only failing with a server-side400.- Requests now time out after
30sby default instead of hanging indefinitely. Passoptions.timeoutto configure a different value (see Request timeout).
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 theSMS APIthe 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');
The package also works with native ESM, including named imports:
import Mailjet, { Client } from '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 callOPTIONS: 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 forpost,put,deletemethods)PARAMS: are the URL parameters to be sent with the requestPERFORM_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 requesttimeout- specifies the number of milliseconds before the request times outproxy- 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 theNodeJSside
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 theNodeJSside
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 theNodeJSside
Config
config have this structure:
host- sets custom host URLversion- sets required version of API for determinate endpoint (set ofv3,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- TheEmail APIv3.1- TheEmail Send API v3.1, which is the latest version of ourSend APIv4- TheSMS 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' })
NOTE:
All requests are sent over HTTPS only.hostmust be a host name without a scheme; a value starting withhttp://throws an error, and redirects to non-HTTPS URLs are not followed.
If your account has been moved to Mailjet's
USarchitecture, thehostvalue you need to set isapi.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:
arraybufferdocumentjson(Default)textstreamblob(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;
...
}>;
}
}
Batch sending & partial failures
The Send API v3.1 lets you submit multiple emails in a single request via the Messages array (this is often called "batch sending").
Batch sending is not an atomic operation. Each entry in Messages is validated and processed independently, so a single request can return a mix of successful and failed messages. A 2xx HTTP response only means Mailjet accepted the request for processing — it does not mean every message in the batch was sent, and a message failure elsewhere in the batch does not stop the rest of the messages from being processed.
Because of this, you should never assume the batch either "all succeeded" or "all failed". Instead, inspect the Status of each entry in result.body.Messages:
Status: 'success'— the message was accepted and is being delivered.Status: 'error'— the message failed; details are available in that entry'sErrorsarray (ErrorCode,ErrorMessage,ErrorIdentifier).
Set AdvanceErrorHandling: true on the request body to get one Errors entry per validation problem with machine-readable ErrorCode/ErrorIdentifier fields, which makes it easier to decide programmatically what happened and what, if anything, is safe to retry.
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]' }],
Subject: 'Your flight plan (1)',
TextPart: 'This message is expected to succeed.',
CustomID: 'order-1001', // used below to correlate request <-> response
},
{
From: { Email: '[email protected]' },
To: [{ Email: 'not-a-valid-address' }],
Subject: 'Your flight plan (2)',
TextPart: 'This message is expected to fail.',
CustomID: 'order-1002',
},
],
AdvanceErrorHandling: true,
};
const result: LibraryResponse<SendEmailV3_1.Response> = await mailjet
.post('send', { version: 'v3.1' })
.request(data);
const succeeded = result.body.Messages.filter((message) => message.Status === 'success');
const failed = result.body.Messages.filter((message) => message.Status !== 'success');
// `failed` here does NOT mean the axios `.catch()`/promise rejection fired -
// the request itself succeeded, but some individual messages did not.
})();
Retry guidance (avoiding duplicate sends)
Because a batch can partially succeed, blindly retrying the whole request (or the whole Messages array) on any failure can resend messages that already succeeded, causing duplicate emails. To retry safely:
- Give every message a unique
CustomIDwhen you first send it, and keep a record of it (e.g. tied to your order/notification ID) before the request is made. - On response, only collect the messages whose
Statusis'error'— never re-include messages whoseStatuswas'success'. - Use the failed message's
Errors[].StatusCode/ErrorCodeto decide if it's worth retrying:- Validation-type errors (invalid recipient, malformed address, blocked domain, etc.) will fail again unless the message content itself is fixed — retrying unmodified is not useful.
- Transient/server-side errors (
StatusCode >= 500) may succeed on retry.
- When you do retry, resubmit only the failed messages, reusing the same
CustomID, so you (and Mailjet's logs) can correlate the retry with the original attempt. - Treat a request-level rejection (a thrown/rejected promise from
.request(), e.g. network failure, auth failure, malformed payload) differently from a per-messageStatus: 'error'— the former means Mailjet never processed the batch at all, so the entireMessagesarray is safe to retry as-is.
See
examples/node/src/batchSend.jsfor a runnable example that sends a batch with one message designed to fail, and shows how to separate successes from failures and decide what to retry.
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;
...
}>;
}
}
Delete Contact Example
Contact deletion (GDPR-compliant) uses a dedicated v4 endpoint, so the resource name must be the plural contacts and the version must be set to v4:
import { Client } from 'node-mailjet'
const mailjet = new Client({
apiKey: process.env.MJ_APIKEY_PUBLIC,
apiSecret: process.env.MJ_APIKEY_PRIVATE
});
(async () => {
const ContactID = 3860384733;
await mailjet
.delete('contacts', { version: 'v4' })
.id(ContactID)
.request();
})();
See the Delete a Contact API reference for more details.
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:
- Browser - Basic app that using
RequireJSand provide page where you can make some requests - Node - Basic app that contain simple scripts with some requests
- Sendmail -
ExpressJSbased app that allows to retrieve list of contacts and send email to some person - ReactJS -
ReactJSbased app that provides page where you can make some requests - Firebase -
Firebasebased app that providesFirebase Functionsfor sending hello world email and sending email based on dynamic query string data
NOTE: For
browserside 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)
})
Note:
For thecontactandcontactdataresources,.id()also accepts a contact's email address instead of its numeric ID (e.g..id('[email protected]')). Pass it as-is — the SDK does not URL-encode it, matching what the Mailjet REST API expects.
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:
Each entry in Data must be an object with Name and Value keys, where Name matches
a property already defined via /contactmetadata.
Sending the property name/value directly (e.g. { first_name: "John" }) instead of
{ Name: "first_name", Value: "John" } will make the API respond with an Invalid key name error.
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: [
{
Name: "first_name",
Value: "John"
},
{
Name: "last_name",
Value: "Smith"
}
]
})
request
.then((result) => {
console.log(result.body)
})
.catch((err) => {
console.log(err.statusCode)
})
Update a template's editable content (the HTML/text/MJML shown in the Passport editor and the Mailjet App):
Note:
PUT/POSTon thetemplateresource itself only updates metadata (Name,Categories,Purposes, ...).
It does not touch the template's body, so changes made that way will show up in aGET templateresponse but never in the Mailjet App editor. To update the actual content, target thetemplate/$ID/detailcontentsub-resource via.id($templateID).action('detailcontent')— and note that.id()must be called before.action(); calling it after throws (see Upgrading to v7).
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('template')
.id($templateID)
.action('detailcontent')
.request({
'Html-part': '<html><body><p>Hello {{var:name}}</p></body></html>',
'Text-part': 'Hello {{var:name}}'
})
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)
})
Note:
A204here (and a subsequent404onGET template/$templateID) confirm the template was removed API-side. If the template still appears in the Mailjet App afterwards, that's a discrepancy between the API and the App UI, not something the request/response here can detect or control - see issue #278.
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:
npm install- install all dependenciesnpm run ts:patch- patchTScompiler for correct buildingTypeScriptdeclaration filesnpm run pkg:prepare-huskyinstall forgit 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:patchnpm run release:minornpm 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.
Explore related projects
Loading…