Prejdi na hlavný obsah

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.

Hack of the week - how do robots check their emails

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:

I will import two components from newly installed library:

Next, I need to set up some variables with the credentials and conditions for the emails. You can put your data here:

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

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

now, the list filtered_messages contains messages, that fulfils all conditions I set on the beginning, lets do brief print of them:

I will get output like this:

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