获取邮件及附件(处理中文问题)

def pzDowmlodUrl(username, password, filespath):
    subject = ''
    sender = ''
    # 腾讯企业邮箱收邮件服务器
    imapObj = IMAPClient('imap.exmail.qq.com', ssl=True)
    imapObj.login(username=username, password=password)
    imapObj.select_folder('INBOX', readonly=True)
    UIDS = imapObj.search('UNSEEN')
    print(UIDS, len(UIDS))
    # UIDS = imapObj.search('ALL')
    if len(UIDS) >= 1:  
        for i in range(len(UIDS)):
            rawMessage = imapObj.fetch(UIDS[i], [b'BODY[]'])
            messageObj = pyzmail.PyzMessage.factory(rawMessage[UIDS[i]][b'BODY[]'])
            # subject = messageObj.get_subject()  
            sender = messageObj.get_addresses('from') 
            sender = sender[0][1]
            if messageObj.html_part is not None:
                for part in messageObj.walk():
                    if part.get_filename() is not None: 
                        if part.get('Content-Disposition', None):
                            Content_Disposition = part['Content-Disposition']
                            filename = re.search('filename="(.*)"$', Content_Disposition).group(1)
                            temp_path = os.path.join(os.path.dirname(__file__), filespath, str(uuid.uuid1()))
                            filename, codetype = email.header.decode_header(filename)[0]
                            if codetype:
                                filename = filename.decode(codetype)
                            if not os.path.exists(temp_path):
                                os.makedirs(temp_path)
                            dstdir = os.path.join(temp_path, filename)
                            data = part.get_payload(decode=True)
                            with open(dstdir, 'wb') as file_base:
                                file_base.write(data)
                imapObj.set_flags(rawMessage, b'\\Seen', silent=False)
            else:
                imapObj.set_flags(rawMessage, b'\\Seen', silent=False)
                pass
    imapObj.logout()
    return len(UIDS), sender

你可能感兴趣的:(获取邮件及附件(处理中文问题))