diff --git a/lib/mandrill-transport.js b/lib/mandrill-transport.js index e058e1c..5b1f57b 100644 --- a/lib/mandrill-transport.js +++ b/lib/mandrill-transport.js @@ -16,12 +16,35 @@ function MandrillTransport(options) { this.mandrillClient = new mandrill.Mandrill(auth.apiKey); } +function isString(data) { + return typeof data === 'string'; +}; + +function toAddressObjects(input) { + if (isString(input)) { + // Run it through addressparser if it's a string + return addressparser(input); + } else if (Array.isArray(input)) { + // If an array examine each element recursively + return input + .map(function (address) { + return toAddressObjects(address); + }) + .reduce(function (list, address) { + return list.concat(address || []); + }, []) + } else if (typeof input === 'object' && input) { + // Assume we have a valid address object if it's a POJO + return [input]; + } +} + MandrillTransport.prototype.send = function(mail, callback) { var data = mail.data || {}; - var toAddrs = addressparser(data.to) || []; - var ccAddrs = addressparser(data.cc) || []; - var bccAddrs = addressparser(data.bcc) || []; - var fromAddr = addressparser(data.from)[0] || {}; + var toAddrs = toAddressObjects(data.to); + var ccAddrs = toAddressObjects(data.cc); + var bccAddrs = toAddressObjects(data.bcc); + var fromAddr = toAddressObjects(data.from)[0] || {}; var mandrillOptions = data.mandrillOptions || {}; var payload = extend(true, { diff --git a/test/mandrill-transport.js b/test/mandrill-transport.js index 63bcb87..7e976e2 100644 --- a/test/mandrill-transport.js +++ b/test/mandrill-transport.js @@ -164,5 +164,50 @@ describe('MandrillTransport', function() { done(); }); }); + + it('allows addresses as arrays and objects', function (done) { + payload.data.to = [ + { + name: 'SpongeBob SquarePants', + address: 'spongebob@bikini.bottom' + }, + { + name: 'Patrick Star', + address: 'patrick@bikini.bottom' + } + ] + + payload.data.cc = [ + { + name: 'Squidward Tentacles', + address: 'squidward@bikini.bottom' + }, + 'Sandy Cheeks ' + ] + + payload.data.bcc = [ + 'Mr. Krabs ', + { + name: 'Plankton', + address: 'plankton@bikini.bottom', + } + ]; + + payload.data.from = { + name: 'Gary the Snail', + address: 'gary@bikini.bottom' + } + + status = 'sent'; + + transport.send(payload, function(err, info) { + expect(err).to.not.exist; + expect(sendStub.calledOnce).to.be.false; + expect(info.accepted.length).to.equal(1); + expect(info.rejected.length).to.equal(0); + expect(info.messageId).to.equal('fake-id'); + done(); + }); + }) }); });