import imaplib
import smtplib
import email
from email.header import decode_header
from email.mime.text import MIMEText
from imapclient import IMAPClient

def send_email(subject, body, to_email):
    # 这个函数名为send_email，它接受三个参数：
    # subject（邮件主题）、body（邮件内容）和to_email（收件人的电子邮件地址）。
    from_email = 'yizeguo1@126.com'

    mail_pass = 'CHRIZKWQSRWYLBOL'# 126授权码
    # mail_pass = 'pwvzuqbiysqshgha'# qq授权码
    
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email
    
    server = smtplib.SMTP('smtp.126.com', 25)
    # server = smtplib.SMTP('smtp.qq.com', 465)
    server.starttls()
    server.login(from_email, mail_pass)
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()


def get_latest_email_body(to_email):
    # 连接到126邮箱的IMAP服务器
    mail = IMAPClient("imap.126.com")
    
    from_email = 'yizeguo1@126.com'
    mail_pass = 'CHRIZKWQSRWYLBOL'# 126授权码
    mail.login(from_email, mail_pass)
    mail.id_({"name": "IMAPClient", "version": "2.1.0"})
    
    # mail.list_folders()
    print(mail.list_folders())
    # 选择收件箱
    messages = mail.select_folder(folder="inbox", readonly=True)

    # 搜索发件人为指定邮箱的所有邮件
    messages = mail.search(None, f'(FROM "{to_email}")')

    # 获取邮件ID列表
    mail_ids = messages[0].split()
    if not mail_ids:
        print("No emails found.")
        return None

    # 获取最新一封邮件的ID
    latest_email_id = mail_ids[-1]

    # 获取最新一封邮件的数据
    status, msg_data = mail.fetch(latest_email_id, "(RFC822)")

    for response_part in msg_data:
        if isinstance(response_part, tuple):
            # 解析邮件
            msg = email.message_from_bytes(response_part[1])

            # 获取纯文本邮件正文
            if msg.get_content_type() == "text/plain":
                body = msg.get_payload(decode=True).decode()
                print("Body:", body)
                return body

    # 关闭连接并登出
    mail.close()
    mail.logout()
    return None
 
    
if __name__ == "__main__":
    
    # send_email("测试", 'test', "guoyize2209@163.com")
    # id_info = {
    # 'name': 'myname',
    # 'version': '1.0.0',
    # 'vendor': 'myclient',
    # 'support-email': 'yizeguo1@126.com'
    # }
    body = get_latest_email_body("guoyize2209@163.com")
    if body:
        print("Latest email body:", body)
    else:
        print("No plain text email found.")