# Custom Code - Get firstname & lastname from email address

**URL:** <https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815>\
**Category:** Data Hub\
**Created:** [September 1, 2023, 3:15pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815 "2023-09-01T15:15:56Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![MSaurat](https://avatars.discourse-cdn.com/v4/letter/m/a698b9/32.png) [@MSaurat](https://community.hubspot.com/u/MSaurat)\
**Post date:** [September 1, 2023, 3:15pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/1 "2023-09-01T15:15:56Z")

</div>

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](mailto: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 match:  
first\_name = match.group(1)  
last\_name = match.group(2)  
return first\_name, last\_name  
# If the email doesn’t match the expected HubSpot format, return None  
return None, None

# Example usage:  
email = “[john.doe@hubspot.com](mailto: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.

Any help appreciated.

Thank you

---

<div class="post-metadata">

**Author:** ![MiaSrebrnjak](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/miasrebrnjak/32/10_2.png) [@MiaSrebrnjak](https://community.hubspot.com/u/MiaSrebrnjak)\
**Post date:** [September 4, 2023, 1:20pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/2 "2023-09-04T13:20:20Z")

</div>

Hi @MSaurat,

Thank you for reaching out to the Community!

I found [this code on GitHub](https://gist.github.com/jackcoldrick90/6d854d0fe41a8b564bb4341f458d1bd2) 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!

Cheers  
Mia, Community Team

---

<div class="post-metadata">

**Author:** ![DanielJeal](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/danieljeal/32/93810_2.png) [@DanielJeal](https://community.hubspot.com/u/DanielJeal)\
**Post date:** [September 7, 2023, 8:27am UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/3 "2023-09-07T08:27:10Z")

</div>

What do you want to do with the name when you get it? Update the Contacts name in HubSpot? Also, what if their email is lastname.firstname?!

---

<div class="post-metadata">

**Author:** ![MSaurat](https://avatars.discourse-cdn.com/v4/letter/m/a698b9/32.png) [@MSaurat](https://community.hubspot.com/u/MSaurat)\
**Post date:** [September 11, 2023, 7:48am UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/4 "2023-09-11T07:48:01Z")

</div>

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@

---

<div class="post-metadata">

**Author:** ![Maciek-Magic](https://avatars.discourse-cdn.com/v4/letter/m/b5e925/32.png) [@Maciek-Magic](https://community.hubspot.com/u/Maciek-Magic)\
**Post date:** [September 12, 2023, 10:24am UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/5 "2023-09-12T10:24:04Z")

</div>

That should do the trick.

```lia-code-sample
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;
 }
}

```

---

<div class="post-metadata">

**Author:** ![DamianKnapp](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/damianknapp/32/193315_2.png) [@DamianKnapp](https://community.hubspot.com/u/DamianKnapp)\
**Post date:** [October 4, 2023, 12:35pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/6 "2023-10-04T12:35:34Z")

</div>

So - this one brings up an error as per below. should this be “import from” on line 1?

```auto
[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'hubspotHandler': invalid syntax (file.py, line 1)
Traceback (most recent call last):
  File "/var/task/file.py" Line 1
    const hubspot = require('@hubspot/api-client');
Memory: 37/128 MB
Runtime: 1.52 ms

```

---

<div class="post-metadata">

**Author:** ![Maciek-Magic](https://avatars.discourse-cdn.com/v4/letter/m/b5e925/32.png) [@Maciek-Magic](https://community.hubspot.com/u/Maciek-Magic)\
**Post date:** [October 4, 2023, 12:53pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/7 "2023-10-04T12:53:11Z")

</div>

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)

---

<div class="post-metadata">

**Author:** ![DamianKnapp](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/damianknapp/32/193315_2.png) [@DamianKnapp](https://community.hubspot.com/u/DamianKnapp)\
**Post date:** [October 4, 2023, 4:03pm UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/8 "2023-10-04T16:03:04Z")

</div>

Ahh ok - cool. So, i have changed this to node but i am now getting a new error

```auto
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

```

---

<div class="post-metadata">

**Author:** ![Maciek-Magic](https://avatars.discourse-cdn.com/v4/letter/m/b5e925/32.png) [@Maciek-Magic](https://community.hubspot.com/u/Maciek-Magic)\
**Post date:** [October 5, 2023, 7:42am UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/9 "2023-10-05T07:42:39Z")

</div>

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.  
Now go to your code and change this

`accessToken: process.env.SECRET_NAME`

to this

`accessToken: process.env.Contact`

---

<div class="post-metadata">

**Author:** ![DamianKnapp](https://d10pqhm3lwygmk.cloudfront.net/user_avatar/community.hubspot.com/damianknapp/32/193315_2.png) [@DamianKnapp](https://community.hubspot.com/u/DamianKnapp)\
**Post date:** [October 5, 2023, 9:41am UTC](https://community.hubspot.com/t/custom-code-get-firstname-lastname-from-email-address/88815/10 "2023-10-05T09:41:42Z")

</div>

Awesome - Ok.

Thanks for getting my training wheels on with this. Its really helped me out.
