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

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容