Created
November 13, 2017 17:06
-
-
Save mxstbr/30106fe4457d14ed5084592698ad57af to your computer and use it in GitHub Desktop.
A send email util for Postmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import postmark from 'postmark'; | |
const debug = require('debug')('send-email'); | |
const stringify = require('json-stringify-pretty-compact'); | |
let client; | |
if (process.env.POSTMARK_SERVER_KEY) { | |
client = new postmark.Client(process.env.POSTMARK_SERVER_KEY); | |
} else { | |
console.log( | |
'\nℹ️ POSTMARK_SERVER_KEY not provided, debug mode enabled. Will log emails instead of actually sending them.' | |
); | |
// If no postmark API key is provided don't crash the server but log instead | |
client = { | |
sendEmailWithTemplate: ({ To, TemplateModel }, cb) => { | |
debug('debug mode enabled, mocking email sending'); | |
cb(); | |
}, | |
}; | |
} | |
const sendEmail = (options) => { | |
const { TemplateId, To, TemplateModel } = options; | |
debug( | |
`--Send email with template ${TemplateId}--\nTo: ${To}\nRe: ${TemplateModel.subject}\nTemplateModel: ${stringify( | |
TemplateModel | |
)}` | |
); | |
return new Promise((res, rej) => { | |
client.sendEmailWithTemplate( | |
{ | |
From: '[email protected]', | |
TemplateId: TemplateId, | |
To: To, | |
TemplateModel: TemplateModel, | |
}, | |
err => { | |
if (err) { | |
console.log('Error sending email:'); | |
console.log(err); | |
return rej(err); | |
} | |
res(); | |
debug(`email to ${To} sent successfully`); | |
} | |
); | |
}); | |
}; | |
export default sendEmail; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment