Gathering detailed insights and metrics for mailgun-js
Gathering detailed insights and metrics for mailgun-js
Gathering detailed insights and metrics for mailgun-js
Gathering detailed insights and metrics for mailgun-js
@types/mailgun-js
TypeScript definitions for mailgun-js
mailgun-js-sdk
A simple node mailgun sdk
mailgun-js-audit
Simple Node.js helper module for Mailgun API - Fix Audit issues
@octonary/mailgun-js
Simple Node.js helper module for Mailgun API. Forked to fix IE issues with ` character.
npm install mailgun-js
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
894 Stars
321 Commits
121 Forks
17 Watchers
25 Branches
41 Contributors
Updated on Jun 24, 2025
Latest Version
0.22.0
Package Id
mailgun-js@0.22.0
Size
14.59 kB
NPM Version
6.4.1
Node Version
10.12.0
Published on
Oct 26, 2018
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
Simple Node.js module for Mailgun.
npm install mailgun-js
This is a simple Node.js module for interacting with the Mailgun API. This module is intended to be used within Node.js environment and not from the browser. For browser use the mailgun.js module.
Please see Mailgun Documentation for full Mailgun API reference.
This module works by providing proxy objects for interacting with different resources through the Mailgun API.
Most methods take a data
parameter, which is a Javascript object that would contain the arguments for the Mailgun API.
All methods take a final parameter callback with two parameters: error
, and body
.
We try to parse the body
into a javascript object, and return it to the callback as such for easier use and inspection by the client.
If there was an error a new Error
object will be passed to the callback in the error
parameter.
If the error originated from the (Mailgun) server, the response code will be available in the statusCode
property
of the error
object passed in the callback.
See the /docs
folder for detailed documentation. For full usage examples see the /test
folder.
1var api_key = 'XXXXXXXXXXXXXXXXXXXXXXX'; 2var domain = 'www.mydomain.com'; 3var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 4 5var data = { 6 from: 'Excited User <me@samples.mailgun.org>', 7 to: 'serobnic@mail.ru', 8 subject: 'Hello', 9 text: 'Testing some Mailgun awesomeness!' 10}; 11 12mailgun.messages().send(data, function (error, body) { 13 console.log(body); 14});
Note that the to
field is required and should be a string containing 1 or more comma-separated addresses. Additionally cc
and bcc
fields can be specified. Recipients in those fields will be addressed as such. See https://documentation.mailgun.com/api-sending.html#sending for additional details.
Messages stored using the Mailgun store()
action can be retrieved using messages(<message_key>).info()
function.
Optionally the MIME representation of the message can be retrieved if MIME
argument is passed in and set to true
.
Something more elaborate. Get mailing list info, create a member and get mailing list members and update member. Notice that the proxy objects can be reused.
1var list = mailgun.lists('mylist@mycompany.com'); 2 3list.info(function (err, data) { 4 // `data` is mailing list info 5 console.log(data); 6}); 7 8var bob = { 9 subscribed: true, 10 address: 'bob@gmail.com', 11 name: 'Bob Bar', 12 vars: {age: 26} 13}; 14 15list.members().create(bob, function (err, data) { 16 // `data` is the member details 17 console.log(data); 18}); 19 20list.members().list(function (err, members) { 21 // `members` is the list of members 22 console.log(members); 23}); 24 25list.members('bob@gmail.com').update({ name: 'Foo Bar' }, function (err, body) { 26 console.log(body); 27}); 28 29list.members('bob@gmail.com').delete(function (err, data) { 30 console.log(data); 31});
Mailgun
object constructor options:
apiKey
- Your Mailgun API KEYpublicApiKey
- Your public Mailgun API KEYdomain
- Your Mailgun Domain (Please note: domain field is MY-DOMAIN-NAME.com
, not https://api.mailgun.net/v3/MY-DOMAIN-NAME.com)mute
- Set to true
if you wish to mute the console error logs in validateWebhook()
functionproxy
- The proxy URI in format http[s]://[auth@]host:port
. ex: 'http://proxy.example.com:8080'
timeout
- Request timeout in millisecondshost
- the mailgun host (default: 'api.mailgun.net'). Note that if you are using the EU region the host should be set to 'api.eu.mailgun.net'protocol
- the mailgun protocol (default: 'https:', possible values: 'http:' or 'https:')port
- the mailgun port (default: '443')endpoint
- the mailgun host (default: '/v3')retry
- the number of total attempts to do when performing requests. Default is 1
.
That is, we will try an operation only once with no retries on error. You can also use a config
object compatible with the async
library for more control as to how the retries take place.
See docs heretestMode
- turn test mode on. If test mode is on, no requests are made, rather the request options and data is loggedtestModeLogger
- custom test mode logging functionAttachments can be sent using either the attachment
or inline
parameters. inline
parameter can be use to send an
attachment with inline
disposition. It can be used to send inline images. Both types are supported with same mechanisms
as described, we will just use attachment
parameter in the documentation below but same stands for inline
.
Sending attachments can be done in a few ways. We can use the path to a file in the attachment
parameter.
If the attachment
parameter is of type string
it is assumed to be the path to a file.
1var filepath = path.join(__dirname, 'mailgun_logo.png'); 2 3var data = { 4 from: 'Excited User <me@samples.mailgun.org>', 5 to: 'serobnic@mail.ru', 6 subject: 'Hello', 7 text: 'Testing some Mailgun awesomeness!', 8 attachment: filepath 9}; 10 11mailgun.messages().send(data, function (error, body) { 12 console.log(body); 13});
We can pass a buffer (has to be a Buffer
object) of the data. If a buffer is used the data will be attached using a
generic filename "file".
1var filepath = path.join(__dirname, 'mailgun_logo.png'); 2var file = fs.readFileSync(filepath); 3 4var data = { 5 from: 'Excited User <me@samples.mailgun.org>', 6 to: 'serobnic@mail.ru', 7 subject: 'Hello', 8 text: 'Testing some Mailgun awesomeness!', 9 attachment: file 10}; 11 12mailgun.messages().send(data, function (error, body) { 13 console.log(body); 14});
We can also pass in a stream of the data. This is useful if you're attaching a file from the internet.
1var request = require('request'); 2var file = request("https://www.google.ca/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"); 3 4var data = { 5 from: 'Excited User <me@samples.mailgun.org>', 6 to: 'serobnic@mail.ru', 7 subject: 'Hello', 8 text: 'Testing some Mailgun awesomeness!', 9 attachment: file 10}; 11 12mailgun.messages().send(data, function (error, body) { 13 console.log(body); 14});
Finally we provide a Mailgun.Attachment
class to add attachments with a bit more customization. The Attachment
constructor takes an options
object. The options
parameters can have the following fields:
data
- can be one of
Stream
which means it is a readable stream.filename
- the file name to be used for the attachment. Default is 'file'contentType
- the content type. Required for case of Stream
data. Ex. image/jpeg
.knownLength
- the content length in bytes. Required for case of Stream
data.If an attachment object does not satisfy those valid conditions it is ignored. Multiple attachments can be sent by
passing an array in the attachment
parameter. The array elements can be of any one of the valid types and each one
will be handled appropriately.
1var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 2var filename = 'mailgun_logo.png'; 3var filepath = path.join(__dirname, filename); 4var file = fs.readFileSync(filepath); 5 6var attch = new mailgun.Attachment({data: file, filename: filename}); 7 8var data = { 9 from: 'Excited User <me@samples.mailgun.org>', 10 to: 'serobnic@mail.ru', 11 subject: 'Hello', 12 text: 'Testing some Mailgun awesomeness!', 13 attachment: attch 14}; 15 16mailgun.messages().send(data, function (error, body) { 17 console.log(body); 18});
1var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 2var filename = 'mailgun_logo.png'; 3var filepath = path.join(__dirname, filename); 4var fileStream = fs.createReadStream(filepath); 5var fileStat = fs.statSync(filepath); 6 7msg.attachment = new mailgun.Attachment({ 8 data: fileStream, 9 filename: 'my_custom_name.png', 10 knownLength: fileStat.size, 11 contentType: 'image/png'}); 12 13mailgun.messages().send(data, function (error, body) { 14 console.log(body); 15});
Sending messages in MIME format can be accomplished using the sendMime()
function of the messages()
proxy object.
The data
parameter for the function has to have to
and message
properties. The message
property can be a full
file path to the MIME file, a stream of the file, or a string representation of the MIME
message. To build a MIME string you can use the nodemailer library.
Some examples:
1var domain = 'mydomain.org'; 2var mailgun = require('mailgun-js')({ apiKey: "YOUR API KEY", domain: domain }); 3var MailComposer = require('nodemailer/lib/mail-composer'); 4 5var mailOptions = { 6 from: 'you@samples.mailgun.org', 7 to: 'mm@samples.mailgun.org', 8 subject: 'Test email subject', 9 text: 'Test email text', 10 html: '<b> Test email text </b>' 11}; 12 13var mail = new MailComposer(mailOptions); 14 15mail.compile().build((err, message) => { 16 17 var dataToSend = { 18 to: 'mm@samples.mailgun.org', 19 message: message.toString('ascii') 20 }; 21 22 mailgun.messages().sendMime(dataToSend, (sendError, body) => { 23 if (sendError) { 24 console.log(sendError); 25 return; 26 } 27 }); 28});
1var filepath = '/path/to/message.mime'; 2 3var data = { 4 to: fixture.message.to, 5 message: filepath 6}; 7 8mailgun.messages().sendMime(data, function (err, body) { 9 console.log(body); 10});
1var filepath = '/path/to/message.mime';
2
3var data = {
4 to: fixture.message.to,
5 message: fs.createReadStream(filepath)
6};
7
8mailgun.messages().sendMime(data, function (err, body) {
9 console.log(body);
10});
members().create({data})
will create a mailing list member with data
. Mailgun also offers a resource for creating
members in bulk. Doing a POST
to /lists/<address>/members.json
adds multiple members, up to 1,000 per call,
to a Mailing List. This can be accomplished using members().add()
.
1var members = [ 2 { 3 address: 'Alice <alice@example.com>', 4 vars: { age: 26 } 5 }, 6 { 7 name: 'Bob', 8 address: 'bob@example.com', 9 vars: { age: 34 } 10 } 11]; 12 13mailgun.lists('mylist@mycompany.com').members().add({ members: members, subscribed: true }, function (err, body) { 14 console.log(body); 15});
Mailgun-js also provides helper methods to allow users to interact with parts of the api that are not exposed already.
These are not tied to the domain passed in the constructor, and thus require the full path with the domain
passed in the resource
argument.
mailgun.get(resource, data, callback)
- sends GET request to the specified resource on api.mailgun.post(resource, data, callback)
- sends POST request to the specified resource on api.mailgun.delete(resource, data, callback)
- sends DELETE request to the specified resource on api.mailgun.put(resource, data, callback)
- sends PUT request to the specified resource on api.Example: Get some stats
1mailgun.get('/samples.mailgun.org/stats', { event: ['sent', 'delivered'] }, function (error, body) { 2 console.log(body); 3});
Module works with Node-style callbacks, but also implements promises with the promisify-call library.
1mailgun.lists('mylist@mydomain.com').info().then(function (data) { 2 console.log(data); 3}, function (err) { 4 console.log(err); 5});
The function passed as 2nd argument is optional and not needed if you don't care about the fail case.
The Mailgun object also has a helper function for validating Mailgun Webhook requests (as per the mailgun docs for securing webhooks). This code came from this gist.
Example usage:
1var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 2 3function router(app) { 4 app.post('/webhooks/mailgun/*', function (req, res, next) { 5 var body = req.body; 6 7 if (!mailgun.validateWebhook(body.timestamp, body.token, body.signature)) { 8 console.error('Request came, but not from Mailgun'); 9 res.send({ error: { message: 'Invalid signature. Are you even Mailgun?' } }); 10 return; 11 } 12 13 next(); 14 }); 15 16 app.post('/webhooks/mailgun/catchall', function (req, res) { 17 // actually handle request here 18 }); 19}
These routes require Mailgun public API key. Please check Mailgun email validation documentation for more responses details.
mailgun.validate(address, private, options, fn)
Checks if email is valid.
private
- whether it's private validateoptions
- any additional optionsExample usage:
1var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 2 3mailgun.validate('test@mail.com', function (err, body) { 4 if(body && body.is_valid){ 5 // do something 6 } 7});
Parses list of email addresses and returns two lists:
Example usage:
1var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); 2 3mailgun.parse([ 'test@mail.com', 'test2@mail.com' ], function (err, body) { 4 if(error){ 5 // handle error 6 }else{ 7 // do something with parsed addresses: body.parsed; 8 // do something with unparseable addresses: body.unparseable; 9 } 10});
debug package is used for debug logging.
1DEBUG=mailgun-js node app.js
Test mode can be turned on using testMode
option. When on, no requests are actually sent to Mailgun, rather we log the request options and applicable payload and form data. By default we log to console.log
, unless DEBUG
is turned on, in which case we use debug logging.
1mailgun = require('mailgun-js')({ apiKey: api_key, domain: domain, testMode: true }) 2 3const data = { 4 from: 'mailgunjs+test1@gmail.com', 5 to: 'mailgunjstest+recv1@gmail.com', 6 subject: 'Test email subject', 7 text: 'Test email text' 8}; 9 10mailgun.messages().send(data, function (error, body) { 11 console.log(body); 12});
options: { hostname: 'api.mailgun.net',
port: 443,
protocol: 'https:',
path: '/v3/sandbox12345.mailgun.org/messages',
method: 'POST',
headers:
{ 'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 127 },
auth: 'api:key-0e8pwgtt5ylx0m94xwuzqys2-o0x4-77',
agent: false,
timeout: undefined }
payload: 'to=mailgunjs%2Btest1%40gmail.com&from=mailgunjstest%2Brecv1%40gmail.com&subject=Test%20email%20subject&text=Test%20email%20text'
form: undefined
undefined
Note that in test mode no error or body are returned as a result.
The logging can be customized using testModeLogger
option which is a function to perform custom logging.
1const logger = (httpOptions, payload, form) => { 2 const { method, path } = httpOptions 3 const hasPayload = !!payload 4 const hasForm = !!form 5 6 console.log(`%s %s payload: %s form: %s`, method, path, hasPayload, hasForm) 7} 8 9mailgun = require('mailgun-js')({ apiKey: api_key, domain: domain, testMode: true, testModeLogger: logger }) 10 11const data = { 12 from: 'mailgunjs+test1@gmail.com', 13 to: 'mailgunjstest+recv1@gmail.com', 14 subject: 'Test email subject', 15 text: 'Test email text' 16}; 17 18mailgun.messages().send(data, function (error, body) { 19 console.log(body); 20});
Sample output:
POST /v3/sandbox12345.mailgun.org/messages payload: true form: false
undefined
To run the test suite you must first have a Mailgun account with a domain setup. Then create a file named ./test/data/auth.json, which contains your credentials as JSON, for example:
1{ "api_key": "XXXXXXXXXXXXXXXXXXXXXXX", "public_api_key": "XXXXXXXXXXXXXXXXXXXXXXX", "domain": "mydomain.mailgun.org" }
You should edit ./test/data/fixture.json and modify the data to match your context.
Then install the dev dependencies and execute the test suite:
$ npm install
$ npm test
The tests will call Mailgun API, and will send a test email, create route(s), mailing list and mailing list member.
This project is not endorsed by or affiliated with Mailgun. The general design and some code was heavily inspired by node-heroku-client.
Copyright (c) 2012 - 2017 OneLobby and Bojan D.
Licensed under the MIT License.
No vulnerabilities found.
No security vulnerabilities found.