<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ogheneyoma Okobiah</title>
    <description>The latest articles on Forem by Ogheneyoma Okobiah (@yomaokobiah).</description>
    <link>https://forem.com/yomaokobiah</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F269181%2F444369fd-fffb-4809-907a-2820d01e622c.png</url>
      <title>Forem: Ogheneyoma Okobiah</title>
      <link>https://forem.com/yomaokobiah</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/yomaokobiah"/>
    <language>en</language>
    <item>
      <title>Email Analysis with Python 3 (Part II)</title>
      <dc:creator>Ogheneyoma Okobiah</dc:creator>
      <pubDate>Tue, 29 Jun 2021 18:36:32 +0000</pubDate>
      <link>https://forem.com/yomaokobiah/email-analysis-with-python-3-part-ii-1ado</link>
      <guid>https://forem.com/yomaokobiah/email-analysis-with-python-3-part-ii-1ado</guid>
      <description>&lt;p&gt;Welcome back! This is a sequel to Part I where we covered making changes to our Gmail account, getting the subject of the email and its sender and visualising some of the email data.&lt;br&gt;
The emphasis of this part is on getting the body of the emails. &lt;/p&gt;

&lt;p&gt;If you read the first part and tried it out, I hope it was without hitches. If you did not but you are interested in learning how to get the body of the email, you can follow from here. Let's jump right in.&lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Python 3&lt;/li&gt;
&lt;li&gt;Pandas&lt;/li&gt;
&lt;li&gt;A gmail account&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Getting The Data
&lt;/h2&gt;

&lt;p&gt;This was covered in  &lt;a href="https://yomaokobiah.com/email-analysis-using-python-3-part-i"&gt;Part I&lt;/a&gt; as it involves making changes to your Gmail account in order for IMAPLib to work with it.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Importing the required libraries to get the email data
&lt;/h3&gt;

&lt;p&gt;Here we import the libraries we need which are imaplib, email, getpass and pandas. You may want to install pandas using &lt;code&gt;pip install pandas&lt;/code&gt; if you do not have it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import imaplib
import email
import getpass
import pandas as pd
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 2: Gaining access to the email server
&lt;/h3&gt;

&lt;p&gt;Here we log into the email server with our credentials.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 3: Specifying the mailbox to get data from.
&lt;/h3&gt;

&lt;p&gt;Here we print out the mail list to see the available mailboxes and we select one.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(mail.list())
mail.select("inbox")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 4:&lt;/strong&gt; Searching and Fetching the data
&lt;/h3&gt;

&lt;p&gt;The block of code below searches the selected mailbox with the given criteria, fetches the emails and stores it to the variable messages.&lt;br&gt;
Here I am searching for emails from FreeCodeCamp.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result, numbers = mail.search(None, '(FROM "quincy@freecodecamp.org")')
uids = numbers[0].split()
uids = [id.decode("utf-8") for id in uids ]
result, messages = mail.fetch(','.join(uids) ,'(RFC822)')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 5:&lt;/strong&gt; Preparing the data to be exported
&lt;/h3&gt;

&lt;p&gt;The block of code below loops through the fetched emails, gets the date it was received, who sent it, the subject of the mail and the body of the mail. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We use the &lt;code&gt;walk()&lt;/code&gt; method in the email library to get the parts and subparts of the message. &lt;/li&gt;
&lt;li&gt;We use the &lt;code&gt;get_content_type()&lt;/code&gt; method to get the email body maintype/subtype.&lt;/li&gt;
&lt;li&gt;We use the &lt;code&gt;get_payload()&lt;/code&gt; to get a string or message instance of the part.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;body_list =[]
date_list = []
from_list = [] 
subject_list = []
for _, message in messages[::2]:
  email_message = email.message_from_bytes(message)
  email_subject = email.header.decode_header(email_message['Subject'])[0]
  for part in email_message.walk():
    if part.get_content_type() == "text/plain" :
        body = part.get_payload(decode=True)
        body = body.decode("utf-8")
        body_list.append(body)
    else:
        continue
    if isinstance(email_subject[0],bytes):
      decoded = email_subject.decode(errors="ignore")
      subject_list.append(decoded)
    else:
      subject_list.append(email_subject[0])
  date_list.append(email_message.get('date'))
  fromlist = email_message.get('From')
  fromlist = fromlist.split("&amp;lt;")[0].replace('"', '')
  from_list.append(fromlist)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here we convert the objects in date_list to datetime objects using the &lt;code&gt;to_datetime()&lt;/code&gt; method, because the time has its UTC format attached, we sliced off the UTC format.&lt;br&gt;
The retrieved information is then converted to a pandas DataFrame and exported to a CSV file.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;date_list = pd.to_datetime(date_list)
date_list = [item.isoformat(' ')[:-6]for item in date_list]
data = pd.DataFrame(data={'Date':date_list,'Sender':from_list,'Subject':subject_list, 'Body':body_list})
data.to_csv('emails.csv',index=False)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Data Cleaning
&lt;/h2&gt;

&lt;p&gt;Now we are going to view the data and clean it where necessary to make it readable. First we read in the csv file and view it:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data = pd.read_csv("\emails.csv")
data.head()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The output can be seen below, going through there are escape characters in the Body column:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--DHBhPtgn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1624956152300/IGFYoIe_U.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--DHBhPtgn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1624956152300/IGFYoIe_U.png" alt="Screenshot 2021-06-29 at 09.41.50.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The function below removes the escape characters in the text. In this case &lt;code&gt;"\r\n"&lt;/code&gt; as seen in the screenshot above. This makes the text more readable.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def clean_data(data, column, i):
    data.loc[i, column] = data.loc[i, column].split("\r\n")
    new_string = " ".join(data.loc[i, column])
    new_string = new_string.split("'',")
    data[column][i:i+1] = pd.DataFrame(data = new_string)
    return data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The code below is using the function above to clean every email body in the file.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for n in range(len(data)):
    new_data = clean_data(data, column = "Body", i = n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The output can be seen below:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--iCdsfyu2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1624956624943/DkKDceSpT.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--iCdsfyu2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1624956624943/DkKDceSpT.png" alt="Screenshot 2021-06-29 at 09.50.02.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You are advised to rewrite a new function according to the escape characters you may find in the Subject or Body of the email you retrieved. &lt;/p&gt;
&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I encountered ERRORS while writing this, the most recurring one was being unable to sign in even after following the instructions on the Google help page. This problem was encountered because I have more than one Gmail account signed in, and I was not using my default email. In case you encounter the same, the solution is outlined below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The instruction said, "If the tips above didn't help, visit &lt;a href="https://www.google.com/accounts/DisplayUnlockCaptcha"&gt;https://www.google.com/accounts/DisplayUnlockCaptcha&lt;/a&gt; and follow the steps on the page." This opens on a new tab.&lt;/li&gt;
&lt;li&gt;The link on the new tab was "&lt;a href="https://accounts.google.com/b/0/DisplayUnlockCaptcha"&gt;https://accounts.google.com/b/0/DisplayUnlockCaptcha&lt;/a&gt;" where the digit 0 is for the default account logged in. &lt;/li&gt;
&lt;li&gt;Check your accounts in the order in which they are listed and change the digit accordingly (e.g.,”1" is the next email and so on).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the full code on GitHub below:&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i3JOwpme--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev.to/assets/github-logo-ba8488d21cd8ee1fee097b8410db9deaa41d0ca30b004c0c63de0a479114156f.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/yomaokobiah"&gt;
        yomaokobiah
      &lt;/a&gt; / &lt;a href="https://github.com/yomaokobiah/email_analysis"&gt;
        email_analysis
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Email data analysis
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;h1&gt;
email_analysis&lt;/h1&gt;
&lt;p&gt;Email data analysis&lt;/p&gt;
&lt;/div&gt;

  &lt;/div&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/yomaokobiah/email_analysis"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;



&lt;p&gt;Thank you for getting to the end of this article, I hope you had fun trying it out.&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt; &lt;a href="https://stackoverflow.com/questions/2230037/how-to-fetch-an-email-body-using-imaplib-in-python"&gt;Stack Overflow; How to fetch an email body using imaplib in python?&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/library/email.message.html"&gt;Email Library Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.python.org/3/library/imaplib.html"&gt;IMAP Library Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
    </item>
    <item>
      <title>Email Analysis Using Python 3 (Part I)</title>
      <dc:creator>Ogheneyoma Okobiah</dc:creator>
      <pubDate>Sat, 19 Jun 2021 19:34:19 +0000</pubDate>
      <link>https://forem.com/yomaokobiah/email-analysis-using-python-3-part-i-275e</link>
      <guid>https://forem.com/yomaokobiah/email-analysis-using-python-3-part-i-275e</guid>
      <description>&lt;p&gt;There is a lot of data out there, mostly unstructured. Emails are a great source of communication data as such there is no limit to what we can harness from it.&lt;br&gt;
At the end of this tutorial you would be able to get email data for insights.&lt;/p&gt;
&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Python 3&lt;/li&gt;
&lt;li&gt;Pandas&lt;/li&gt;
&lt;li&gt;Matplotlib&lt;/li&gt;
&lt;li&gt;Seaborn&lt;/li&gt;
&lt;li&gt;Wordcloud&lt;/li&gt;
&lt;li&gt;A gmail account&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Getting The Data
&lt;/h2&gt;

&lt;p&gt;There are several ways to go achieve the aim of this article; find below, how I did mine.&lt;/p&gt;

&lt;p&gt;Here a Gmail account is being used; for the imaplib script to work I made the following changes to my account; enabled IMAP and turned on less secured apps.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, open Gmail, click on the &lt;strong&gt;settings&lt;/strong&gt; ⚙️ icon and click See all settings to enable IMAP.&lt;/li&gt;
&lt;li&gt;On the next page, click on the &lt;strong&gt;Forwarding and POP/IMAP&lt;/strong&gt; tab.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;IMAP Access&lt;/strong&gt; section, select &lt;strong&gt;Enable IMAP&lt;/strong&gt;. Then click &lt;strong&gt;Save changes&lt;/strong&gt;. If you need more help, kindly visit this &lt;a href="https://support.google.com/mail/answer/7126229?hl" rel="noopener noreferrer"&gt;Gmail help page&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;To turn on less secured apps, navigate to your Google dashboard by clicking on your account avatar in the upper right-hand corner of your screen and then click &lt;strong&gt;My Account&lt;/strong&gt; or navigate to myaccount.google.com.&lt;/li&gt;
&lt;li&gt;Then choose &lt;strong&gt;Sign-in &amp;amp; security&lt;/strong&gt;, scroll down until you see the option Allow less secure apps, and turn the access on.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you still can’t log in after doing the above, kindly visit here for official Google &lt;a href="https://support.google.com/mail/answer/7126229?visit_id=637574811006268631-897992682&amp;amp;rd=2#cantsignin&amp;amp;zippy=%2Ci-cant-sign-in-to-my-email-client" rel="noopener noreferrer"&gt;help support&lt;/a&gt;. &lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Importing the required libraries to get the email data
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;imaplib is an Internet Message Access Protocol (IMAP) library&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;email is a python library that parses, handles and generates email messages.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;getpass is a python library that contains utilities to get password or current username&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;pandas is a python library for data manipulation and analysis.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import imaplib
import email
import getpass
import pandas as pd
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 2: Gaining access to the email address
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;em&gt;username&lt;/em&gt; is the email address. &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;password&lt;/em&gt; is the password to the email address when prompted. [If you don't want to use the getpass package, you can enter your password as a string.]&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;mail&lt;/em&gt; is the email server we're going to connect to and it varies, for this tutorial we're using gmail.&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;mail.login&lt;/em&gt; logs into the server using the provided credentials.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 3: Specifying the mailbox to get data from.
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;mail.list()&lt;/code&gt; is a method that gives a list of the mailboxes - i.e inbox, draft and so on in the email address.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;mail.select()&lt;/code&gt; is a method that takes an argument of the mailbox you want to get data from.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print(mail.list())
mail.select("inbox")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 4: Searching and Fetching the data
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Line 1:&lt;/strong&gt; mail.uid() is a method whose first argument is the command you want to execute, in this case the command is "search". The rest of the arguments are used for the search. (Search gives from oldest to recent)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 1:&lt;/strong&gt; result is an exit code of the command while numbers is a list that contains an object of type byte.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 2:&lt;/strong&gt; is a list of every section in numbers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 3:&lt;/strong&gt; is a list of decoded bytes&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 4:&lt;/strong&gt; is a slice of the recent 100 items (recall that search orders it from oldest to recent). &lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 5:&lt;/strong&gt; the command we want to execute is "fetch" and store it in messages. We're fetching the subject of the messages in this case.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result, numbers = mail.uid('search', None, "ALL")
uids = numbers[0].split()
uids = [id.decode("utf-8") for id in uids ]
uids = uids[-1:-101:-1]
result, messages = mail.uid('fetch', ','.join(uids), '(BODY[HEADER.FIELDS (SUBJECT FROM DATE)])')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  Step 5: Preparing the data to be exported
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Line 1-3:&lt;/strong&gt; empty lists for the data we specified in messages.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 4:&lt;/strong&gt; looping through the content of the message we fetched. Using a step of two because it returned a tuple of two items.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 5:&lt;/strong&gt; parsing the bytes email to message object.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 6-11:&lt;/strong&gt; msg is in bytes, in order to use it it had to be decoded to a format we can read.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 12:&lt;/strong&gt; adding the dates to date_list.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 13-15:&lt;/strong&gt; getting the sender detail, it's in the format "Sender name"  hence the split and replace methods are used to get only the "Sender name".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 16-19:&lt;/strong&gt; converting the objects in date_list to datetime objects, because the time has it's UTC format attached, a new list was created and the UTC format was sliced off from each object in the list.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 20-22:&lt;/strong&gt; checking the length of created lists, because arrays have to be the same length.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Line 23-25:&lt;/strong&gt; converting the lists to a dictionary and then a pandas dataframe, viewing it and saving it for download.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;date_list = []
from_list = [] 
subject_text = []
for i, message in messages[::2]:
    msg = email.message_from_bytes(message)
    decode = email.header.decode_header(msg['Subject'])[0]
    if isinstance(decode[0],bytes):
        decoded = decode[0].decode()
        subject_text.append(decoded)
    else:
        subject_text.append(decode[0])
    date_list.append(msg.get('date'))
    fromlist = msg.get('From')
    fromlist = fromlist.split("&amp;lt;")[0].replace('"', '')
    from_list1.append(fromlist)
date_list = pd.to_datetime(date_list)
date_list1 = []
for item in date_list:
    date_list1.append(item.isoformat(' ')[:-6])
print(len(subject_text))
print(len(from_list))
print(len(date_list1))
df = pd.DataFrame(data={'Date':date_list1, 'Sender':from_list, 'Subject':subject_text})
print(df.head())
df.to_csv('inbox_email.csv',index=False)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Visualisation
&lt;/h2&gt;

&lt;p&gt;Now that we have a the email data in CSV format, we can read the data using pandas, and visualise it.&lt;br&gt;
There are several Python data visualisation libraries, but here I used Wordcloud, Matplotlib and Seaborn. I wanted to see an infographic on the most used words in the subjects of my emails and here is how I did it.&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 1: Reading and viewing the CSV
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590503891198%2FtEDPANCq-.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590503891198%2FtEDPANCq-.png" alt="read.png"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 2: Getting statistical data
&lt;/h3&gt;

&lt;p&gt;I used the the describe method to get the statistical data, unique values and all to get insight on the what's in the data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590503684511%2F0UnaE1iPk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590503684511%2F0UnaE1iPk.png" alt="describee.png"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 3: Creating new variables
&lt;/h3&gt;

&lt;p&gt;I created two variables; Time and SinceMid. SinceMid is the number of hours after midnight.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;(Note: The time can be removed from the date column completely)&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from datetime import datetime
FMT = '%H:%M:%S'
emails['Time'] = emails['Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%-d%H:%M:%S').strftime(FMT))
emails['SinceMid'] = emails['Time'].apply(lambda x: (datetime.strptime(x, FMT) - datetime.strptime("00:00:00", FMT)).seconds) / 60 / 60
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590539232938%2F4AdcGk2Uf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590539232938%2F4AdcGk2Uf.png" alt="time.png"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Step 4: The plots
&lt;/h3&gt;

&lt;p&gt;I created a wordcloud image of the most used words in the subjects of my mails. In this example there are no stopwords, stopwords are usually filtered out as most times they're not informative.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from wordcloud import WordCloud
import matplotlib.pyplot as plt


# Create a list of words
text = ""
for item in emails["Subject"]:
    if isinstance(item,str):
        text += " " + item
    text.replace("'", "")
    text.replace(",","")
    text.replace('"','')


# Create the wordcloud object
wordcloud = WordCloud(width=800, height=800, background_color="white")

# Display the generated image:
wordcloud.generate(text)
plt.figure(figsize=(8,8))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.margins(x=0, y=0)
plt.title("Most Used Subject Words", fontsize=20,ha="center", pad=20)
plt.show()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here's the output:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590540248193%2FcRq4Dar2T.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590540248193%2FcRq4Dar2T.png" alt="download.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I created a histogram of the hours after midnight using seaborn.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import seaborn as sns
sns.distplot(emails["SinceMid"],bins=20)
plt.title("Hours since midnight")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Here is the histogram:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590540894969%2FIU6EtxMoC.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1590540894969%2FIU6EtxMoC.png" alt="download_.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can check out &lt;a href="https://python-graph-gallery.com/" rel="noopener noreferrer"&gt;python gallery&lt;/a&gt; for more possible visualisations.&lt;/p&gt;
&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I had fun writing this, I hope you did too while reading it. This goes without saying, I encountered ERRORS while doing this [some of them I had never seen before]. When you get error messages, a good starting point is using the print statement to get insight and then googling the error message. &lt;br&gt;
The Part II will also be published on this blog, it would focus on getting the body of the mail and not the subject as this one.&lt;/p&gt;

&lt;p&gt;The full code can be found below:&lt;/p&gt;


&lt;div class="ltag-github-readme-tag"&gt;
  &lt;div class="readme-overview"&gt;
    &lt;h2&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev.to%2Fassets%2Fgithub-logo-5a155e1f9a670af7944dd5e12375bc76ed542ea80224905ecaf878b9157cdefc.svg" alt="GitHub logo"&gt;
      &lt;a href="https://github.com/yomaokobiah" rel="noopener noreferrer"&gt;
        yomaokobiah
      &lt;/a&gt; / &lt;a href="https://github.com/yomaokobiah/email_analysis" rel="noopener noreferrer"&gt;
        email_analysis
      &lt;/a&gt;
    &lt;/h2&gt;
    &lt;h3&gt;
      Email data analysis
    &lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class="ltag-github-body"&gt;
    
&lt;div id="readme" class="md"&gt;
&lt;div class="markdown-heading"&gt;
&lt;h1 class="heading-element"&gt;email_analysis&lt;/h1&gt;

&lt;/div&gt;

&lt;p&gt;Email data analysis&lt;/p&gt;

&lt;/div&gt;
&lt;br&gt;
&lt;br&gt;
  &lt;/div&gt;
&lt;br&gt;
  &lt;div class="gh-btn-container"&gt;&lt;a class="gh-btn" href="https://github.com/yomaokobiah/email_analysis" rel="noopener noreferrer"&gt;View on GitHub&lt;/a&gt;&lt;/div&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;br&gt;


&lt;p&gt;Thank you for reading up to this point.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Disclaimer: I encourage you to experiment outside what's written here, if you encounter bugs and you feel like getting me involved [after Googling], send me a DM on  &lt;a href="https://twitter.com/yomdroid" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt; I'd be happy to learn something new. Thank you in anticipation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;References/Credits&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://developer.ibm.com/tutorials/pattern-analysis-of-emails-using-python/" rel="noopener noreferrer"&gt;An IBM tutorial on pattern email analysis using python 2&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4_SSL" rel="noopener noreferrer"&gt;IMAPLib Documentation&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.python.org/3/library/email.html" rel="noopener noreferrer"&gt;Email package Documentation&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
    </item>
    <item>
      <title>Decluttering Mailbox Using Python</title>
      <dc:creator>Ogheneyoma Okobiah</dc:creator>
      <pubDate>Sat, 29 May 2021 09:32:29 +0000</pubDate>
      <link>https://forem.com/yomaokobiah/decluttering-mailbox-using-python-44l8</link>
      <guid>https://forem.com/yomaokobiah/decluttering-mailbox-using-python-44l8</guid>
      <description>&lt;p&gt;I've had so many unread emails in my inbox because they were promotional content, or I was just too lazy to read when they came in. Now imagine opening your mailbox and seeing over a thousand emails — screams in 1917!! How can I declutter as fast as possible?&lt;/p&gt;

&lt;p&gt;Now I know Gmail has a delete feature but I believe we're meant to "automate the boring stuff with python" and you may learn something new or not.&lt;/p&gt;

&lt;p&gt;In this article, I will show you how to set up a script to send unread/unwanted messages from your inbox to trash using IMAPlib and how to delete unread/unwanted messages using IMAPClient permanently.&lt;/p&gt;

&lt;p&gt;Let's jump right into it!&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Python&lt;/li&gt;
&lt;li&gt;Gmail account &lt;/li&gt;
&lt;li&gt;ImapClient [optional]&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Setting up your Gmail account
&lt;/h2&gt;

&lt;p&gt;IMAP stands for Internet Mail Access protocol. According to Wikipedia, it is "an Internet standard protocol used by email clients to retrieve email messages from a mail server over a TCP/IP connection.”&lt;/p&gt;

&lt;p&gt;To get started, we need to set up a Gmail account for the process to be successful. I made the following changes to my Gmail account, which enabled IMAP and turned on less secured apps.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First, open Gmail, click on the &lt;strong&gt;settings&lt;/strong&gt; ⚙️ icon and click See all settings to enable IMAP.&lt;/li&gt;
&lt;li&gt;On the next page, click on the &lt;strong&gt;Forwarding and POP/IMAP&lt;/strong&gt; tab.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;IMAP Access&lt;/strong&gt; section, select &lt;strong&gt;Enable IMAP&lt;/strong&gt;. Then click &lt;strong&gt;Save changes&lt;/strong&gt;. If you need more help, kindly visit this &lt;a href="https://support.google.com/mail/answer/7126229?hl"&gt;Gmail help page&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;To turn on less secured apps, navigate to your Google dashboard by clicking on your account avatar in the upper right-hand corner of your screen and then click &lt;strong&gt;My Account&lt;/strong&gt; or navigate to myaccount.google.com.&lt;/li&gt;
&lt;li&gt;Then choose &lt;strong&gt;Sign-in &amp;amp; security&lt;/strong&gt;, scroll down until you see the option Allow less secure apps, and turn the access on.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you still can’t log in after doing the above, kindly visit here for official Google &lt;a href="https://support.google.com/mail/answer/7126229?visit_id=637574811006268631-897992682&amp;amp;rd=2#cantsignin&amp;amp;zippy=%2Ci-cant-sign-in-to-my-email-client"&gt;help support&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  How to trash your emails using IMAPlib
&lt;/h2&gt;

&lt;p&gt;The IMAP library is an inbuilt python library used for accessing and manipulating emails over IMAP. The code below logs you into the desired email address. After logging in, we select the desired mailbox to see a list of all available mailboxes to select from using &lt;code&gt;print(mail.list())&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Starter code for IMAPlib
&lt;/h3&gt;

&lt;p&gt;The criterion for emails to be sent to the trash in this section are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Unread emails.&lt;/li&gt;
&lt;li&gt;Emails based on a specific subject.&lt;/li&gt;
&lt;li&gt;Emails based on a specific sender.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import imaplib
import getpass
username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
mail.select("INBOX")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Trashing all unread emails
&lt;/h3&gt;

&lt;p&gt;The code below sends all unread emails to the trash. You never can tell if you need any email, so you have thirty (30) days before Gmail removes it from the trash. First, we search through the emails setting the criteria to "UNSEEN" (which is the flag for unread messages). The variable result is an exit code of the command, while messages are a list that contains an object of type byte. Finally, we loop through the emails in the list and put them in the trash folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;results, messages = mail.search(None, 'UNSEEN')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Trashing all emails with a particular subject
&lt;/h3&gt;

&lt;p&gt;Here, we search the selected mailbox using our desired criteria. You should replace &lt;code&gt;"Title"&lt;/code&gt; with your desired subject in the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;results, messages = mail.search(None, '(SUBJECT "Title")')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Trashing all emails from a specific sender
&lt;/h3&gt;

&lt;p&gt;Here, we search the mailbox using our desired criteria. You should replace &lt;code&gt;"abc@xyz.com"&lt;/code&gt; with your preferred email address in the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;results, messages = mail.search(None, '(FROM "abc@xyz.com")')
messages = messages[0].split()
for x in messages:
  result, message = mail.store(x, '+X-GM-LABELS', '\\Trash')
mail.close()
mail.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I'll briefly talk about the methods used.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;search()&lt;/code&gt; is a method used to look through the selected mailbox, it takes two arguments; a charset and a criterion. The charset can be set to None.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;store()&lt;/code&gt; is a method used to change the flag or label of a message; it takes three arguments; the message, the command, and the flag.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;close()&lt;/code&gt; is a method used to close the selected mailbox.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;logout()&lt;/code&gt; is a method used to close the connection to the server.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;'+X-GM-LABELS'&lt;/code&gt; a label is treated as a folder so that changes can be made to messages using IMAP commands.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to permanently delete your emails using IMAPClient
&lt;/h2&gt;

&lt;p&gt;While researching this article, I came across the IMAPClient library. From its &lt;a href="https://imapclient.readthedocs.io/en/2.2.0/"&gt;official documentation&lt;/a&gt;, I discovered that: "although IMAPClient actually uses the imaplib module from the Python standard library under the hood, it provides a different API."&lt;/p&gt;

&lt;p&gt;Using IMAPClient to delete emails will not send the emails to the trash folder; they will be permanently deleted. You should BE SURE you want to permanently delete your emails before using any code snippets here.&lt;/p&gt;

&lt;h3&gt;
  
  
  Starter Code for IMAPClient
&lt;/h3&gt;

&lt;p&gt;To use IMAPClient, you have to install the package using the command below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install imapclient
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we import the library and set the server of our email address.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from imapclient import IMAPClient
import getpass
server = IMAPClient('imap.gmail.com', use_uid=True)
username =  input("Enter the email address: ")
password = getpass.getpass("Enter password: ")
server.login(username, password)
select_info = server.select_folder("INBOX")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The criterion for emails to be sent to the trash in this section are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Unread emails.&lt;/li&gt;
&lt;li&gt;Emails based on a specific subject.&lt;/li&gt;
&lt;li&gt;Emails based on a specific sender.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Permanently deleting all unread emails
&lt;/h3&gt;

&lt;p&gt;The code below permanently deletes all unread emails.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;messages = server.search("UNSEEN")
for x in messages:
  server.delete_messages(x)
server.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Permanently deleting all emails with a particular subject
&lt;/h3&gt;

&lt;p&gt;We search the selected mailbox using our desired criteria. You should replace &lt;code&gt;"Title"&lt;/code&gt; with your desired subject in the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;messages = server.search(['SUBJECT', 'Title'])
for x in messages:
  server.delete_messages(x)
server.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Permanently deleting all emails from a specific sender
&lt;/h3&gt;

&lt;p&gt;We search the mailbox using our desired criteria. You should replace &lt;code&gt;"abc@xyz.com"&lt;/code&gt; with your preferred email address in the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;messages = server.search(['FROM', 'abc@xyz.com'])
for x in messages:
  server.delete_messages(x)
server.logout()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Note
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Logging out of the server is important&lt;/li&gt;
&lt;li&gt;To access all emails while using IMAPlib, use &lt;code&gt;mail.select('"[Gmail]/All Mail"').&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Ensure you turn off less secure apps.&lt;/li&gt;
&lt;li&gt;A lot of emails were harmed in the process of making this tutorial 😂.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;I had fun writing this, and I hope you did too while reading it. I also encountered ERRORS while writing the script. The most recurring one was being unable to sign in even after following the instructions on the Google help page. This problem was encountered because I have more than one Gmail account signed in, and I was not using my default email. In case you encounter the same, the solution is outlined below:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The instruction said, "If the tips above didn't help, visit &lt;a href="https://www.google.com/accounts/DisplayUnlockCaptcha"&gt;https://www.google.com/accounts/DisplayUnlockCaptcha&lt;/a&gt; and follow the steps on the page." This opens on a new tab.&lt;/li&gt;
&lt;li&gt;The link on the new tab was "&lt;a href="https://accounts.google.com/b/0/DisplayUnlockCaptcha"&gt;https://accounts.google.com/b/0/DisplayUnlockCaptcha&lt;/a&gt;" where the digit 0 is for the default account logged in. &lt;/li&gt;
&lt;li&gt;Check your accounts in the order in which they are listed and change the digit accordingly (e.g.,”1" is the next email and so on).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can find the complete script on &lt;a href="https://github.com/Yomdroid/Decluttering_Email"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thank you for reading this tutorial!&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4.unselect"&gt;IMAP Library Documentation&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://gist.github.com/giovaneliberato/b3ebce305262888633c1"&gt;Giovane Liberato Github Gist&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://imapclient.readthedocs.io/en/2.2.0/index.html"&gt;IMAPClient Documentation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>python</category>
      <category>email</category>
    </item>
  </channel>
</rss>
