邮件内容解析

背景:

将手机验证码转发到qq邮箱后,通过python代码解析邮件获取验证码。

以下代码主要展示如何解析邮件正文内容。

具体代码功能,可以通过查看imaplib的用法进行了解。

import imaplib
import email
from email.parser import Parser
from email.header import decode_header 
from flanker import mime
import re
import time

# 连接到邮件服务器
imap_server = imaplib.IMAP4_SSL("imap.qq.com")
# 登录
imap_server.login("13***********[email protected]", "kp**********iig")
# 选择邮件箱
imap_server.select("INBOX")  # 选择收件箱


typ, data = imap_server.search(None,'Subject','手机短信转发'.encode('utf-8')) # 通过主题搜索邮件
for msg_id in data[0].split():
    res, msg = imap_server.fetch(msg_id, '(RFC822)')
    for response in msg:
        if isinstance(response,tuple):
            msg=email.message_from_bytes(response[1])
            subject,encoding=decode_header(msg['Subject'])[0]
            if isinstance(subject,bytes):
                subject=subject.decode(encoding)
 
            From,encoding=decode_header(msg.get('From'))[0]
            if isinstance(From, bytes):
                From=From.decode(encoding) 
            date_time =  msg.get("Date")  # 解析时间
            dt = time.strptime(date_time[5:24],"%d %b %Y %H:%M:%S")
            print('\n')
            print('Sub:',subject)
            print('From:',From)
            print("date_time...", type(date_time),date_time, dt)
            body = ""
            if msg.is_multipart():
                print('**** ---multipart--')
                for part in msg.walk():
                    content_type=part.get_content_type()
                    content_disposition=str(part.get('Content-Disposition'))
                    #body
                    try:
                        body=part.get_payload(decode=True).decode()
                    except:
                        pass
                    if content_type=='text/plain' and 'attachment' not in content_disposition:
                        print(body)
                    #attachment
                    elif 'attachment' in content_disposition:
                        filename=part.get_filename()
                        #if filename:
                        #    folder_name=clean(subject)
                        #    if not os.path.isdir(folder_name):
                        #        os.mkdir(folder_name)
                        #    filepath=os.path.join(folder_name,filename)
                        #    open(filepath,'wb').write(part.get_payload(decode=True))
                        #    print(filepath,'save')
            else:
                print('****---singlepart---')
                content_type=msg.get_content_type()
                body=msg.get_payload(decode=True).decode()
                #if content_type=='text/plain':
                #    print(body)
            print("-  --- -----", body)
imap_server.close()
imap_server.logout() 

你可能感兴趣的:(python,开发语言)