Created
January 28, 2019 09:55
-
-
Save willwillems/0ec04c8180ca33373a2ebc48910084dd to your computer and use it in GitHub Desktop.
Upload email templates to Sparkpost
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
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) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.