python 获取163 邮箱的邮件信息

此案例是是获取的一个亚马逊的验证码

import time
from imaplib import IMAP4_SSL
import imaplib,email,datetime
from lxml import etree
from dateutil.parser import parse

def str_to_unicode(s, encoding=None):
    return str(s, encoding) if encoding else str(s)

def get_xpath(xpath, content):
    # xpath 工具
    out = []
    tree = etree.HTML(content)
    results = tree.xpath(xpath)
    for result in results:
        if 'ElementStringResult' in str(type(result)) or 'ElementUnicodeResult' in str(type(result)):
            out.append(result)
        else:
            out.append(etree.tostring(result))
    return out


def send_mail(now_time):
    max_retries = 5  # 最大重试次数
    retry_delay = 2  # 每次重试的间隔时间(秒)
    while True:
        status = 0
        sender = 'XXX'  # 邮箱
        password = 'XXX'  # 开启163邮箱的IMAP,获取授权码
        # 尝试连接 IMAP 服务器
        for attempt in range(max_retries):
            try:
                email_server = IMAP4_SSL(host='imap.163.com')
                break
            except Exception as e:
                if attempt < max_retries - 1:
                    print(f"连接失败,正在重试... (尝试 {attempt + 1}/{max_retries})")
                    time.sleep(retry_delay)
                else:
                    print("连接失败,已达到最大重试次数。")
                    return None
        email_server.login(user=sender, password=password)
        imaplib.Commands["ID"] = ('AUTH',)
        args = ("name", sender, "contact", sender, "version", "1.0.0", "vendor", "myclient")
        email_server._simple_command("ID", str(args).replace(",", "").replace("\'", "\""))

        email_server.select('INBOX', readonly=True)

        emaillist = email_server.search(None, 'UnSeen')
        emailist = emaillist[1][0].split()
        for unseen in reversed(emailist):
            status, emaildata = email_server.fetch(unseen, '(RFC822)')
            messages = email.message_from_string(emaildata[0][1].decode('utf-8'))
            date = datetime.datetime.strftime(parse(messages['Date']) + datetime.timedelta(hours=8),
                                              '%Y-%m-%d %H:%M:%S')
            print(date, now_time)
            if date >= now_time:
                status = 1
                pass
            else:
                time.sleep(3)
                print('暂未收到验证码!等待3秒后重试')
                email_server.close()
                email_server.logout()
                break
            message_subject = email.header.decode_header(messages["Subject"])
            subject = str_to_unicode(message_subject[0][0], message_subject[0][1])
            if 'amazon.com' in subject or 'Account data access attempt' in subject:
                for data in messages.walk():
                    if data.get_content_type() == 'text/html':
                        charset = data.get_content_charset()
                        data = data.get_payload(decode=True).decode(charset)
                        code = str(
                            get_xpath('/html/body/table/tbody/tr/td/table/tbody/tr[6]/td/p/text()', data)[0]).strip()
                        email_server.close()
                        email_server.logout()
                        print(code)
                        return code
            else:
                continue
        if status == 1:
            break
        time.sleep(3)


if __name__ == '__main__':
    now_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    code = send_mail(now_time)
    print(code)

now_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
code = send_mail(now_time)

image

posted @ 2024-09-13 14:28  张张包~  阅读(56)  评论(0编辑  收藏  举报