Date: Time:
Welcome, Log in by clicking  Here!

Parsing with python cont….

This is a copy of my code. I don't have my github set up.

import imaplib

import email

import yaml

with open(“credentials.yml”) as f:
content = f.read()

my_credentials = yaml.load(content, Loader=yaml.FullLoader)

user, password = my_credentials[“user”], my_credentials[“password”]

imap_url = ‘imap.gmail.com’

# Connection with GMAIL using SSL
my_mail = imaplib.IMAP4_SSL(imap_url)

# Log in using your credentials
my_mail.login(user, password)

# Select the Inbox to fetch messages
my_mail.select(‘Inbox’)

#Define Key and Value for email search
key = ‘FROM’
value = ‘paypal@emails.paypal.com’
_, data = my_mail.search(None, key, value) #Search for emails with specific key and value

mail_id_list = data[0].split() #IDs of all emails that we want to fetch

msgs = [] # empty list to capture all messages
#Iterate through messages and extract data into the msgs list
for num in mail_id_list:
typ, data = my_mail.fetch(num, ‘(RFC822)’) #RFC822 returns whole message (BODY fetches just body)
msgs.append(data)

# NOTE that a Message object consists of headers and payloads.

with open(“email_results.txt”, “w”, encoding=”utf-8″) as file:

for msg in msgs[::-1]:
for response_part in msg:
if isinstance(response_part, tuple): my_msg=email.message _from_bytes(response_part[1])
subject=my_msg[‘subject’]
sender=my_msg[‘from’]
body=””

for part in my_msg.walk():
if part.get_content_type()== ‘text/plain’:
body=part.get_payload( decode= True).decode(“utf-8”)
break # only get the first plain text response_part

#write email details to the file
file.write(“______________ _____________________\n”)
file.write(“subj: ” + str(subject) + “\n”)
file.write(“from: ” + str(sender) + “\n”)
file.write(“body: ” + str(body) + “\n”)

Posted on August 18, 2023 in coding by henryoviedo93
Tags: ,

Comments on 'Parsing with python cont….' (0)

Comments are closed.