Skip to content

Instantly share code, notes, and snippets.

@ewandennis
Last active June 13, 2016 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ewandennis/d8655f2eb266d7773518ebf1b5a88d53 to your computer and use it in GitHub Desktop.
Save ewandennis/d8655f2eb266d7773518ebf1b5a88d53 to your computer and use it in GitHub Desktop.
Split fromEmail into local part and domain substitution variables
'use strict';
/*
* Update a SparkPost template to use substitution variables
* in content.from.name, content.from.email and content.reply_to
*
* Usage: node setDynamicFromReplyTo.js <API KEY> <template ID>
*
* Note: your API KEY must have template write privileges.
*
*/
var SparkPost = require('sparkpost')
, key = process.argv[2]
, templateID = process.argv[3]
, client = new SparkPost(key)
, sampleTrans = {
recipients: ['...'],
content: {
template_id: ""
},
substitution_data: {
fromName: "Your Name",
fromEmailLocalPart: "you",
fromEmailDomain: "yourdomain.com",
replyTo: "youagain@yourotherdomain.com"
}
};
function msg(s) {
console.log(s);
}
function err(s) {
console.log('Error: ' + s);
}
msg('Extracting template: ' + templateID + ' ...');
client.templates.find({id: templateID}, function(error, res) {
if (error) {
err("Unable to fetch template named " + templateID);
err(error);
} else {
msg('Template extracted. Updating fields: ');
msg('\tcontent.from.name = "{{fromName}}"');
msg('\tcontent.from.email = "{{fromEmailLocalPart}}@{{fromEmailDomain}}"');
msg('\tcontent.reply_to = "{{replyTo}}"');
var tpl;
try {
tpl = JSON.parse(res.body).results;
} catch(e) {
err('Failed to parse template JSON');
err(e);
return;
}
tpl.content.from = {
name: '{{fromName}}',
email: '{{fromEmailLocalPart}}@{{fromEmailDomain}}'
};
tpl.content.reply_to = '{{replyTo}}';
msg('Saving...');
client.templates.update({
template: tpl
}, function(error, res) {
if (error) {
err('Failed to save updated template');
err(error);
} else {
msg('Template updated!\n');
msg('You can use use this template with custom from and reply to addresses with a transmission like this:');
sampleTrans.content.template_id = templateID;
msg(JSON.stringify(sampleTrans, null, ' '));
msg('\nNote: your fromEmail domain must be a valid sending domain within SparkPost');
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment