Python 3 - How to extract only email body

7.8k Views Asked by At

I have this code to extract email body, but the output show the message and some encrypted information. I need help to get only the message.

Last version i've try the lib imaplib, but i don´t have sucess because all message it´s encrypted, so i change to poplib.

As future updates i want to add Subject, date and sender

#!/usr/bin/env python3
# -- coding: utf-8 --

import email
import poplib

login = input('Email: ')
password = input('Password: ')
pop_server = 'pop-mail.outlook.com'
pop_port = 995

mail_box = poplib.POP3_SSL(pop_server, pop_port)
mail_box.user(login)
mailbox.pass_(password)
numMessages = len(mail_box.list()[1])

if numMessages > 15:
    numMessages = 15
for i in range(15):
    (server_msg, body, octets) = mail_box.retr(i+1)
    for j in body:
        try:
            msg = email.message_from_string(j.decode("utf-8"))
            strtext = msg.get_payload()
            print(strtext)
        except:
            pass
1

There are 1 best solutions below

0
On

Using imaplib, if a is the raw email string:

msg = email.message_from_string(a)
if msg.is_multipart():
    for part in msg.walk():
        payload = part.get_payload(decode=True) #returns a bytes object
        strtext = payload.decode() #utf-8 is default
        print(strtext)
else:
    payload = msg.get_payload(decode=True)
    strtext = payload.decode()
    print(strtext)