Clean mailbox
Tags: #gmail #productivity #naas_drivers
Author: Martin Donadieu

Input

Import libraries

1
import naas
2
from naas_drivers import email
3
import pandas as pd
4
import numpy as np
5
import plotly.express as px
Copied!

Account credentials

1
username = "**********@gmail.com"
2
password = "**********"
3
smtp_server = "imap.gmail.com"
4
box = "INBOX"
Copied!
Note: You need to create an application password following this procedure - https://support.google.com/mail/answer/185833?hl=en

Model

Connect to email box

1
emails = naas_drivers.email.connect(username,
2
password,
3
username,
4
smtp_server)
Copied!

Get email list

1
dataframe = emails.get(criteria="ALL")
2
dataframe
Copied!

Creating dataframe and inserting values

1
sender_name = []
2
sender_email = []
3
for df in dataframe["from"]:
4
sender_name.append(df['name'])
5
sender_email.append(df['email'])
6
result = pd.DataFrame(columns = ['SENDER_NAME','SENDER_EMAIL','COUNT','PERCENTAGE'])
7
indexes = np.unique(sender_name, return_index=True)[1]
8
[sender_name[index] for index in sorted(indexes)]
9
10
indexes = np.unique(sender_email, return_index=True)[1]
11
[sender_email[index] for index in sorted(indexes)]
12
total_email = len(emails.get(criteria="ALL"))
13
c = 0
14
for i in sender_email:
15
new_row = {'SENDER_NAME':sender_name[c],'SENDER_EMAIL':i,'COUNT':sender_email.count(i),'PERCENTAGE':round(((sender_email.count(i))/total_email)*100)}
16
result = result.append(new_row, ignore_index=True)
17
c+=1
18
result = result.drop_duplicates()
19
result.sort_values(by=['COUNT'], inplace=True, ascending=False)
20
result
Copied!

Email graph plot

1
fig = px.bar(x=result['COUNT'], y=result['SENDER_EMAIL'], orientation='h')
2
fig.show()
Copied!

Deleting using uid

1
%%time
2
uid = [21] #uid of mails to be deleted
3
uid = map(str, uid)
4
flag = "DELETED"
5
for i in uid:
6
attachments = emails.set_flag(i, flag, True)
Copied!

Output

Deleting using email id

1
d_email = "[email protected]" # email id to be deleted
2
data_from = dataframe['from']
3
data_uid = dataframe['uid']
4
uid = []
5
for i in range(len(dataframe)):
6
if data_from[i]['email'] == d_email:
7
uid.append(data_uid[i])
Copied!

Deleting the emails

1
for i in uid:
2
attachments = emails.set_flag(i, "DELETED", True)
Copied!

Showing the upated email list

1
dataframe = emails.get(criteria="ALL")
2
dataframe
Copied!
Copy link
Edit on GitHub