HOW #7 – How do robots check their emails
In one of the previous Hack of the week article, I wrote how to send emails with python script. Today I will show you, how to read emails, from gmail inbox. This is one of the way, how users can interact with the robots.
- user can trigger the run of the robot
- user can reply to the email send by the robot with additional information.
I will create a simple script in python, which will check the gmail inbox, if there are new messages. If yes, then apply filter:
- message has subject: „command“
- the text contains string: „run the robot“
For this case, anybody can send email to robot, and the robot will check emails from all users. For future, it is also possible to filter the senders, from whose we want to read the emails. For the simplicity, this will not be covered today.
First I will need imap_tools library for accessing emails from python:
pip install imap_tools
I will import two components from newly installed library:
from imap_tools import MailBox, AND
Next, I need to set up some variables with the credentials and conditions for the emails. You can put your data here:
mail_server = "imap.gmail.com"
user_name = "email@example.com"
user_password = "****************"
user_subject = "command"
text_to_search = "run the robot"
The script will open connection to the gmail imap server and fetches messages, which are fulfilling condition:
- subject is "run_the_robot"
- email has not been seen yet
and stores them in the list not_red_messages
not_red_messages = [
for msg in MailBox(mail_server)
in next part, I will filter out the messages, which do not contain text phrase "run the robot" in the text part of the email
filtered_messages = 
for message in not_red_messages:
if text_to_search in message.text:
now, the list filtered_messages contains messages, that fulfils all conditions I set on the beginning, lets do brief print of them:
for filtered_message in filtered_messages:
I will get output like this:
date=Thu, 23 Sep 2021 10:36:55 +0200 || firstname.lastname@example.org |
| subject=command || text=Hi, run the robot, please.
that's mean, that the script has got one email from user email@example.com, which is fulfilling the conditions I set on the beginning. Usually, we use this data later in the code for deciding etc.
That's all for today.