How to get pure text from python email using imaplib

微笑、不失礼 提交于 2020-01-24 08:48:02

问题


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?


回答1:


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'].




回答2:


Look for the plain text part of the email message.

for payload in message.walk():
    if payload.get_content_type().lower() == 'text/plain':
        print(payload.get_payload())


来源:https://stackoverflow.com/questions/43586656/how-to-get-pure-text-from-python-email-using-imaplib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!