script to get text of the email email in python

Here is how you can fetch the text of an email in Python:

main.py
import imaplib
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('your_email@gmail.com', 'your_password')
mail.select('inbox')

result, data = mail.search(None, 'ALL')

ids = data[0]  # list of emails
id_list = ids.split()

latest_email_id = id_list[-1]
result, data = mail.fetch(latest_email_id, "(RFC822)")

raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)

#to get the text of the email, traverse the payload of the email
def getText(email_message_instance):
    payload = email_message_instance.get_payload()
    if isinstance(payload, list):
        return '\n'.join([getText(subpart) for subpart in payload])
    else:
        return payload

email_text = getText(email_message)

print(email_text)
748 chars
30 lines

Replace 'your_email@gmail.com' and 'your_password' with your email and password, respectively. Additionally, you will need to change the email provider and the search criteria ('ALL' in the example) based on your specific use case.

related categories

gistlibby LogSnag