Email reading program in Python

Photo by Divide By Zero on Unsplash

In this post I will walk you through an easy and quick project in python. It will hardly take a few hours to complete and implement and will be ready to be added to your resume. So, let’s begin with the description and requirements.

The problem statement we will be tackling in this project is to create a program that can get your mails and read it out to you when run.

We will be using Python to code it out, although if you find appropriate APIs in your favorite language you can go ahead with it. The program has a very simple flow(thanks to the readily available APIs).

The statement can be broken into three sub problems:

  1. get to the mail and read the content
  2. convert the text to speech
  3. play that sound obtained from the above conversion

Let’s tackle each sub problem one by one and later bring it all together to create the final solution.

  1. Getting to the mail and getting the content :

For this part we will be using all the inbuilt libraries of python. Our target is to make our program read mails from gmail and gmail being secure won’t just let an unregistered program just get into your emails(security and privacy and all that stuff, you know). So to allow the email access we need to tell google to chilax and let us read the messages.

To do that we need to enable “IMAP access” for the mail id. follow the steps below to enable it:

> open gmail

>click on settings (top right side)

> go to the Forwarding and POP/IMAP tab

>scroll and you’ll see the enable IMAP part. Enable it.

Now there is one more thing that may give us ugly errors in our otherwise beautiful program. And that is if Gmail doesn’t allow your application to access account.

The error may look something like this:

error you get if access is restricted

Resolution?:

To solve the error just go to your google account management and click on security. Scroll down a bit and you should see the option of 2-step Verification.. Got it? Okay, now turn it off.. We want to make it less secure to be able to access it as easy as possible( by the way.. !! BE WARNED YOU ARE MAKING YOUR ACCOUNT A BIT VULNERABLE!!).

Now that 2-step is off, if you scroll a bit more you should be able to see an option to allow access to ‘Less Secure Apps’. enable it and you are done with the account(until we access it later).

Let’s Code Now!!

Now the setting of the account is done, let’s see what we need to do on the python side.

The code is pretty straight forward and I will try to explain what is what as we code along..

import imaplib

import email

from email.header import decode_header

The above lines bring some required libraries in to our program. These are inbuilt and hence nothing needs to be pip installed yet.

Now, I want to keep my email and password secure and hence I have them saved as constants in a separate file and use it. This also increases maintainability and also keeps my secrets what they are.. a secret.

from secret_data import *

#mail details

user = USER

pswd = PASS

So till now we have told the program what account to get mails from. Now we will get the mails and pull out some information(BTW .. fun thing here would be to see what data we actually get and feel free to throw in some prints to see what you are dealing with)

The following code sets up IMAP so that it knows what server to request to and logs into your gmail account(if you don’t have gmail, you just need to change the server address which you can easy google). After LogIn is success, we choose to open the Inbox(again you can try other folders too like maybe Spam or anything else,feel free to let your imagination run wild)

imap = imaplib.IMAP4_SSL(“imap.gmail.com”,993)

imap.login(user,pswd)

status, num_of_messages = imap.select(“INBOX”)

now the num_of_messages give you how many messages are there in the Inbox and we will need to convert it to int so that we can use it.

Now all we need to do is iterate over the messages and get them one by one. We can proceed, or more appropriately may want to proceed in one of the two ways.. either we read all the mails from top to bottom, Or we just read a few or the top ones. I will show the first method and mark the changes you need to do (actually just one change) to get to the second approach.

Okay so this is a big one, so let’s first understand what we doin:

>Iterate over the message and use message number as message ID and fetch it using IMAP.(the older messages have lower id.. that is if I received a mail yesterday, and another today, yesterday’s mail will have id = 1 and today’s mail will be 2. which also makes sense.). Since we are going to read all the messages, I will be going from 1 to all the way to the most recent message.

>check if we get a response (which will be an instance of tuple, that is it will be a tuple)

>main body is decoded from bytes

>we decode the subject and other headers

>do something with it all

Code:

now, as promised. if you want .. let’s say top ’N’ messages, just change the outer for loop to:

for i in range(num_of_messages, num_of_messages-N, -1):

and the rest of the code will be the same.

with that we have our mail content. Now if the mail is multi part or has attachments, you need to make some small changes to handle those but for this demo, it is sufficient to have the content we have till now

2. Converting the text obtained from mail to sound :

Now that we have the content of the mail with us the next step is to convert text to speech(high techy techy). This is an interesting and very complex thing to do from scratch so I will not dive deep into it but rather encourage you to read about it’s workings.

Proceeding with a simpler option, and putting my trust in google, we will use Google Text to Speech library for python. Now here we need to install some stuff so go to terminal and run

pip install gTTS

Let it install and then we will proceed with a very simple function to convert parsed text to speech( not so high techy techy).

The following code imports gTTS and uses it to convert provided string to speech and save it in a temp.mp3 file which we can play later on in the last part of the solution.

the temp.mp3 is stored in the same directory as the code, so if you want to store it somewhere else (like in a sub-folder just provide the path along with the filename).

p.s. gTTS takes time to do it’s work if the text is too big. DO NOT PANIC!

3. Reading the content out loud:

Now that we have our mail content into sound format, all we have to do is to play it. This will conclude the “reading the mail” part.

Now to play a sound in python, there are many liberaries but the one I like and prefer is the playsound library(because it worked and it took only one line to play).

If you also choose to go ahead with playsound, you need to do a pip install.

pip install playsound

Once playsound is installed, this is the three line code that does all the work of ‘reading’.

Okay, Now at this point, we have the power of accessing the mail, converting the content to speech and then play the speech to read out the mail.

Let’s Bring It All Together:

From the first part of the code where we access the content of the mail, we store the subject, the content and the sender details in variables and all in string format.

We see that in the create_sound function all we need to do is to pass a string and it will create the sound file(temp.mp3).

We want to read each mail one after the other and hence in the inner for loop(the ‘for response in msg’ one in IMAP section), we call our create_sound and then read functions like so..

check the lines to get the indentation of the code. This part comes after the ‘From = From.decode(encoding)’ line

Notice the os.remove(“temp.mp3”) part? Well I don’t want to keep the sound file on my system so I just delete it. Also it starts new message with a clean slate.

As the last part, save everything and run the main python file.

very important -> !!WARNING: CONNECT TO INTERNET!!

If everything goes well, You should be able to hear your message in a sweet computer lady voice…

Cheers! you have a sweet quick project ready to show off and amaze your friends or whatever you plan to do. Just remember that your gmail account is still at less security than recommended so after you are done, undo all the changes you made(for your own good) or do this all on a new gmail account and use it to get free subscriptions later..

See you next time with another story..!

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Django & DRF — Adding Fields To ListView

How To Install WordPress On a VPS server

How To Install WordPress On a VPS server

How to use Pandas pd.cut with Age example

Advice on Software Projects to Survive at COVID-19: Time to Skill up Continuous Testing

Monthly Technical Progress in September, 2021

Tech Q&A for the non-tech product manager — The API

The Escape Button is a Feature

How to implement Room persistence library in Android..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adarsh Dubey

Adarsh Dubey

More from Medium

How to Become Python Programmer

Utilizing Classes in Python

Python Short Problems

Create Word File with Python