Schedule mailbox cleaning
Tags: #gmail #productivity #naas_drivers
Author: Sanjay Sabu

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 = "[email protected]"
2
password = "atsuwkylwfhucugw"
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

Setting the scheduler

1
naas.scheduler.add(recurrence="0 9 * * *") # Scheduler set for 9 am
Copied!

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="seen")
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
name_unique = np.unique(sender_name)
8
email_unique = np.unique(sender_email)
9
total_email = len(emails.get(criteria="seen")) + len(emails.get(criteria="unseen"))
10
c = 0
11
for i in np.unique(sender_name):
12
new_row = {'SENDER_NAME':i,'SENDER_EMAIL':sender_email[c],'COUNT':sender_name.count(i),'PERCENTAGE':round(((sender_name.count(i))/total_email)*100)}
13
result = result.append(new_row, ignore_index=True)
14
c+=1
15
result
Copied!

Email graph plot

1
fig = px.bar(x=result['COUNT'], y=result['SENDER_NAME'], orientation='h')
2
fig.show()
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 = []
Copied!

Updating the uid values

1
for i in range(len(dataframe)):
2
if data_from[i]['email'] == d_email:
3
uid.append(data_uid[i])
4
print(uid)
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="seen")
2
dataframe
Copied!
Copy link
Edit on GitHub