BuiltOnAir

Mail Merge with Lob.com

Created by: Creator: Bill Carovano

External API

This shared base demonstrates how you can perform a mail merge using Airtable and the Lob.com service using this script.

For a quick video tutorial on using the script look here.

There are two scripting blocks in this base:

  1. Get table and field IDs (Script Shown Below). This code allows you to obtain your own unique table and field IDs, which you will use to update your “Send Letter” script. I recommend using field IDs and table IDs instead of names, so that any changes to the table or field names won’t break your script.
  2. Send Letter (To view this script check out the Airtable Universe Base). This interacts with the Lob API to mail a letter.

Script Code


							// replace with your own Lob API key below 
let APIkey = btoa("test_fa3b26f1d3c70e4e8f8d4def3936e1105ae" + ":");

// tblF61QmthNkxqPHI is the Mail List table
let table = base.getTable("tblF61QmthNkxqPHI"); // this is the table ID for the 'Mail List' table

let result = await table.selectRecordsAsync();

for (let record of result.records) {

  let firstname = record.getCellValue("fldPnIWJYUDc9YXmz"); // field ID for First Name
  let lastname = record.getCellValue("fldFUl46aSEdxTHzv"); // field ID for Last name
  let propaddress = record.getCellValue("fld622b41xCEy9zml"); // field ID for Property Street Address
  let toAddressStreet = record.getCellValue("fldgtUE406Q2t4LAT"); // field ID for to Address Street
  let toAddressCity = record.getCellValue("fldSlgOTQbJ6P7pty"); // field ID for to Address Street
  let toAddressState = record.getCellValue("fldxnzD5D7GH8ty1e"); // field ID for to Address Street
  let toAddressZIP = record.getCellValue("fldNpcksdh1lY0b89"); // field ID for to Address Street

  console.log(firstname);

  let querystring = "description=Letter: " + firstname + " " + lastname +
          "&to[name]=" + firstname + " " + lastname +
          "&to[address_line1]=" + toAddressStreet +
          "&to[address_city]=" + toAddressCity +
          "&to[address_state]=" + toAddressState +
          "&to[address_zip]=" + toAddressZIP +
          "&from[name]=REI Investors" + 
          "&from[address_line1]=185 BERRY ST STE 6100" + 
          "&from[address_city]=SAN FRANCISCO" + 
          "&from[address_state]=CA" + 
          "&from[address_zip]=94107-1741" + 
          "&file=tmpl_25e2808b3413630" + // you will need to insert your own Lob template ID here.
          "&merge_variables[first_name]=" + firstname + 
          "&merge_variables[property_address]=" + propaddress +
          "&color=true";

  let response =  await fetch("https://api.lob.com/v1/letters", {
    body: querystring,
    headers: {
      Authorization: "Basic " + APIkey,
     "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST"
  })

  // get the API response
  let data = await response.json();

  console.log(data);

} //end for loop through each record