Skip to content

Instantly share code, notes, and snippets.

@willwillems
Created January 28, 2019 09:55
Show Gist options
  • Save willwillems/0ec04c8180ca33373a2ebc48910084dd to your computer and use it in GitHub Desktop.
Save willwillems/0ec04c8180ca33373a2ebc48910084dd to your computer and use it in GitHub Desktop.
Upload email templates to Sparkpost
require('dotenv').config()
const fs = require('fs')
const path = require('path')
const SparkPost = require('sparkpost')
const templateFolder = './templates/html/'
const sparkpostApiKey = process.env.SPARKPOST_API_KEY
const client = new SparkPost(sparkpostApiKey)
const defaultCreateOptions = {
'id': '',
'name': '',
'published': true,
'options': {
'open_tracking': true,
'click_tracking': true
},
'content': {
'from': {
'email': '[email protected]',
'name': 'Your Company'
},
'subject': 'This week\'s news',
'reply_to': 'James <[email protected]>',
'text': '',
'html': ''
}
}
const defaultUpdateOptions = {
'content': {
'from': {
'email': '[email protected]',
'name': 'Your Company'
},
'subject': 'This week\'s news',
'reply_to': 'James <[email protected]>',
'text': '',
'html': ''
}
}
const createTemplate = (fileName, content) => {
return client.templates.create({
...defaultCreateOptions,
id: fileName,
name: fileName,
content: {
...defaultCreateOptions.content,
html: content
}
})
}
const updateTemplate = (fileName, content) => {
return client.templates.update(fileName, {
...defaultUpdateOptions,
content: {
...defaultUpdateOptions.content,
html: content
}
})
}
fs.readdirSync(templateFolder).forEach(file => {
const fileName = path.parse(file).name // get filename without extention
const content = fs.readFileSync(`${templateFolder}/${file}`, 'utf8')
updateTemplate(fileName, content)
.then(console.log)
.catch(err => {
// if template does not exist yet
if (err.statusCode === 404) {
return createTemplate(fileName, content)
.then(console.log)
.catch(console.error)
}
console.error(err)
})
})
@willwillems
Copy link
Author

Simple Node script to automatically upload your email templates to Sparkpost, I use it in combination with MJML which places the compiled HTML files in the template folder.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment