Creating a dustmail driver - nodecraft/dustmail.js GitHub Wiki

Writing an email driver for dustmail.js is extremely simple. The driver is just a basic function to handle the email being sent and is always passed and object of emailData, and expects a callback. emailData always contains the following, which is the data returned by dustmail:

{
	to: '[email protected]',
	from: '[email protected]',
	subject: 'Dustmail is awesome!',
	attachments: [ // array of objects
		{
			name: 'readme.txt',
			content: 'Hello World!', // full content of the file
			contentType: 'text/plain'
		}
	],
	render: {
		HtmlBody: '...',
		TextBody: '...'
	}
}

It's the driver's job to translate this data into a format acceptable by the service it's using to send email.

List of drivers

dustmail-mandrill

dustmail-postmark

Our Postmark example driver can be found below. Postmark expects data in the following format, so our driver needs to convert this data as such.

Postmark Request Body

{
  From: '[email protected]',
  To: '[email protected]',
  Subject: 'Dustmail is awesome!',
  HtmlBody: ...,
  TextBody: ...
  Attachments: [
    {
      Name: '...',
      Content: '...',
      ContentType: '...'
    },
    ...
  ]
}

Postmark Driver

var postmark = require('postmark'),
	_ = require('underscore');
module.exports = function(key) {
	return function(emailData, callback) {
		var sendData = {
			To: emailData.to,
			From: emailData.from,
			Subject: emailData.subject,
			HtmlBody: emailData.render.HtmlBody,
			TextBody: emailData.render.TextBody
		};
		var attachments = [];
		if(emailData.attachments) {
			_.each(emailData.attachments, function(attachment) {
				attachments.push({
					Name: attachment.name,
					Content: new Buffer(attachment.content).toString('base64'), // postmark wants a base64 encoded string
					ContentType: attachment.contentType
				});
			});
			sendData.Attachments = attachments;
		}
		if(!sendData.HtmlBody && !sendData.TextBody) {
			return callback({message: 'Neither TextBody or HtmlBody set. Email can not be sent'});
		}
		postmark(key).send(sendData, function(err, result) {
			if(err) {
				callback({message: 'Email failed to send', raw: err});
			}else{
				callback(null,result);
			}
		});
	}
}