'Extracting data from emails reveals only the data of the last day only the "subject name" took place after printing it
import imaplib
import email
import getpass
import pandas as pd
#The usual process of email reading:
username = 'xxxxxxxxxxxxx'
password = 'xxxxxxxxxx'
mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login(username, password)
mail.select("inbox")
#determining the needed subject:
result, numbers = mail.search(None, '(Subject "*warning")')
uids = numbers[0].split()
uids = [id.decode("utf-8") for id in uids ]
result, messages = mail.fetch(','.join(uids) ,'(RFC822)')
#creating the lists to fetch the following:
body_list =[]
to_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')
from_list.append(fromlist)
tolist = email_message.get('to')
to_list.append(tolist)
date_list = pd.to_datetime(date_list)
date_list = [item.isoformat(' ')[:-6]for item in date_list]
a = {'Date':date_list,'Sender':from_list,'Receiver':to_list,'Subject':subject_list,
'Body':body_list}
data = pd.DataFrame.from_dict(a, orient='index')
data.to_csv('emails.csv',index=False)
data = pd.read_csv(r"C:\emails.csv").transpose()
print(data)
The extracted data frame is for the last day the subject name had appeared only and the other days are not recorded which make it useful, I doubt that there is something wrong when it comes to lists, kindly help me to fix this "Thanks in advance".
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
