python通过imap协议读取最新邮件

邮箱信息改成自己的邮箱

UNSEEN:接收未读邮件

ALL:接收所有邮件

SEEN:接收已查看邮件

import imaplib
import email
from email.header import decode_header

# 邮箱信息
imap_server = 'imap.example.com'
imap_port = 993
username = 'your_email@example.com'
password = 'your_password'

# 连接邮箱服务器
imap = imaplib.IMAP4_SSL(imap_server, imap_port)
imap.login(username, password)

# 选择邮箱中的收件箱
imap.select('INBOX')

# 搜索未读邮件
status, response = imap.search(None, 'UNSEEN')  # UNSEEN:接收未读邮件 ALL:接收所有邮件 SEEN:接收已查看邮件
unread_msg_nums = response[0].split()

# 遍历未读邮件
for msg_num in unread_msg_nums:
    status, msg_data = imap.fetch(msg_num, '(RFC822)')
    msg = email.message_from_bytes(msg_data[0][1])

    # 获取邮件主题
    subject = decode_header(msg['Subject'])[0][0]
    if isinstance(subject, bytes):
        subject = subject.decode()

    # 获取发件人
    sender = decode_header(msg['From'])[0][0]
    if isinstance(sender, bytes):
        sender = sender.decode()

    # 输出邮件信息
    print('Subject:', subject)
    print('From:', sender)
    print('Message:')
    print(msg.get_payload())

# 关闭连接
imap.close()
imap.logout()
© 版权声明
THE END
喜欢就支持一下吧
点赞14赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容