Skip to content

Instantly share code, notes, and snippets.

@anka
Created June 1, 2022 08:52
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 anka/76aad85ff98c1679bfa72e90e3c8cbf3 to your computer and use it in GitHub Desktop.
Save anka/76aad85ff98c1679bfa72e90e3c8cbf3 to your computer and use it in GitHub Desktop.
Hubspot custom workflow function to send transactional email with custom data
const hubspot = require('@hubspot/api-client');
exports.main = async (event, callback) => {
// initialize the hubspot api client with your api secret
const hubspotClient = new hubspot.Client({
apiKey: process.env.API_KEY
});
// the ID of the email template
const EMAIL_TEMPLATE_ID = 82546305923;
// the ID of the current contact in the workflow
const contactId = event.object.objectId;
let contact = undefined;
// Get contact details
try {
// set properties you want to fetch
const properties = ["email", "firstname", "lastname"];
const paginateAssociations = undefined;
const associations = undefined;
const archived = false;
const api = hubspotClient.crm.contacts.basicApi;
const apiResponse = await api.getById(contactId,
properties,
associations,
paginateAssociations,
archived);
contact = apiResponse.body;
} catch (e) {
e.message === 'HTTP request failed'
? console.error(JSON.stringify(e.response, null, 2))
: console.error(e)
throw e;
}
// OUT OF SCOPE
// Fetch some external data you want to render in your email template. In our
// example we use a fixed HTML string for simplicity.
const readingStats = "<tr><td>1</td><td>Hubspot Emails with Custom Data</td><td>1.200</td></tr>"
// Send email with custom data
try {
// create send id to avoid multiple email sends for a customer on the same day
const today = new Date().setHours(0, 0, 0, 0).toString();
const sendId = "sendId_" + contact.id + "_" + today;
// fill out the basic message properties
const message = {
"to": contact.properties.email,
"sendId": sendId,
"replyTo": [],
"cc": [],
"bcc": []
};
// set the contact properties
const contactProperties = contact.properties;
// here you can add all your custom data
const customProperties = {
readingStats: readingStats
};
// the final email message object
const PublicSingleSendRequestEgg = {
message,
contactProperties,
customProperties,
emailId: EMAIL_TEMPLATE_ID
};
const api = hubspotClient.marketing.transactional.defaultApi;
const apiResponse = await api.sendEmail(PublicSingleSendRequestEgg)
console.log(JSON.stringify(apiResponse.body, null, 2));
} catch (e) {
e.message === 'HTTP request failed'
? console.error(JSON.stringify(e.response, null, 2))
: console.error(e)
throw e;
}
callback({outputFields: {}}); // call final callback without any parameters
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment