Help

Use Airtable Automations to manage Sendgrid Marketing Contacts

Topic Labels: Scripting extentions
1087 0
cancel
Showing results for 
Search instead for 
Did you mean: 
Jonathan_Straus
5 - Automation Enthusiast
5 - Automation Enthusiast

For context, I have built a Softr app with Airtable as the backend and I want to use SendGrid Marketing to be able to email users of my app but I don’t want to have to manually sync the list of users from Airtable to SendGrid every time a new user signs up for my app.

So I adapted @JonathanBowen’s awesome SendGrid email send script example to call the SendGrid Marketing Contacts API for use in an Airtable Automation triggered when a new record is created in the users table.

// Set up input variables
let inputConfig = input.config();
let email = inputConfig.email;
let firstName = inputConfig.firstName;
let lastName = inputConfig.lastName;
let userType = inputConfig.userType; 
let signupDate = inputConfig.signupDate; 

let SG_API = 'YOUR_SENDGRID_API_KEY';
let SG_URL = 'https://api.sendgrid.com/v3/marketing/contacts';

let data = {
    "contacts": [
        {
            "email": email,
            "first_name": firstName,
            "last_name": lastName, 
            // Custom fields must be referenced by ID, not name. Find custom field IDs via https://docs.sendgrid.com/api-reference/custom-fields/get-all-field-definitions
            "custom_fields": {
                "w1_T": userType,
                "w2_D": signupDate
            }
        }
    ]
};
    
let options = {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + SG_API    
    },
    body: JSON.stringify(data)
};
console.log(options);

let response = await fetch(SG_URL, options);
console.log(response);

Since this endpoint is a PUT upsert API, it’s the same call to create or update a contact for a given email address and you can use this same script in an Airtable Automation triggered when a record in the users table is updated if you want to keep user attribute changes synced to the corresponding contact in SendGrid Marketing.

When trying to adapt this script, please note that the way SendGrid Marketing handles custom fields in contacts is complicated. You can specify reserved fields by field name (e.g., ‘email’, ‘first_name’, ‘last_name’). But if you want to sync any fields from your user table that don’t map to an existing SendGrid reserved field, then you need to:

  1. Create the custom fields you want to use
  2. Lookup the id of each of your custom fields using the Field Definitions endpoint
  3. Use the corresponding custom field ID in your Airtable script
0 Replies 0