Random Cat Facts: APIs and Automated Emails

1 minute read

In this inaugural post, I’d like to share a project from 2019 - my first Python project which was started because of my love for cats! I was inspired after attending a lunch and learn about APIs at work.

After that lunch and learn, I wondered whether I could use this newfound knowledge to send myself a random cat fact every morning to start off the day. Countless Google searches and Stack Overflow pages later, I sent this first automated email to myself on September 22, 2019: Email Sample

Below are the steps I took to set up the daily email using this cat facts API. Email Sample

1. Establish API Connection

Connect to the API using the requests Python library.

# import dependencies
import requests

# define parameters
cat_params = {'animal_type': 'cat', 'amount': '1'}

# pass parameters in URL and send GET request
catfacts = requests.get('https://cat-fact.herokuapp.com/facts/random', params = cat_params)

Then test the connection by checking the status code.

  • Status code 200: everything is ok
  • Status code 404: page or resource was not found
print(catfacts.status_code)

2. Save API Response

Use the built in JSON decoder to save the API response as catfacts_json. This API response contains our random cat fact and will be used in the body of the email.

catfacts_json = catfacts.json()

3. Email Set Up

This gmail Python library was used to send out the daily email. Specify the senderEmail, the email address that will be sending out the daily email. The senderPassword can be generated by following these instructions.

# import dependencies
import gmail

# set up sender email
senderEmail = 'sender@email.com'
senderPassword = 'samplePassword'
credentials = gmail.GMail(senderEmail, senderPassword)

4. Write the Email

Specify various components of the email. Note that the emailBody is uses HTML format and catfacts_json['text'] represents a random cat fact from the API.

# define email components
emailSubject = 'Daily Cat Fact'
recipientEmail = 'recipient@email.com'
recipientName = 'Recipient Name'
emailBody = 'Good morning ' + recipientName + '!<br><br>' + 'Here is today&#39;s cat fact:<br>' + catfacts_json['text'] + '<br><br>' + 'Have a nice day (:'

# generate email
msg = gmail.Message(emailSubject
                    ,to = recipientEmail
                    ,html = emailBody)

5. Send Email and Schedule Task

The last step is to send out the email with the code snippet below. You can now schedule this Python script to send out random cat facts every day!

credentials.send(msg)