Custom Code - Get firstname & lastname from email address
解決
Hi,
I'm not a developper of any sort but I'm trying to understand custom code for worflows. I'd like to be able to get the firstname & lastname of a contact when the email address looks like this "firstame.lastname@domain.com".
I've used this python code:
import re
def extract_name_from_hubspot_email(email): # Define a regular expression pattern to match HubSpot email format pattern = r'^([a-zA-Z]+)\.([a-zA-Z]+)@.*$'
# Use re.match to extract the first name and last name match = re.match(pattern, email)
# If the email doesn't match the expected HubSpot format, return None return None, None
# Example usage: email = "john.doe@hubspot.com" first_name, last_name = extract_name_from_hubspot_email(email) if first_name and last_name: print("First Name:", first_name) print("Last Name:", last_name) else: print("Unable to extract first name and last name from the email.")
But not really sure how to do it with the custom code.
Custom Code - Get firstname & lastname from email address
解決
That should do the trick.
const hubspot = require('@hubspot/api-client');
exports.main = async (event, callback) => {
const hubspotClient = new hubspot.Client({
accessToken: process.env.SECRET_NAME // Change "SECRET_NAME" with your Private App key secret name
});
let email;
try {
const ApiResponse = await hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["email"]);
email = ApiResponse.properties.email;
let names = email.split("@"); // split emaill adress by "@"
let fnln = names[0].split("."); // get whatever is before "@" and plit it by "."
var fn = fnln[0]; //get whatever is before "." (First name)
var ln = fnln[1]; // get whatever is after "." (Last name)
if(fnln.length == 2 ){ // checking if First Name and Last Name exists together and are separeted by "."
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
"properties": {
"firstname": fn, // update contact record with First Name
"lastname": ln // update contact record with Last Name
}
});
} else{
// WIll update First Name as John and Last Name as Doe
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
"properties": {
"firstname": "John",
"lastname": "Doe"
}
});
}
} catch (err) {
console.error(err);
// We will automatically retry when the code fails because of a rate limiting error from the HubSpot API.
throw err;
}
}
Custom Code - Get firstname & lastname from email address
解決
Looks like you didn't change SECRET_NAME to your Secret name with Private App token.
I'll walk you through.
Navigate to HubSpot Settings
In Left menu find INTEGRATIONS > PRIVATE APPS
Click Crate a Private app button In Basic Info give it a name - ex. Contact
In Scopes in CRM find crm.objects.contacts and select Read and Write for it
Click Create App button and Continue creating in pop-up
Click Show token and Copy
Now go to you Custom Code step in workflow Second from Top there is a Dropdown list with Secrets, click it
Click Add Secret,
Give it a name best would be same as you gave to you Private App ie. Contact so you know what is what In Secret Value paste token you copied from Private App. And Save it.
Custom Code - Get firstname & lastname from email address
解決
That should do the trick.
const hubspot = require('@hubspot/api-client');
exports.main = async (event, callback) => {
const hubspotClient = new hubspot.Client({
accessToken: process.env.SECRET_NAME // Change "SECRET_NAME" with your Private App key secret name
});
let email;
try {
const ApiResponse = await hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["email"]);
email = ApiResponse.properties.email;
let names = email.split("@"); // split emaill adress by "@"
let fnln = names[0].split("."); // get whatever is before "@" and plit it by "."
var fn = fnln[0]; //get whatever is before "." (First name)
var ln = fnln[1]; // get whatever is after "." (Last name)
if(fnln.length == 2 ){ // checking if First Name and Last Name exists together and are separeted by "."
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
"properties": {
"firstname": fn, // update contact record with First Name
"lastname": ln // update contact record with Last Name
}
});
} else{
// WIll update First Name as John and Last Name as Doe
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
"properties": {
"firstname": "John",
"lastname": "Doe"
}
});
}
} catch (err) {
console.error(err);
// We will automatically retry when the code fails because of a rate limiting error from the HubSpot API.
throw err;
}
}
Custom Code - Get firstname & lastname from email address
解決
Looks like you didn't change SECRET_NAME to your Secret name with Private App token.
I'll walk you through.
Navigate to HubSpot Settings
In Left menu find INTEGRATIONS > PRIVATE APPS
Click Crate a Private app button In Basic Info give it a name - ex. Contact
In Scopes in CRM find crm.objects.contacts and select Read and Write for it
Click Create App button and Continue creating in pop-up
Click Show token and Copy
Now go to you Custom Code step in workflow Second from Top there is a Dropdown list with Secrets, click it
Click Add Secret,
Give it a name best would be same as you gave to you Private App ie. Contact so you know what is what In Secret Value paste token you copied from Private App. And Save it.
Custom Code - Get firstname & lastname from email address
解決
Above script is for Node.js and your error have .py extenson which indicates that you are using Python. Change Language to node.js (drop down at very top of Custom code window)
Custom Code - Get firstname & lastname from email address
解決
Ahh ok - cool. So, i have changed this to node but i am now getting a new error
WARNING: The logs for this function have exceeded the 4KB limit.
...
th\":\"299\",\"content-type\":\"application/json;charset=utf-8\",\"date\":\"Wed, 04 Oct 2023 14:13:54 GMT\",\"nel\":\"{\\\"success_fraction\\\":0.01,\\\"report_to\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"report-to\":\"{\\\"endpoints\\\":[{\\\"url\\\":\\\"https:\\\\/\\\\/a.nel.cloudflare.com\\\\/report\\\\/v3?s=R1xxowtx0mun4hENbLNfeB6D8pGV9PDfJdYRMKneCXYxWPhTz5c7SUkOIVZbZ80AMu1zh9phiTEUAvMyfQP4MJt9SPrbkf5tNih%2FZymAXLdV%2FPvFnKBXbJ8a7cJA0F88\\\"}],\\\"group\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"server\":\"cloudflare\",\"strict-transport-security\":\"max-age=31536000; includeSubDomains; preload\",\"vary\":\"origin, Accept-Encoding\",\"x-content-type-options\":\"nosniff\",\"x-envoy-upstream-service-time\":\"3\",\"x-evy-trace-listener\":\"listener_https\",\"x-evy-trace-route-configuration\":\"listener_https/all\",\"x-evy-trace-route-service-name\":\"envoyset-translator\",\"x-evy-trace-served-by-pod\":\"iad02/hubapi-td/envoy-proxy-5b5c96c966-58hgh\",\"x-evy-trace-virtual-host\":\"all\",\"x-hubspot-auth-failure\":\"401 Unauthorized\",\"x-hubspot-correlation-id\":\"d648677e-8e57-436f-937d-be9d4aea1ebb\",\"x-request-id\":\"d648677e-8e57-436f-937d-be9d4aea1ebb\",\"x-trace\":\"2BF72E4BDF67F1EE00D32853021FA9998311A5AE28000000000000000000\"}"," at BasicApiResponseProcessor.<anonymous> (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:247:23)"," at Generator.next (<anonymous>)"," at fulfilled (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:5:58)"," at processTicksAndRejections (node:internal/process/task_queues:96:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: Error: HTTP-Code: 401","Message: An error occurred.","Body: {\"status\":\"error\",\"message\":\"Authentication credentials not found. This API supports OAuth 2.0 authentication and you can find more details at https://developers.hubspot.com/docs/methods/auth/oauth-overview\",\"correlationId\":\"d648677e-8e57-436f-937d-be9d4aea1ebb\",\"category\":\"INVALID_AUTHENTICATION\"}","Headers: {\"access-control-allow-credentials\":\"false\",\"cf-cache-status\":\"DYNAMIC\",\"cf-ray\":\"810e0734ae500497-FRA\",\"connection\":\"close\",\"content-length\":\"299\",\"content-type\":\"application/json;charset=utf-8\",\"date\":\"Wed, 04 Oct 2023 14:13:54 GMT\",\"nel\":\"{\\\"success_fraction\\\":0.01,\\\"report_to\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"report-to\":\"{\\\"endpoints\\\":[{\\\"url\\\":\\\"https:\\\\/\\\\/a.nel.cloudflare.com\\\\/report\\\\/v3?s=R1xxowtx0mun4hENbLNfeB6D8pGV9PDfJdYRMKneCXYxWPhTz5c7SUkOIVZbZ80AMu1zh9phiTEUAvMyfQP4MJt9SPrbkf5tNih%2FZymAXLdV%2FPvFnKBXbJ8a7cJA0F88\\\"}],\\\"group\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"server\":\"cloudflare\",\"strict-transport-security\":\"max-age=31536000; includeSubDomains; preload\",\"vary\":\"origin, Accept-Encoding\",\"x-content-type-options\":\"nosniff\",\"x-envoy-upstream-service-time\":\"3\",\"x-evy-trace-listener\":\"listener_https\",\"x-evy-trace-route-configuration\":\"listener_https/all\",\"x-evy-trace-route-service-name\":\"envoyset-translator\",\"x-evy-trace-served-by-pod\":\"iad02/hubapi-td/envoy-proxy-5b5c96c966-58hgh\",\"x-evy-trace-virtual-host\":\"all\",\"x-hubspot-auth-failure\":\"401 Unauthorized\",\"x-hubspot-correlation-id\":\"d648677e-8e57-436f-937d-be9d4aea1ebb\",\"x-request-id\":\"d648677e-8e57-436f-937d-be9d4aea1ebb\",\"x-trace\":\"2BF72E4BDF67F1EE00D32853021FA9998311A5AE28000000000000000000\"}"," at process.<anonymous> (file:///var/runtime/index.mjs:1250:17)"," at process.emit (node:events:513:28)"," at emit (node:internal/process/promises:140:20)"," at processPromiseRejections (node:internal/process/promises:274:27)"," at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Unknown application error occurred
Runtime.Unknown
Memory: 74/128 MB
Runtime: 1546.15 ms
Custom Code - Get firstname & lastname from email address
解決
Hey Dan,
Yes basically extract FN & LN and add the corresponding fields. I'm not worried about the email address having LN.FN@ as we're dealing with professional accounts and 99% are FN.LN@
I found this code on GitHub which could be helpful: @coldrickjack shared how to split the full name provided by a contact using a custom coded workflow action.
@coldrickjack do you think @MSaurat could do something similar with the first & lastname of a contact's email address? Thank you!