Security News
Opengrep Emerges as Open Source Alternative Amid Semgrep Licensing Controversy
Opengrep forks Semgrep to preserve open source SAST in response to controversial licensing changes.
node-mailjet
Advanced tools
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.
This library officially supports the following Node.JS
versions:
v12.x
Install the SDK use the following code:
npm install node-mailjet
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 API
the authorization is based on a Bearer token.
See information about it in the SMS API section of the readme.
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'
});
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: {}
}
);
For SMS API
you can use static method smsConnect
:
const mailjet = Mailjet.smsConnect(
process.env.MJ_API_TOKEN,
{
config: {},
options: {}
}
);
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: "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 <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)
})
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)
METHOD
: the method you want to use for this call (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)options
have this structure:
requestHeaders
- associative array describing custom header fields which you can pass to the requesttimeout
- sets maximum time to wait for the first byte to arrive from the server, but it does not limit how long the entire download can takeproxyUrl
- sets a HTTPS
proxy URL to direct all requests to a specific URLYou 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: {
requestHeaders: {
'X-API-Key': 'foobar'
},
timeout: 1000,
proxyUrl: 'www.test-proxy.com'
}
});
You are able to set a timeout for your request using the timeout
parameter.\
The timeout
parameter describe maximum time to wait for the first byte to arrive from the server, but it does not limit how long the entire download can take.
The API request timeout
is set in milliseconds:
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' })
You are able to set a custom headers for your request using the requestHeaders
parameter.
const mailjet = new Mailjet({
apiKey: process.env.MJ_APIKEY_PUBLIC,
apiSecret: process.env.MJ_APIKEY_PRIVATE,
options: {
requestHeaders: {
'API-Key': 'foobar',
Accept: 'application/json',
'Content-Type': 'application/json'
}
}
});
const request = mailjet
.post('send', { version: 'v3.1' })
The proxyUrl
parameter allows you to set a HTTPS
proxy URL to send the API requests through:
const mailjet = new Mailjet({
apiKey: process.env.MJ_APIKEY_PUBLIC,
apiSecret: process.env.MJ_APIKEY_PRIVATE,
options: {
proxyUrl: 'YOUR_PROXY_URL'
}
});
const request = mailjet
.post('send', { version: 'v3.1' })
The proxy URL is passed directly to superagent.connect() as:
if (clientOptions.proxyUrl) {
request.connect({ '*': clientOptions.proxyUrl });
}
NOTE:
This parameter worked only on the node side because inNode.JS
it's possible to ignore DNS resolution and direct all requests to a specific IP address.
config
have this structure:
host
- sets custom host URLversion
- sets required version of API for determinate endpoint (set of v3
, v3.1
, v4
)output
- sets the Accept
headerYou 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: 'new.api.mailjet',
version: 'v3.1',
output: 'xml',
}
});
And for each request
manually (this config
will have more precedence than passed in client
):
const request = mailjet
.post('send', {
host: 'new.api.mailjet',
version: 'v3.1',
output: 'json',
})
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 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 request = mailjet
.post('send', { version: 'v3.1' })
For additional information refer to our API Reference.
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
.
The default accepted output for the Mailjet API is json
.
You can modify this accepted output data by setting a value for output
in your call:
const request = mailjet
.post('send', { version: 'v3.1', output: 'xml' })
The output
parameter allowing you to specify either the full canonicalized MIME type name as type/subtype
or the extension suffix form as xml
, json
, png
, etc.
For more detailed information and set of supported output
values visit this doc.
NOTE:
Keep in mind that not all passed values tooutput
property will correctly execute by Mailjet server.
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 second argument with value false
to .request(data, performAPICall)
method:
const request = mailjet
.post('send', { version: 'v3.1' })
.request({}, false)
At the moment library based on TypeScript
and provide generic method Request.request<TResult>(data)
:
import Mailjet from 'node-mailjet'
const mailjet = new Mailjet({
apiKey: process.env.MJ_APIKEY_PUBLIC,
apiSecret: process.env.MJ_APIKEY_PRIVATE
});
interface IContract {
IsExcludedFromCampaigns: boolean;
Name: string;
CreatedAt: string;
DeliveredCount: number;
Email: string;
}
type TResponse<TEntity> = {
Count: number;
Total: number;
Data: Array<TEntity>
}
const request = mailjet
.get('contact')
.request<TResponse<IContract>>()
And response
will have this shape:
{
response: Response;
body: {
Count: number;
Total: number;
Data: Array<{
IsExcludedFromCampaigns: boolean;
Name: string;
CreatedAt: string;
DeliveredCount: number;
Email: string;
}>;
}
}
But at the moment library don't provide a types for Mailjet API only for library level. But we work on it.
For now or for earlier versions 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.
For this 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/
List of basic applications that was built in different environments:
RequireJS
and provide page where you can make some requestsExpressJS
based app that allow to retrieve list of contacts and send email to some personReactJS
based app that provide page where you can make some requestsNOTE: For
browser
side examples at the moment a proxy is required to communicate with the Mailjet API due to CORS limitations.
POST
RequestUse the post
method of the Mailjet client:
const request = mailjet
.post($RESOURCE, $CONFIG)
.id($ID)
.request($DATA)
.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.
POST
requestCreate 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: "passenger@mailjet.com",
IsExcludedFromCampaigns: "true",
Name: "New Contact"
})
request
.then((result) => {
console.log(result.body)
})
.catch((err) => {
console.log(err.statusCode)
})
actions
Manage the subscription status of a contact to multiple lists:
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')
.id($contactID)
.action('managecontactslists')
.request({
ContactsLists: [
{
ListID: $listID,
Action: "addnoforce"
}
]
})
request
.then((result) => {
console.log(result.body)
})
.catch((err) => {
console.log(err.statusCode)
})
GET
RequestUse the get
method of the Mailjet client:
const request = mailjet
.get($RESOURCE, $CONFIG)
.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 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)
})
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 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
RequestUse the put
method of the Mailjet client:
const request = mailjet
.put($RESOURCE, $CONFIG)
.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.
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
RequestUse the delete
method of the Mailjet client:
const request = mailjet
.delete($RESOURCE, $CONFIG)
.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.
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)
})
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);
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)
})
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:
If you have suggestions on how to improve the guides, please submit an issue in our Official API Documentation repo.
Node.JS
>= 4.xInit package with:
npm run init
Where the init
script contain all essential init steps:
npm install
- install all dependenciesnpm run ts:patch
- patch TS
compiler for correct building TypeScript
declaration filesnpm run pkg:prepare
- husky
install for git hooks
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
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.
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
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.
4.0.0 (2022-06-10)
FAQs
Mailjet API client
The npm package node-mailjet receives a total of 68,979 weekly downloads. As such, node-mailjet popularity was classified as popular.
We found that node-mailjet demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Opengrep forks Semgrep to preserve open source SAST in response to controversial licensing changes.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.