Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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': 'your@email.company.com',
'name': 'Your Company'
},
'subject': 'This week\'s news',
'reply_to': 'James <james@company.com>',
'text': '',
'html': ''
}
}
const defaultUpdateOptions = {
'content': {
'from': {
'email': 'your@email.company.com',
'name': 'Your Company'
},
'subject': 'This week\'s news',
'reply_to': 'James <james@company.com>',
'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)
})
})
@NickolasBoyer

This comment has been minimized.

Copy link
Owner Author

commented Jan 28, 2019

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
You can’t perform that action at this time.