Python3与Python2解析电子邮件正文的方式不同

时间:2019-05-29 00:07:36

标签: python python-3.x string python-2.7 imaplib

当前,我正在研究一个电子邮件解析器,该解析器仅使用imaplib建立与我的gmail帐户的连接并阅读新电子邮件。

一切正常,并且使用python2(即“ python myScript.py”)运行脚本时,结果符合预期

例如,如果我收到一封电子邮件,如下所示:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject

Test1
Test2

我的脚本将按预期输出:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: Test1
Test2

但是,使用python3(即“ python3 myScript.py”)运行此命令时,结果不一样,转义字符显示在消息正文中,请参见下文:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: b'Test1\r\nTest2\r\n'

下面是用于此过程的代码:

def readMailbox(mail):
    res, data = mail.uid('search', None, 'UNSEEN')
    i = len(data[0].split())

    for x in range(i):
        latestEmailUID = data[0].split()[x]
        result, emailData = mail.uid('fetch', latestEmailUID, '(RFC822)')
        emailMessage = email.message_from_string(emailData[0][1].decode('utf-8'))

        emailFrom = str(email.header.make_header(email.header.decode_header(emailMessage['From'])))
        emailTo = str(email.header.make_header(email.header.decode_header(emailMessage['To'])))
        subject = str(email.header.make_header(email.header.decode_header(emailMessage['Subject'])))

        # Body details
        for part in emailMessage.walk():
            if part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True)
                print('To: %s' % emailTo)
                print('From: %s' % emailFrom)
                print('Subject: %s' % subject)
                print('Body: %s' % body)

我将需要能够捕获字符串主体而不显示转义字符以供以后使用。谁能向我解释为什么会这样,或者我需要在python3中做些不同的事情以便我可以正常解析电子邮件的正文?

感谢您的宝贵时间,向正确方向提供的任何指导将不胜感激!

1 个答案:

答案 0 :(得分:1)

字符串前面的'b'表示它仍然是一个字节数组,尚未被解码。

像其他字符串一样,以'utf-8'进行解码,它应按预期输出特殊字符

...
body = part.get_payload(decode=True)
body = body.decode('utf-8')
print('Body: %s' % body)
...