0

我想通过imapclient模块获取腾讯QQ中的邮件。以下是我输入的代码:

import imapclient
imapObj = imapclient.IMAPClient('imap.qq.com',ssl=True)
imapObj.login('my_email_address@qq.com','MY_SECREST_PASSWORD')
imapObj.select_folder('INBOX',readonly=True)
UIDs = imapObj.search(['SINCE 05-Jul-2021'])

回应是:

UIDs
[46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 86, 87]

然后我输入以下代码:

rawMessages = imapObj.fetch([54],['BODY[]'])
import pprint
pprint.pprint(rawMessages)

但我得到了这个结果:

defaultdict(<class 'dict'>,
        {54: {b'BODY[]': b'Received: from 69.72.42.10 (unknown [69.72.42.10'
                         b'])\r\n\tby newmx37.qq.com (NewMx) with SMTP id '
                         b'\r\n\tfor <651853891@qq.com>; Tue, 27 Jul 2021 '
                         b'17:17:25 +0800\r\nX-QQ-FEAT: Nrj7KsauvmTIWAx9l'
                         b'McI+hrdqGBrqmAk\r\nX-QQ-MAILINFO: NUNG9mg7s8ZO'
'''skip'''
                         b'p; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbs=\r'
                         b'\np;=0D\r\n    </div>=0D\r\n  =0D\r\n=0D\r\n<'
                         b'/body></html>=\r\n\r\n----==_mimepart_60ffcf0651'
                         b'2b8_297158d1c343f9--\r\n\r\n',
              b'FLAGS': (),
              b'SEQ': 9}})

我应该如何获得正确的格式!

4

2 回答 2

0

原来我漏掉了书中的一些知识。

我们可以这样得到邮件的正确格式:

import imapclient
import email
import pyzmail
from pprint import pprint

my_email = 'my_email_address@qq.com'
my_pass_word = 'MY_SECREST_PASSWORD'
n = 30

imapObj = imapclient.IMAPClient('imap.qq.com',ssl=True)
imapObj.login(my_email,my_pass_word)
imapObj.select_folder('INBOX',readonly=True)
UIDs = imapObj.search(['SINCE 05-Jul-2021'])
print(UIDs)

#rawMessages = imapObj.fetch([49],['BODY[]'])
rawMessages = imapObj.fetch([102],['Body[]'])
message = pyzmail.PyzMessage.factory(rawMessages[102][b'BODY[]'])
#rawMessages = imapObj.fetch([54],"RFC822")

#pprint.pprint(rawMessages)
mes_sub = message.get_subject()
mes_from = message.get_addresses('from')
mes_to = message.get_addresses('to')
mes_cc = message.get_addresses('cc')
mes_bcc = message.get_addresses('bcc')
pprint(mes_sub)
print('message from:', mes_from,'\n','message to:', mes_to,'\n','message cc:', 
mes_cc,'\n','message bcc:', mes_bcc)
if message.text_part != None:  #the text you want to see
    mes_text = message.text_part.get_payload().decode(message.text_part.charset)
    print('-'*n + 'text_part:' + '-'*n)
    print(mes_text)
##if message.html_part != None:   #If you want to see the hypertext markup 
language section
##    mes_html = 
message.html_part.get_payload().decode(message.html_part.charset)
##    h = 'html_part:\n'
##    print('-'*n + h + '-'*n)
##    pprint(mes_html)
于 2021-09-25T08:40:11.327 回答
0

尝试使用email模块。

来自文档

# Download unread emails and parse them into standard EmailMessage objects
import email

from imapclient import IMAPClient

HOST = "imap.host.com"
USERNAME = "someuser"
PASSWORD = "secret"

with IMAPClient(HOST) as server:
    server.login(USERNAME, PASSWORD)
    server.select_folder("INBOX", readonly=True)

    messages = server.search("UNSEEN")
    for uid, message_data in server.fetch(messages, "RFC822").items():
        email_message = email.message_from_bytes(message_data[b"RFC822"])
        print(uid, email_message.get("From"), email_message.get("Subject"))

更新:添加更多示例,来自电子邮件示例

from imapclient import IMAPClient
import email
from email import policy
import mimetypes
import os

server = IMAPClient('imap.qq.com', ssl=True)
# your email account
server.login('your_email_account@qq.com','your_code')
select_info = server.select_folder('INBOX',readonly=True)
messages = server.search(['SINCE 05-Jul-2021'])



# parse email
for uid, message_data in server.fetch(messages[:1], "RFC822").items():
    email_message = email.message_from_bytes(message_data[b"RFC822"], policy=policy.default)

    # print headers
    for key, val in email_message.items():
        print(key, val)
    
    print()
    print(email_message.is_multipart())
    print(email_message.get_content_type())
    print()

    # save content
    counter = 1
    for part in email_message.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = f'part-{counter:03d}{ext}'
        counter += 1
        with open(os.path.join("./email", filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))

于 2021-08-01T10:13:57.983 回答