Giter VIP home page Giter VIP logo

mailgun-js's Introduction

mailgun.js

Simple Node.js module for Mailgun.

Installation

npm install mailgun-js

Usage overview

Please see Mailgun Documentation for full Mailgun API reference.

Currently we implement the send message (non-MIME) API and the Domains, Routes, Campaigns, Mailing Lists, Unsubscribes and Bounces API's. These would be the most common and practical API's to be programmatically used. Others would be easy to add if needed.

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. See the /docs folder for detailed documentation. For full usage examples see the /test folder.

var api_key = 'key-XXXXXXXXXXXXXXXXXXXXXXX';
var domain = 'mydomain.mailgun.org';
var Mailgun = require('mailgun-js');

var mailgun = new Mailgun({apiKey: api_key, domain: domain});

var data = {
  from: 'Excited User <[email protected]>',
  to: '[email protected]',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!'
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

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.

var list = mailgun.lists('[email protected]');

list.info(function (err, data) {
  // `data` is mailing list info
  console.log(data);
});

var bob = {
  subscribed: true,
  address: '[email protected]',
  name: 'Bob Bar',
  vars: {age: 26}
};

list.members().create(bob, function (err, data) {
  // `data` is the member details
  console.log(data);
});

list.members().list(function (err, members) {
  // `members` is the list of members
  console.log(members);
});

list.members('[email protected]').update({ name: 'Foo Bar' }, function (err, body) {
  console.log(body);
});

Attachments

Attachments 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.

var filepath = path.join(__dirname, '/mailgun_logo.png');

var data = {
  from: 'Excited User <[email protected]>',
  to: '[email protected]',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!',
  attachment: filepath
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

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".

var filepath = path.join(__dirname, '/mailgun_logo.png');
var file = fs.readFileSync(filepath);

var data = {
  from: 'Excited User <[email protected]>',
  to: '[email protected]',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!',
  attachment: file
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

Finally we provide a Mailgun.Attachment class to add attachment and specify both the buffer and filename data.

var filename = '/mailgun_logo.png';
var filepath = path.join(__dirname, filename);
var file = fs.readFileSync(filepath);

var attch = new Mailgun.Attachment(file, filename);

var data = {
  from: 'Excited User <[email protected]>',
  to: '[email protected]',
  subject: 'Hello',
  text: 'Testing some Mailgun awesomness!',
  attachment: attch
};

mailgun.messages().send(data, function (error, body) {
  console.log(body);
});

If an attachment object is not of type Buffer or a string or a Mailgun.Attachment object with valid data 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.

Creating mailing list members

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().

var members = [
  {
    address: 'Alice <[email protected]>',
    vars: { age: 26 }
  },
  {
    name: 'Bob',
    address: '[email protected]',
    vars: { age: 34 }
  }
];

mailgun.lists('[email protected]').members().add({ members: members, subscribed: true }, function (err, body) {
  console.log(body);
});

Generic requests

Mailgun-js also provides helper methods to allow users to interact with parts of the api that are not exposed already.

  • 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

mailgun.get('/stats', { event: ['sent', 'delivered'] }, function (error, body) {
  console.log(body);
});

Promises

Module works with Node-style callbacks, but also implements promises with the Q library.

mailgun.lists('[email protected]').info().then(function (data) {
  console.log(data);
}, function (err) {
  console.log(err);
});

The function passed as 2nd argument is optional and not needed if you don't care about the fail case.

Tests

To run the test suite you must first have a Mailgun account with a domain setup. Then create a file named ./test/auth.json, which contains your credentials as JSON, for example:

{ "api_key": "key-XXXXXXXXXXXXXXXXXXXXXXX", "domain": "mydomain.mailgun.org" }

You should edit ./test/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.

Notes

This project is not endorsed by or affiliated with Mailgun. The general design and some code was heavily inspired by node-heroku-client.

License

Copyright 2012, 2013, 2014 OneLobby

Licensed under the MIT License.

mailgun-js's People

Contributors

adammagaluk avatar avbel avatar bojand avatar soplakanets avatar

Watchers

 avatar  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.