Search code examples
pythonemailtextimaplib

How to get pure text from python email using imaplib


I am wondering how to get pure text form python email using imaplib. What i have so far:

from datetime import datetime
import imaplib ,email
IMAP_SERVER = 'imap.gmail.com'
EMAIL_ACCOUNT = "example@gmail.com"
PASSWORD = "password"
   rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print("No messages found!")
        return

    if data != ['']:  # if not empty list means messages exist
        for num in data[0].split():
            rv, data = M.fetch(num, '(RFC822)') #(BODY[HEADER.FIELDS (SUBJECT FROM)])
            if rv != 'OK':
                print("ERROR getting message", num)
                return

            message = email.message_from_bytes(data[0][1])
            text = ""
            if message.is_multipart():
                for payload in message.get_payload():
                    text = payload.get_payload()
            else:
                    text = message.get_payload()

            res = {
                'From': email.utils.parseaddr(message['From'])[1],
                'From name': email.utils.parseaddr(message['From'])[0],
                'Time': datetime.fromtimestamp(email.utils.mktime_tz(email.utils.parsedate_tz(message['Date']))),
                'To': message['To'],
                'Subject': email.header.decode_header(message["Subject"])[0][0],
                'Text': text
            }
            print(res['Text'])

    else:
        print("Nothing to work with.")

If i do it this way, the code works, but i get

<div dir="ltr">test 3 body</div>

as an output. Is there any way to get purely "test 3 body" out?


Solution

  • If you just stack on removing html tags from string you have to use regular expression like here:

    import re
    
    s = '<div dir="ltr">test 3 body</div>'
    print(re.sub('<[^<]+?>', '', s))
    

    Output: test 3 body

    s has to be your res['Text'].