Daily Quotes
Context
Throughout the last few years I have prioritised reading as a daily habit. That has evolved from merely reading a book, to full book summaries with key insights, quotes, and my own thoughts and personal reflections on each topic. These notes represent my time and effort on this journey to try to always be my best version. But that is only possible if I act on what I learn, both from books and other sources.
Since I have already read 70+ books, it’s impossible to always be aware of all of the teachings I have already learned. That will only get worse with time because I have no intention to stop reading, and I also do my best to keep a learner mindset in all areas of life. For a while now, I have been playing with the idea of having a system to review these book notes, some of my favourite quotes from insipirational figures, and also other bits of knowledge I acquire from personal projects/studies.
By centralising all this kind of information in my Notion’s second brain, I can effortlessly access and revisit it all. But to take it a step further, with the power of Python, I can connect to Notion’s API, retrieve some of my personal notes, and seamlessly integrate them into an email. Then, automating the delivery of daily quote emails offers me not only a convenient way to get motivational quotes but also a system to periodically remind myself of my own personal notes and insights.
Script explanation
First and foremost, the script begins by importing the required packages, including smtplib
for email functionality, datetime
for date-related operations, json for working with JSON data, random for generating random numbers, logging for error logging, and EmailMessage for creating email messages. Additionally, the notion_client package is imported to interact with the Notion API.
Next, I defined several configuration variables to work with Notion’s API and e-mail functionalities.
Using the ‘notion_client’ package, we only need two variables to work with Notion’s API: the token from a Notion integration, and the id from the Notion page we want to work with. These are really easy to get, just follow these instructions.
To have the script working with e-mails, we need the SMTP server and port, and the address and password from the sender e-mail (for this case I used a gmail account). Then we just set a variable for the recipient’s email (my hotmail account).
Lastly, I set a file to work as the script’s log, for potential errors.
Note: I replaced some of the parts with underscores just for this blog’s sake, it is not supposed to be like this:
The first function in this script is write_dict_to_file_as_json that writes the Notion page data (retrieved as a dictionary) to a JSON file. This function was used for easier inspection of the data during the script’s development.
Then, there is read_text that retrieves the content of a Notion page given its ID, using the Notion API. This function returns a list of results, which includes the blocks of content in the page.
The function safe_get allows accessing nested properties of a database given a dot-chained key. It handles potential errors such as missing keys, type errors, and index errors and returns None if any issue is encountered.
To get random quotes, the function get_random_numbers generates a list of random numbers within a given range (1 to the total number of quotes) using the random.sample function. In this case, it selects five random numbers to represent the indices of quotes to be included in the email.
To prepare the e-mail, the function e_mail_prep creates an EmailMessage object, sets the sender, recipient, subject, and content of the message, and returns the message object.
Then, send_e_mail uses the smtplib library to establish a connection with the SMTP server, login to the sender's email account, and send the email message.
Finally, the main function serves as the entry point for the script. It encapsulates the main logic of the script, and performs the following steps:
The function establishes a connection to the Notion API using the integration token and retrieves information about the specified Notion database.
It queries the database to obtain the rows (quotes) stored within it.
For each row, it retrieves the content, author, origin, and date properties and stores them in a simplified form as a dictionary.
The function then selects five random numbers using the get_random_numbers function.
It constructs the content of the email by retrieving the appropriate quote information based on the selected random numbers.
An introductory and concluding message is added to the email content.
The email message is prepared using the e_mail_prep
function and sent using the
send_e_mail function.If any exception occurs during the execution, an error notification email is prepared and sent to the specified recipient email address.
I purposely left 3 commented lines, which I used to inspect the data while I was developing the script, just in case someone might want to do it as well.
To end, the if name == 'main' block ensures that the
main function is executed when the script is directly run and not when it is imported as a module.
Full Python script
Here you can see the full script, but you can also get the it from my GitHub page.
Executing the script
To automate the process of sending daily quote emails, I used Windows Task Scheduler to schedule the script's execution. This tool provides a user-friendly interface to schedule and manage tasks, making it an excellent tool for automating this processes on a Windows system, and eliminates the need for manual intervention. Here are the steps to get it up and running:
Set up the Python script — To get started, make sure you have the necessary Python script that retrieves quotes from Notion and sends them via email.
Open Windows Task Scheduler — Open the Windows Task Scheduler application by searching for "Task Scheduler" in the Start menu.
Create a new task — In the Task Scheduler window, click on "Create Basic Task" on the right-hand side. This will open a wizard that will guide you through the process of creating a new task.
Provide task details — In the task creation wizard, provide a name and description for the task. For example, you can name it "Daily Quote Email" and provide a suitable description.
Choose the trigger — Select the trigger "Daily" to specify that the task should run every day. Set the desired time for the script to execute.
Choose the action — Select the action "Start a program" to specify the program that will be executed. Click "Next" to proceed.
Configure the Action — In the "Program/script" field, provide the path to your Python interpreter. This is usually located in the Python installation directory, such as C:\Python\python.exe, but you can find it by opening the command prompt and running where python. In the "Add arguments" field, provide the path to your actual Python script.
Finalise and save the task — Review the task details on the summary screen and click "Finish" to create the task. The task scheduler will now execute the Python script automatically at the specified time every day.
Resources
Resource 1 and Resource 2: These links (both the article and the video) serve as practical guides for working with the Notion API in Python, covering the setup process, creating, querying, updating, and deleting pages in a Notion database.
Resource 3: This is great playlist (with just 5 minute videos) to understand the basics of reading and writing data through Notion’s API, both in pages and databases.
Resource 4: For more informations about Notion’s API, you can also check the official documention available.