├── .eslintrc ├── .travis.yml ├── .editorconfig ├── .gitignore ├── .jshintrc ├── examples └── sendmail.js ├── package.json ├── CONTRIBUTING.md ├── CHANGELOG.md ├── README.md ├── lib └── sparkPostTransport.js ├── test └── sparkpostTransport.js └── LICENSE /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "sparkpost/api" 3 | } 4 | 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 6 4 | - 8 5 | - 9 6 | - node 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | end_of_line = lf 7 | charset = "utf-8" 8 | 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Config 2 | *.env 3 | 4 | # Logs 5 | logs 6 | *.log 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | 13 | # Directory for instrumented libs generated by jscoverage/JSCover 14 | lib-cov 15 | 16 | # Coverage directory used by tools like istanbul 17 | coverage 18 | 19 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 20 | .grunt 21 | 22 | # node-waf configuration 23 | .lock-wscript 24 | 25 | # Compiled binary addons (http://nodejs.org/api/addons.html) 26 | build/Release 27 | 28 | # Dependency directory 29 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 30 | node_modules 31 | 32 | # *nix swap files 33 | *.swp 34 | *.swo 35 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "node" : true, 3 | "es3" : true, 4 | "strict" : true, 5 | "curly" : true, 6 | "eqeqeq" : true, 7 | "immed" : true, 8 | "indent" : 2, 9 | "newcap" : true, 10 | "noarg" : true, 11 | "quotmark" : true, 12 | "undef" : true, 13 | "unused" : true, 14 | "asi" : false, 15 | "boss" : false, 16 | "debug" : false, 17 | "laxcomma" : true, 18 | "maxcomplexity" : 5, 19 | "expr": true, 20 | "predef": [ 21 | "before", 22 | "beforeEach", 23 | "after", 24 | "afterEach", 25 | "describe", 26 | "it" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /examples/sendmail.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /* eslint-disable no-console */ 4 | const nodemailer = require('nodemailer') 5 | , sparkPostTransport = require('nodemailer-sparkpost-transport') 6 | , transporter = nodemailer.createTransport(sparkPostTransport({ 7 | 'sparkPostApiKey': '', 8 | 'options': { 9 | 'open_tracking': true, 10 | 'click_tracking': true, 11 | 'transactional': true 12 | }, 13 | 'campaign_id': 'Nodemailer Demo' 14 | })); 15 | 16 | transporter.sendMail({ 17 | from: 'me@example.com', 18 | to: 'you@example.net', 19 | subject: 'Nodemailer + SparkPost = Sheer Awe', 20 | text: 'Plain text email content', 21 | html: '

Richly marked up email content

' 22 | }, function(err, info) { 23 | if (err) { 24 | console.error(err); 25 | } else { 26 | console.log(info); 27 | } 28 | }); 29 | 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodemailer-sparkpost-transport", 3 | "version": "2.2.0", 4 | "description": "SparkPost transport for Nodemailer", 5 | "main": "lib/sparkPostTransport.js", 6 | "scripts": { 7 | "pretest": "eslint examples lib test *.js", 8 | "test": "mocha", 9 | "postversion": "git push upstream && git push --tags upstream" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git@github.com:SparkPost/nodemailer-sparkpost-transport.git" 14 | }, 15 | "keywords": [ 16 | "nodemailer", 17 | "sparkpost" 18 | ], 19 | "author": "SparkPost", 20 | "license": "Apache-2.0", 21 | "bugs": { 22 | "url": "https://github.com/SparkPost/nodemailer-sparkpost-transport/issues" 23 | }, 24 | "homepage": "https://github.com/SparkPost/nodemailer-sparkpost-transport", 25 | "dependencies": { 26 | "sparkpost": "^2.1.0" 27 | }, 28 | "devDependencies": { 29 | "chai": "^4.2.0", 30 | "eslint": "=3.0.0", 31 | "eslint-config-sparkpost": "1.0.1", 32 | "mocha": "^5.2.0", 33 | "nodemailer": "^4.6.8", 34 | "sinon": "^7.1.1" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to SparkPost 2 | 3 | Transparency is one of our core values, and we encourage developers to contribute and become part of the SparkPost developer community. 4 | ## Prerequisite to contribution 5 | 6 | Before writing code, please search for existing issues or create a new issue to confirm where your contribution fits into the roadmap. 7 | 8 | Current milestone Pull Requests will receive priority review for merging. 9 | 10 | ## Contribution Steps 11 | 1. Fork this repository 12 | 2. Create a new branch named after the issue you’ll be fixing (include the issue number as the branch name, example: Issue in GH is #8 then the branch name should be ISSUE-8)) 13 | 3. Write corresponding tests and code (only what is needed to satisfy the issue and tests please) 14 | * Include your tests in the 'test' directory in an appropriate test file 15 | * Write code to satisfy the tests 16 | * Run tests using ```npm test``` 17 | 5. Ensure automated tests pass 18 | 6. Submit a new Pull Request applying your feature/fix branch to the develop branch of the SparkPost client library 19 | 20 | ## Releases 21 | If you are a collaborator, when you want release a new version, follow these steps. 22 | 23 | *Note: This assumes you have an `upstream` remote set up to `git@github.com:SparkPost/nodemailer-sparkpost-transport.git`* 24 | 25 | 1. Make sure all the changes are merged into master 26 | 2. Make sure all changes have passed [Travis CI build][1] 27 | 3. Determine type of release. We use [Semantic Versioning](http://semver.org/). 28 | 4. Update [CHANGELOG.md](CHANGELOG.md) with release notes and commit 29 | 5. Run `npm version` command to increment `package.json` version, commit changes, tag changes, and push to upstream. 30 | - Patch -> `npm version patch` 31 | - Minor -> `npm version minor` 32 | - Major -> `npm version major` 33 | 6. Once [Travis CI build][1] (from tag) has completed, make sure you're working directory is clean and run `npm publish` 34 | while in the project root. 35 | 7. Create a new [Github Release](https://github.com/SparkPost/node-sparkpost/releases) using the new tag. Copy release 36 | notes from the [CHANGELOG.md](CHANGELOG.md). 37 | 38 | [1]: https://travis-ci.org/SparkPost/nodemailer-sparkpost-transport 39 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | All notable changes to this project will be documented in this file. 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | 5 | ## [Unreleased] 6 | 7 | ## [2.2.0] - 2018/11/9 8 | - Added attachments, reply to, and headers support. Closes #9 9 | - Upgraded Nodemailer version tested against and other test deps 10 | 11 | ## [2.1.0] - 2018/07/16 12 | 13 | ### Added 14 | - Support for setting the SparkPost endpoint. Closes #20. 15 | 16 | ## [2.0.0] - 2017/01/06 *breaking* 17 | With this major release, we are now using the latest 2.x version of the node-sparkpost library. 18 | This removes support for versions of Node.js below 4.0. 19 | 20 | ### Added 21 | - Populate node-sparkpost's stackIdentity option 22 | 23 | ### Updated 24 | - Updated to [`sparkpost@2.1.0`](https://github.com/SparkPost/node-sparkpost/). 25 | 26 | ### Removed 27 | - No longer supporting Node.js versions 0.10 & 0.12. We will be following the [LTS Schedule](https://github.com/nodejs/LTS) going forward. 28 | 29 | ## [1.1.0] - 2016/11/10 30 | ### Added 31 | - Support for Nodemailer's `from.name` and `from.address` fields by @ewandennis. Closes #10. 32 | 33 | ### Updated 34 | - Switched to using `npm version` for releases by @aydrian. Closes #13. 35 | - Updated to `sparkpost@1.3.8`. 36 | - Updated to `mocha@3.1.2`. 37 | - Updated to `sinon@1.17.6`. 38 | 39 | ### Removed 40 | - `with-package` package no longer needed. 41 | 42 | ## [1.0.0] - 2016/07/26 43 | - [#7](https://github.com/SparkPost/nodemailer-sparkpost-transport/pull/7) Implemented the Nodemailer API (@ewandennis) 44 | 45 | ## [0.1.2] - 2016/05/17 46 | - [#4](https://github.com/SparkPost/nodemailer-sparkpost-transport/pull/4) Removed dotenv, updated README, and general cleanup. Closes #3 (@aydrian) 47 | - [#2](https://github.com/SparkPost/nodemailer-sparkpost-transport/pull/2) Sort available options lists (@simison) 48 | - [#1](https://github.com/SparkPost/nodemailer-sparkpost-transport/pull/1) fixed typo in readme file (@OogieBoogieInJSON) 49 | 50 | ## [0.1.1] - 2016/05/17 51 | - Unpublished from NPM. Republished as v0.1.2 52 | 53 | ## 0.1.0 - 2015/08/28 54 | - Initial release 55 | 56 | [Unreleased]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/v2.0.0...HEAD 57 | [2.0.0]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/1.1.0...v2.0.0 58 | [1.1.0]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/1.0.0...v1.1.0 59 | [1.0.0]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/0.1.2...1.0.0 60 | [0.1.2]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/0.1.1...0.1.2 61 | [0.1.1]: https://github.com/SparkPost/nodemailer-sparkpost-transport/compare/v0.1.0...0.1.1 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | [Sign up](https://app.sparkpost.com/join?plan=free-0817?src=Social%20Media&sfdcid=70160000000pqBb&pc=GitHubSignUp&utm_source=github&utm_medium=social-media&utm_campaign=github&utm_content=sign-up) for a SparkPost account and visit our [Developer Hub](https://developers.sparkpost.com) for more resources. 4 | 5 | # SparkPost transport for Nodemailer 6 | ## nodemailer-sparkpost-transport 7 | 8 | [![Build Status](https://travis-ci.org/SparkPost/nodemailer-sparkpost-transport.svg?branch=master)](https://travis-ci.org/SparkPost/nodemailer-sparkpost-transport) 9 | [![NPM version](https://badge.fury.io/js/nodemailer-sparkpost-transport.png)](http://badge.fury.io/js/nodemailer-sparkpost-transport) 10 | 11 | ## Usage 12 | 13 | ### Install 14 | 15 | ``` 16 | npm install nodemailer-sparkpost-transport 17 | ``` 18 | 19 | ### Create a Nodemailer transport object 20 | 21 | ```javascript 22 | var nodemailer = require('nodemailer'); 23 | var sparkPostTransport = require('nodemailer-sparkpost-transport'); 24 | var transporter = nodemailer.createTransport(sparkPostTransport(options)); 25 | ``` 26 | 27 | where: 28 | 29 | - **options** defines connection _default_ transmission properties 30 | - `sparkPostApiKey` - SparkPost [API Key](https://app.sparkpost.com/account/api-keys). If not provided, it will use the `SPARKPOST_API_KEY` env var. 31 | - `endpoint` - The endpoint to use for the SparkPost API requests. If you have a SparkPost EU account, set this to `https://api.eu.sparkpost.com` (optional) 32 | - `campaign_id` - Name of the campaign (optional) 33 | - `metadata` - Transmission level metadata containing key/value pairs (optional) 34 | - `options` - JSON object in which transmission options are defined (optional) 35 | - `substitution_data` - Key/value pairs that are provided to the substitution engine (optional) 36 | 37 | For more information, see the [SparkPost API Documentation for Transmissions](https://developers.sparkpost.com/api/transmissions) 38 | 39 | ## Send a message 40 | 41 | ```javascript 42 | transport.sendMail({ 43 | from: 'me@here.com', 44 | to: 'you@there.com', 45 | subject: 'Very important stuff', 46 | text: 'Plain text', 47 | html: 'Rich taggery' 48 | }, function(err, info) { 49 | if (err) { 50 | console.log('Error: ' + err); 51 | } else { 52 | console.log('Success: ' + info); 53 | } 54 | }); 55 | ``` 56 | 57 | [Read more about Nodemailer's `sendMail()` method here](https://github.com/nodemailer/nodemailer#sending-mail). 58 | 59 | ### Additional Options 60 | 61 | The SparkPost Nodemailer transport also supports a few SparkPost-specific `sendMail()` options in both the transport constructor and the 'sendMail()` method. 62 | 63 | Note: `sendMail()` options override their constructor counterparts: 64 | 65 | - **options** 66 | - `campaign_id` - Overrides for constructor option 67 | - `metadata` - Override for constructor option 68 | - `options` - Override for constructor option 69 | - `substitution_data` - Override for constructor option 70 | -------------------------------------------------------------------------------- /lib/sparkPostTransport.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // Dependencies 4 | const pkg = require('../package') 5 | , SparkPost = require('sparkpost'); 6 | 7 | // Constructor 8 | function SparkPostTransport(options) { 9 | let opt; 10 | 11 | // Set required properties 12 | this.name = 'SparkPost'; 13 | this.version = pkg.version; 14 | options = options || {}; 15 | 16 | // Set the SparkPost API Key (must have appropriate Transmission resource permissions) 17 | this.sparkPostApiKey = process.env.SPARKPOST_API_KEY || options.sparkPostApiKey; 18 | this.sparkPostEmailClient = new SparkPost(this.sparkPostApiKey, { 19 | stackIdentity: `nodemailer-sparkpost-transport/${this.version}`, 20 | endpoint: options.endpoint 21 | }); 22 | 23 | // Set any options which are valid 24 | for (opt in options) { 25 | this[opt] = (options.hasOwnProperty(opt)) ? options[opt] : undefined; 26 | } 27 | 28 | return this; 29 | } 30 | 31 | function populateCustomFields(message, defaults, request) { 32 | const data = message.data 33 | , customFields = ['campaign_id', 'metadata', 'substitution_data', 'options', 'content', 'recipients']; 34 | 35 | // Apply default SP-centric options and override if provided in mail object 36 | customFields.forEach(function(fld) { 37 | if (data.hasOwnProperty(fld)) { 38 | request[fld] = data[fld]; 39 | } else if (defaults.hasOwnProperty(fld)) { 40 | request[fld] = defaults[fld]; 41 | } 42 | }); 43 | } 44 | 45 | function populateFrom(inreq, outreq) { 46 | if (inreq.from) { 47 | if (typeof(inreq.from) === 'object') { 48 | outreq.content.from = { 49 | name: inreq.from.name || null, 50 | email: inreq.from.address 51 | }; 52 | } else { 53 | outreq.content.from = inreq.from; 54 | } 55 | } 56 | } 57 | 58 | function populateInlineStdFields(message, resolveme, request) { 59 | const data = message.data 60 | , resolveKeys = ['html', 'text'] 61 | , contentFlds = { 62 | 'subject': 'subject', 63 | 'headers': 'headers', 64 | 'replyTo': 'reply_to' 65 | }; 66 | 67 | populateFrom(data, request); 68 | 69 | // content fields that get transferred to request 70 | Object.keys(contentFlds).map(function(key) { 71 | if (data.hasOwnProperty(key)) { 72 | request.content[contentFlds[key]] = data[key]; 73 | } 74 | }); 75 | 76 | // content that gets resloved 77 | resolveKeys.map(function(key) { 78 | if (data.hasOwnProperty(key)) { 79 | resolveme[key] = key; 80 | } 81 | }); 82 | 83 | // format attachments 84 | if (data.attachments) { 85 | const spAttachments = []; 86 | 87 | data.attachments.map(function(att) { 88 | spAttachments.push({ 89 | name: att.filename, 90 | type: att.contentType, 91 | data: att.content 92 | }); 93 | }); 94 | 95 | request.content.attachments = spAttachments; 96 | } 97 | } 98 | 99 | function populateRecipients(request, msgData) { 100 | if (msgData.to) { 101 | request.recipients = emailList(msgData.to) || []; 102 | } 103 | 104 | if (msgData.cc) { 105 | request.cc = emailList(msgData.cc); 106 | } 107 | 108 | if (msgData.bcc) { 109 | request.bcc = emailList(msgData.bcc); 110 | } 111 | } 112 | 113 | SparkPostTransport.prototype.send = function send(message, callback) { 114 | const data = message.data 115 | , request = { 116 | content: {} 117 | } 118 | , resolveme = {}; 119 | 120 | // Conventional nodemailer fields override SparkPost-specific ones and defaults 121 | populateCustomFields(message, this, request); 122 | 123 | populateRecipients(request, data); 124 | 125 | if (data.raw) { 126 | resolveme.raw = 'email_rfc822'; 127 | } else { 128 | populateInlineStdFields(message, resolveme, request); 129 | } 130 | 131 | this.resolveAndSend(message, resolveme, request, callback); 132 | }; 133 | 134 | SparkPostTransport.prototype.resolveAndSend = function(mail, toresolve, request, callback) { 135 | const self = this 136 | , keys = Object.keys(toresolve); 137 | 138 | if (keys.length === 0) { 139 | return this.sendWithSparkPost(request, callback); 140 | } 141 | 142 | // eslint-disable-next-line one-var 143 | const srckey = keys[0] 144 | , dstkey = toresolve[keys[0]]; 145 | 146 | delete toresolve[srckey]; 147 | 148 | this.loadContent(mail, srckey, function(err, content) { 149 | request.content[dstkey] = content; 150 | self.resolveAndSend(mail, toresolve, request, callback); 151 | }); 152 | }; 153 | 154 | SparkPostTransport.prototype.loadContent = function(mail, key, callback) { 155 | const content = mail.data[key]; 156 | if (typeof content === 'string') { 157 | return process.nextTick(function() { 158 | callback(null, content); 159 | }); 160 | } 161 | mail.resolveContent(mail.data, key, function(err, res) { 162 | if (err) { 163 | return callback(err); 164 | } 165 | callback(null, res.toString()); 166 | }); 167 | }; 168 | 169 | SparkPostTransport.prototype.sendWithSparkPost = function(transBody, callback) { 170 | this.sparkPostEmailClient.transmissions.send(transBody, function(err, res) { 171 | if (err) { 172 | return callback(err); 173 | } 174 | // Example successful Sparkpost transmission response: 175 | // { "results": { "total_rejected_recipients": 0, "total_accepted_recipients": 1, "id": "66123596945797072" } } 176 | return callback(null, { 177 | messageId: res.results.id, 178 | accepted: res.results.total_accepted_recipients, 179 | rejected: res.results.total_rejected_recipients 180 | }); 181 | }); 182 | }; 183 | 184 | function emailList(strOrLst) { 185 | let lst = strOrLst; 186 | if (typeof strOrLst === 'string') { 187 | lst = strOrLst.split(','); 188 | } 189 | 190 | return lst.map(function(addr) { 191 | if (typeof addr === 'string') { 192 | return {address: addr}; 193 | } 194 | return { 195 | address: { 196 | name: addr.name, 197 | email: addr.address 198 | }}; 199 | }); 200 | } 201 | 202 | module.exports = function(options) { 203 | return new SparkPostTransport(options); 204 | }; 205 | -------------------------------------------------------------------------------- /test/sparkpostTransport.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const sinon = require('sinon') 4 | , expect = require('chai').expect 5 | , nodemailer = require('nodemailer') 6 | , sparkPostTransport = require('../lib/sparkPostTransport.js') 7 | , pkg = require('../package.json'); 8 | 9 | describe('SparkPost Transport', function() { 10 | const transport = sparkPostTransport({sparkPostApiKey: '12345678901234567890'}); 11 | 12 | it('should have a name and version property', function(done) { 13 | expect(transport).to.have.property('name', 'SparkPost'); 14 | expect(transport).to.have.property('version', pkg.version); 15 | done(); 16 | }); 17 | 18 | it('should expose a send method', function(done) { 19 | expect(transport.send).to.exist; 20 | expect(transport.send).to.be.a('function'); 21 | done(); 22 | }); 23 | 24 | it('should be able to set options', function(done) { 25 | const transport = sparkPostTransport({ 26 | sparkPostApiKey: '12345678901234567890', 27 | endpoint: 'https://api.eu.sparkpost.com', 28 | campaign_id: 'sample_campaign', 29 | tags: ['new-account-notification'], 30 | metadata: {'source': 'event'}, 31 | substitution_data: {'salutatory': 'Welcome to SparkPost!'}, 32 | options: {'click_tracking': true, 'open_tracking': true}, 33 | content: {'template_id': 'newAccountNotification'}, 34 | recipients: [{'email': 'john.doe@example.com', 'name': 'John Doe'}] 35 | }); 36 | 37 | expect(transport.endpoint).to.equal('https://api.eu.sparkpost.com'); 38 | expect(transport.campaign_id).to.equal('sample_campaign'); 39 | expect(transport.tags).to.deep.equal(['new-account-notification']); 40 | expect(transport.metadata).to.deep.equal({'source': 'event'}); 41 | expect(transport.substitution_data).to.deep.equal({'salutatory': 'Welcome to SparkPost!'}); 42 | expect(transport.options).to.deep.equal({'click_tracking': true, 'open_tracking': true}); 43 | expect(transport.content).to.deep.equal({'template_id': 'newAccountNotification'}); 44 | expect(transport.recipients).to.deep.equal([{'email': 'john.doe@example.com', 'name': 'John Doe'}]); 45 | 46 | done(); 47 | }); 48 | 49 | }); 50 | 51 | describe('Send Method', function() { 52 | 53 | describe('SP-centric mail structure', function() { 54 | it('should be able to overload options at the transmission', function(done) { 55 | // Create the default transport 56 | const transport = sparkPostTransport({ 57 | sparkPostApiKey: '12345678901234567890', 58 | campaign_id: 'sample_campaign', 59 | tags: ['new-account-notification'], 60 | metadata: {'source': 'event'}, 61 | substitution_data: {'salutatory': 'Welcome to SparkPost!'}, 62 | options: {'click_tracking': true, 'open_tracking': true}, 63 | content: {'template_id': 'newAccountNotification'}, 64 | recipients: [{'email': 'john.doe@example.com', 'name': 'John Doe'}] 65 | }); 66 | 67 | // Create the modified options for use with the above stub test 68 | // eslint-disable-next-line one-var 69 | const overloadedTransmission = { 70 | campaign_id: 'another_sample_campaign', 71 | tags: ['alternative-tag'], 72 | metadata: {'changedKey': 'value'}, 73 | substitution_data: {'salutatory': 'And now...for something completely different'}, 74 | options: {'click_tracking': false, 'open_tracking': false, 'transactional': true}, 75 | recipients: [{ 76 | list_id: 'myStoredRecipientTestList' 77 | }], 78 | content: { 79 | template_id: 'someOtherTemplate' 80 | } 81 | }; 82 | 83 | // Stub the send method of the SDK out 84 | sinon.stub(transport, 'send').callsFake(function(data, resolve) { 85 | // Grab the transmission body from the send() payload for assertions 86 | expect(data.campaign_id).to.equal('another_sample_campaign'); 87 | expect(data.tags).to.deep.equal(['alternative-tag']); 88 | expect(data.metadata).to.deep.equal({'changedKey': 'value'}); 89 | expect(data.substitution_data).to.deep.equal({'salutatory': 'And now...for something completely different'}); 90 | expect(data.options).to.deep.equal({'click_tracking': false, 'open_tracking': false, 'transactional': true}); 91 | expect(data.content).to.deep.equal({'template_id': 'someOtherTemplate'}); 92 | expect(data.recipients).to.deep.equal([{'list_id': 'myStoredRecipientTestList'}]); 93 | 94 | // Resolve the stub's spy 95 | resolve({ 96 | results: { 97 | total_rejected_recipients: 0, 98 | total_accepted_recipients: 1, 99 | id: '66123596945797072' 100 | } 101 | }); 102 | }); 103 | 104 | // Call the stub from above 105 | transport.send(overloadedTransmission, function(data) { 106 | expect(data.results.id).to.exist; 107 | expect(data.results.total_rejected_recipients).to.exist; 108 | expect(data.results.total_accepted_recipients).to.exist; 109 | done(); 110 | }); 111 | // Return the original method to its proper state 112 | transport.send.restore(); 113 | }); 114 | }); 115 | 116 | describe('conventional nodemailer mail structure', function() { 117 | let sptrans 118 | , transport 119 | , mail 120 | , rcp1 121 | , rcp2; 122 | 123 | function checkRecipientsFromFld(mail, infld, val, outfld, done) { 124 | mail[infld] = val; 125 | transport.sendMail(mail, function() { 126 | const transBody = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 127 | 128 | expect(transBody).to.include.keys(['recipients', 'content']); 129 | expect(transBody[outfld]).to.have.length(2); 130 | expect(transBody[outfld][0]).to.deep.equal({ address: rcp1 }); 131 | expect(transBody[outfld][1]).to.deep.equal({ address: rcp2 }); 132 | done(); 133 | }); 134 | } 135 | 136 | beforeEach(function() { 137 | sptrans = sparkPostTransport({ 138 | sparkPostApiKey: '12345678901234567890' 139 | }); 140 | 141 | transport = nodemailer.createTransport(sptrans); 142 | 143 | rcp1 = 'Mrs. Asoni '; 144 | rcp2 = 'b@b.com'; 145 | 146 | mail = { 147 | from: 'roberto@from.example.com', 148 | to: 'kingcnut@to.example.com', 149 | subject: 'Modern Kinging', 150 | text: 'Edicts and surfeits...', 151 | html: '

Edicts and surfeits...

', 152 | replyTo: 'other@to.example.com', 153 | headers: { 154 | 'X-MSYS-SUBACCOUNT': 125 155 | } 156 | }; 157 | 158 | sptrans.sparkPostEmailClient.transmissions.send = sinon.stub().yields({ 159 | results: { 160 | total_rejected_recipients: 0, 161 | total_accepted_recipients: 1, 162 | id: '66123596945797072' 163 | } 164 | }); 165 | }); 166 | 167 | it('should accept nodemailer content fields', function(done) { 168 | transport.sendMail(mail, function() { 169 | const transBody = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 170 | 171 | expect(transBody).to.have.keys(['recipients', 'content']); 172 | expect(transBody.content.html).to.equal(mail.html); 173 | expect(transBody.content.text).to.equal(mail.text); 174 | expect(transBody.content.subject).to.equal(mail.subject); 175 | expect(transBody.content.from).to.equal(mail.from); 176 | expect(transBody.content.reply_to).to.equal(mail.replyTo); 177 | expect(transBody.content.headers).to.equal(mail.headers); 178 | expect(transBody.recipients).to.have.length(1); 179 | expect(transBody.recipients[0]).to.have.keys('address'); 180 | expect(transBody.recipients[0].address).to.be.a('string'); 181 | expect(transBody.recipients[0].address).to.equal(mail.to); 182 | done(); 183 | }); 184 | }); 185 | 186 | it('should format attachments', function(done) { 187 | mail.attachments = [ 188 | { 189 | filename: 'an_attachment', 190 | content: 'Q29uZ3JhdHVsYXRpb25zLCB5b3UgY2FuIGJhc2U2NCBkZWNvZGUh', 191 | contentType: 'application/pdf' 192 | }, 193 | { 194 | filename: 'another_attachment', 195 | content: 'Q30uZ3JhdHVsYXRpb25zLCB5b3UgY2FuIGJhc2U2NCBkZWNvZGUh', 196 | contentType: 'application/pdf' 197 | } 198 | ]; 199 | 200 | transport.sendMail(mail, function() { 201 | const transBody = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 202 | 203 | expect(transBody.content.attachments.length).to.equal(2); 204 | expect(transBody.content.attachments[0]).to.deep.equal({ 205 | name: 'an_attachment', 206 | type: 'application/pdf', 207 | data: 'Q29uZ3JhdHVsYXRpb25zLCB5b3UgY2FuIGJhc2U2NCBkZWNvZGUh' 208 | }); 209 | done(); 210 | }); 211 | }); 212 | 213 | it('should accept raw mail structure', function(done) { 214 | delete mail.subject; 215 | delete mail.text; 216 | delete mail.html; 217 | delete mail.from; 218 | mail.raw = 'rawmsg'; 219 | transport.sendMail(mail, function() { 220 | const transBody = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 221 | 222 | expect(transBody).to.have.keys(['recipients', 'content']); 223 | expect(transBody.content).to.have.keys('email_rfc822'); 224 | expect(transBody.recipients).to.have.length(1); 225 | expect(transBody.recipients[0]).to.have.keys('address'); 226 | expect(transBody.recipients[0].address).to.be.a('string'); 227 | expect(transBody.recipients[0].address).to.equal(mail.to); 228 | done(); 229 | }); 230 | }); 231 | 232 | it('should accept from as a string', function(done) { 233 | mail.from = 'me@here.com'; 234 | transport.sendMail(mail, function() { 235 | const trans = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 236 | expect(trans.content.from).to.be.a('string'); 237 | done(); 238 | }); 239 | }); 240 | 241 | it('should accept from as an object', function(done) { 242 | mail.from = { 243 | name: 'Me', 244 | address: 'me@here.com' 245 | }; 246 | 247 | transport.sendMail(mail, function() { 248 | const trans = sptrans.sparkPostEmailClient.transmissions.send.firstCall.args[0]; 249 | expect(trans.content.from).to.be.an('object'); 250 | expect(trans.content.from).to.have.property('name'); 251 | expect(trans.content.from.name).to.equal(mail.from.name); 252 | expect(trans.content.from).to.have.property('email'); 253 | expect(trans.content.from.email).to.equal(mail.from.address); 254 | done(); 255 | }); 256 | }); 257 | 258 | it('should accept to as an array', function(done) { 259 | checkRecipientsFromFld(mail, 'to', [rcp1, rcp2], 'recipients', done); 260 | }); 261 | 262 | it('should accept to as a string', function(done) { 263 | checkRecipientsFromFld(mail, 'to', [rcp1, rcp2].join(','), 'recipients', done); 264 | }); 265 | 266 | it('should accept cc as an array', function(done) { 267 | checkRecipientsFromFld(mail, 'cc', [rcp1, rcp2], 'cc', done); 268 | }); 269 | 270 | it('should accept cc as a string', function(done) { 271 | checkRecipientsFromFld(mail, 'cc', [rcp1, rcp2].join(','), 'cc', done); 272 | }); 273 | 274 | it('should accept bcc as an array', function(done) { 275 | checkRecipientsFromFld(mail, 'bcc', [rcp1, rcp2], 'bcc', done); 276 | }); 277 | 278 | it('should accept bcc as a string', function(done) { 279 | checkRecipientsFromFld(mail, 'bcc', [rcp1, rcp2].join(','), 'bcc', done); 280 | }); 281 | }); 282 | }); 283 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------