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.

For example:

  • 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.

Lets start:

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 = ""
user_name = "[email protected]"
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)
        .login(user_name, user_password)
        .fetch(AND(subject=user_subject, seen=False))

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:
             f"|| sender={filtered_message.from_}"
             f"|| subject={filtered_message.subject}"
             f"|| text={filtered_message.text}"

I will get output like this:

date=Thu, 23 Sep 2021 10:36:55 +0200 || [email protected] |
| subject=command || text=Hi, run the robot, please.

that's mean, that the script has got one email from user [email protected], 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.