在python

时间:2018-11-27 16:56:05

标签: python character-encoding gmail email-parsing quoted-printable

我想用Python解码“ quoted-printable”编码的字符串,但是我似乎停留在某个地方。

我根据以下代码从我的gmail帐户中提取了某些邮件:

import imaplib
import email
import quopri


mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('mail@gmail.com', '*******')
mail.list()

mail.select('"[Gmail]/All Mail"') 



typ, data = mail.search(None, 'SUBJECT', '"{}"'.format('123456'))

data[0].split()

print(data[0].split())

for e_mail in data[0].split():
    typ, data = mail.fetch('{}'.format(e_mail.decode()),'(RFC822)')
    raw_mail = data[0][1]
    email_message = email.message_from_bytes(raw_mail)
    if email_message.is_multipart():
        for part in email_message.walk():
            if part.get_content_type() == 'text/plain':
                if part.get_content_type() == 'text/plain':
                    body = part.get_payload()
                    to = email_message['To']

                    utf = quopri.decodestring(to)

                    text = utf.decode('utf-8')
                    print(text)
.
.
.

例如,如果我打印'to',则如果'to'具有诸如é,á,ó...之类的字符,则结果为:

=?UTF-8?B?UMOpdGVyIFBldMWRY3o=?=

我可以使用 quopri 库成功解码“ body”带引号的可打印编码字符串,如下所示:

quopri.decodestring(sometext).decode('utf-8') 

,但是相同的逻辑不适用于电子邮件的其他部分,例如,收件人,发件人,主题。

有人知道提示吗?

2 个答案:

答案 0 :(得分:0)

您正在尝试使用utf-8解码拉丁字符。您得到的输出是base64。内容为:

找不到可打印的字符,尝试使用其他源字符集,或将数据作为文件上传以进行二进制解码。

尝试一下。 Python: Converting from ISO-8859-1/latin1 to UTF-8

答案 1 :(得分:0)

这可以解决它:

from email.header import decode_header
      def mail_header_decoder(header):
            if header != None:
                mail_header_decoded = decode_header(header)
                l=[]  
                header_new=[]
                for header_part in mail_header_decoded: 
                    l.append(header_part[1])

                if all(item == None for item in l):
                    # print(header)
                    return header
                else:
                    for header_part in mail_header_decoded:
                        header_new.append(header_part[0].decode())
                    header_new = ''.join(header_new) # convert list to string
                    # print(header_new)
                    return header_new
相关问题