Monthly Archives: April 2014

Easily sending postcards to your Kickstarter backers with Lob

Recently my friend Joël Franusic was stressing out about sending postcards to his Kickstarter backers and asked me to help him out. He pointed me to the excellent service Lob.com, which is a very developer-friendly API around printing and mailing. We quickly had some code up and running that could take a CSV export of Kickstarter campaign backers, verify addresses, and trigger the sending of customizable, actual physical postcards to the backers.

Screen Shot 2014-04-14 at 2.24.30 PM

We wanted to share the project such that it could help out other Kickstarter campaigns, so we put it on Github: https://github.com/mrooney/kickstarter-lob.

Below I explain how to install and use this script to use Lob to send postcards to your Kickstarter backers. The section after that explains how the script works in detail.

Using the script to mail postcards to your backers

First, you’ll need to sign up for a free account at Lob.com, then grab your “Test API Key” from the “Account Details” section of your account page. At this point you can use your sandbox API key to test away free of charge and view images of any resulting postcards. Once you are happy with everything, you can plug in credit card details and start using your “Live” API key. Second, you’ll need an export from Kickstarter for the backers you wish to send postcards to.

Now you’ll want to grab the kickstarter-lob code and get it set.

These instructions assume that you’re using a POSIX compatible operating system like Mac OS X or Linux. If you’re using Mac OS X, open the “Terminal” program and type the commands below into it to get started:

git clone https://github.com/mrooney/kickstarter-lob.git
cd kickstarter-lob
sudo easy_install pip # (if you don’t have pip installed already)
pip install -r requirements.txt
cp config_example.json config.json
open config.json

At this point, you should have a text editor open with the configuration information. Plug in the correct details, making sure to maintain quotes around the values. You’ll need to provide a few things besides an API key:

  • A URL of an image or PDF to be used for the front of the postcard.
    This means that you need to have your PDF available online somewhere. I suggest using Amazon’s S3 service to host your PDF.

  • A message to be printed on the back of the postcard (the address of the receiver will automatically show up here as well).

  • Your return address.

Now you are ready to give it a whirl. Run it like so. Make sure you include the filename for your Kickstarter export:

$ python kslob.py ~/Downloads/your-kickstarter-backer-report.csv
Fetching list of any postcards already sent...
Verifying addresses of backers...
warning: address verification failed for jsmith@example.com, cannot send to this backer.
Already sent postcards to 0 of 161 backers
Send to 160 unsent backers now? [y/N]: y
Postcard sent to Jeff Bezos! (psc_45df20c2ade155a9)
Postcard sent to Tim Cook! (psc_dcbf89cd1e46c488)
...
Successfully sent to 160 backers with 0 failures

The script will verify all addresses, and importantly, only send to addresses not already sent to. The script queries Lob to keep track of who you’ve already sent a postcard to; this important feature allows you to download new Kickstarter exports as people fill in or update their addresses. After downloading a new export from Kickstarter, just run the script against the new export, and the script will only send postcards to the new addresses.

Before anything actually happens, you’ll notice that you’re informed of how many addresses have not yet received postcards and prompted to send them or not, so you can feel assured it is sending only as many postcards as you expect.

If you were to run it again immediately, you’d see something like this:

$ python kslob.py ~/Downloads/your-kickstarter-backer-report.csv
 Fetching list of any postcards already sent...
 Verifying addresses of backers...
 warning: address verification failed for jsmith@example.com, cannot send to this backer.
 Already sent postcards to 160 of 161 backers
 SUCCESS: All backers with verified addresses have been processed, you're done!

After previewing your sandbox postcards on Lob’s website, you can plug in your live API key in the config.json file and send real postcards at reasonable rates.

How the script works

This section explains how the script actually works. If all you wanted to do is send postcards to your Kickstarter backers, then you can stop reading now. Otherwise, read on!

Before you get started, take a quick look at the “kslob.py” file on GitHub: https://github.com/mrooney/kickstarter-lob/blob/master/kslob.py

We start by importing four Python libraries: “csv”, “json”, “lob”, and “sys”. Of those four libraries, “lob” is the only one that isn’t part of Python’s standard library. The “lob” library is installed by using the “pip install -r requirements.txt” command I suggest using above. You can also install “lob-python” using pip or easy_install.

#!/usr/bin/env python
import csv
import json
import lob
import sys

Next we define one class named “ParseKickstarterAddresses” and two functions “addr_identifier” and “kickstarter_dict_to_lob_dict”

“ParseKickstarterAddresses” is the code that reads in the backer report from Kickstarter and turns it into an array of Python dictionaries.

class ParseKickstarterAddresses:
   def __init__(self, filename):
       self.items = []
       with open(filename, 'r') as csvfile:
           reader = csv.DictReader(csvfile)
           for row in reader:
               self.items.append(row)

The “addr_identifier” function takes an address and turns it into a unique identifier, allowing us to avoid sending duplicate postcards to backers.

def addr_identifier(addr):
   return u"{name}|{address_line1}|{address_line2}|{address_city}|{address_state}|{address_zip}|{address_country}".format(**addr).upper()

The “kickstarter_dict_to_lob_dict” function takes a Python dictionary and turns it into a dictionary we can give to Lob as an argument.

def kickstarter_dict_to_lob_dict(dictionary):
   ks_to_lob = {'Shipping Name': 'name',
                'Shipping Address 1': 'address_line1',
                'Shipping Address 2': 'address_line2',
                'Shipping City': 'address_city',
                'Shipping State': 'address_state',
                'Shipping Postal Code': 'address_zip',
                'Shipping Country': 'address_country'}
   address_dict = {}
   for key in ks_to_lob.keys():
       address_dict[ks_to_lob[key]] = dictionary[key]
   return address_dict

The “main” function is where the majority of the logic for our script resides. Let’s cover that in more detail.

We start by reading in the name of the Kickstarter backer export file. Loading our configuration file (“config.json”) and then configuring Lob with the Lob API key from the configuration file:

def main():
   filename = sys.argv[1]
   config = json.load(open("config.json"))
   lob.api_key = config['api_key']

Next we query Lob for the list of postcards that have already been sent. You’ll notice that the “processed_addrs” variable is a Python “set”, if you haven’t used a set in Python before, a set is sort of like an array that doesn’t allow duplicates. We only fetch 100 results from Lob at a time, and use a “while” loop to make sure that we get all of the results.

print("Fetching list of any postcards already sent...")
processed_addrs = set()
postcards = []
postcards_result = lob.Postcard.list(count=100)
while len(postcards_result):
    postcards.extend(postcards_result)
    postcards_result = lob.Postcard.list(count=100, offset=len(postcards))

One we fetch all of the postcards, we print out how many were found:

print("...found {} previously sent postcards.".format(len(postcards)))

Then we iterate through all of our results and add them to the “processed_addrs” set. Note the use of the “addr_identifier” function, which turns each address dictionary into a string that uniquely identifies that address.

for processed in postcards:
    identifier = addr_identifier(processed.to.to_dict())
    processed_addrs.add(identifier)

Next we set up a bunch of variables that will be used later on, variables with configuration information for the postcards that Lob will send, the addresses from the Kickstarter backers export file, and variables to keep track of who we’ve sent postcards to and who we still need to send postcards to.

postcard_from_address = config['postcard_from_address']
postcard_message = config['postcard_message']
postcard_front = config['postcard_front']
postcard_name = config['postcard_name']
addresses = ParseKickstarterAddresses(filename)
to_send = []
already_sent = []

At this point, we’re ready to start validating addresses, the code below loops over every line in the Kickstarter backers export file and uses Lob to see if the address is valid.

print("Verifying addresses of backers...")
for line in addresses.items:
    to_person = line['Shipping Name']
    to_address = kickstarter_dict_to_lob_dict(line)
    try:
        to_name = to_address['name']
        to_address = lob.AddressVerify.verify(**to_address).to_dict()['address']
        to_address['name'] = to_name
    except lob.exceptions.LobError:
        msg = 'warning: address verification failed for {}, cannot send to this backer.'
        print(msg.format(line['Email']))
        continue

If the address is indeed valid, we check to see if we’ve already sent a postcard to that address. If so, the address is added to the list of addresses we’ve “already_sent” postcards to. Otherwise, it’s added to the list of address we still need “to_send” postcards to.

if addr_identifier(to_address) in processed_addrs:
    already_sent.append(to_address)
else:
    to_send.append(to_address)

Next we print out the number of backers we’ve already sent postcards to and check to see if we need to send postcards to anybody, exiting if we don’t need to send postcards to anybody.

nbackers = len(addresses.items)
print("Already sent postcards to {} of {} backers".format(len(already_sent), nbackers))
if not to_send:
    print("SUCCESS: All backers with verified addresses have been processed, you're done!")
    return

Finally, if we do need to send one or more postcards, we tell the user how many postcards will be mailed and then ask them to confirm that those postcards should be mailed:

query = "Send to {} unsent backers now? [y/N]: ".format(len(to_send), nbackers)
if raw_input(query).lower() == "y":
    successes = failures = 0

If the user enters “Y” or “y”, then we start sending postcards. The call to Lob is wrapped in a “try/except” block. We handle calls to the Lob library that return a “LobError” exception, counting those calls as a “failure”. Other exceptions are not handled and will result in the script exciting with that exception.

for to_address in to_send:
    try:
        rv = lob.Postcard.create(to=to_address, name=postcard_name, from_address=postcard_from_address, front=postcard_front, message=postcard_message)
        print("Postcard sent to {}! ({})".format(to_address['name'], rv.id))
        successes += 1
    except lob.exceptions.LobError:
        msg = 'Error: Failed to send postcard to Lob.com'
        print("{} for {}".format(msg, to_address['name']))
        failures += 1

Lastly, we print a message indicating how many messages were sent and how many failures we had.

    print("Successfully sent to {} backers with {} failures".format(successes, failures))
else:

(If the user pressed a key other than “Y” or “y”, this is the message that they’ll see)

print("Okay, not sending to unsent backers.")

And there you have it, a short script that uses Lob to send postcards to your Kickstarter backers, with code to only send one postcard per address, that gracefully handles errors from Lob.

I hope that you’ve found this useful! Please let us know of any issues you encounter on Github, or send pull requests adding exciting new features. Most importantly, enjoy easily bringing smiles to your backers!