如何在Python中通过IMAP获取未读消息并设置消息已读标志?

8 投票
3 回答
33548 浏览
提问于 2025-04-18 01:18
import imaplib
def read():

    userName = "xxx@gmail.com"
    password = "xxxx" 
    name = 'xxx@gmail.com'
    email_ids = [userName]
    data = []
    imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
    imap_server.login(userName, password)
    imap_server.select('INBOX')
    da = []
    status, response = imap_server.status('INBOX', "(UNSEEN)")
    unreadcount = int(response[0].split()[2].strip(').,]'))
    print unreadcount

    status, response = imap_server.search(None, '(FROM "xxx@gmail.com")')
    email_ids = [e_id for e_id in response[0].split()]
    for e_id in email_ids:
        _, response = imap_server.fetch(e_id, '(UID BODY[TEXT])')
        da.append(response[0][1])
    print da


read()

怎么整理上面的代码,让它只读取未读邮件?还有,一旦我们读取了这些邮件,怎么用Python把这些邮件标记为已读呢?

3 个回答

2

你可以使用我的库 - imap_tools: https://pypi.org/project/imap-tools/

from imap_tools import MailBox, A

# get subjects of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'pwd') as mailbox:
    subjects = [msg.subject for msg in mailbox.fetch(A(seen=False), mark_seen=True)]
3

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用这些数据。这个过程就像是把水从一个水桶倒到另一个水桶里。

有些时候,我们需要确保在这个过程中,数据不会被意外地改变或者丢失。为了做到这一点,我们可以使用一些工具和方法来保护我们的数据,就像在倒水的时候用一个漏斗,确保水不会洒出来。

此外,编程中还有一些概念,比如“变量”和“函数”。变量就像是一个可以存放东西的盒子,而函数则是一个可以执行特定任务的机器。我们可以把数据放进变量里,然后用函数来处理这些数据。

总之,编程就像是在做一个复杂的拼图,我们需要把不同的部分组合在一起,才能完成一个完整的图案。

def read(username, password, sender_of_interest=None):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login(username, password)
    imap.select('INBOX')
    # Use search(), not status()
    # Print all unread messages from a certain sender of interest
    if sender_of_interest:
        status, response = imap.uid('search', None, 'UNSEEN', 'FROM {0}'.format(sender_of_interest))
    else:
        status, response = imap.uid('search', None, 'UNSEEN')
    if status == 'OK':
        unread_msg_nums = response[0].split()
    else:
        unread_msg_nums = []
    data_list = []
    for e_id in unread_msg_nums:
        data_dict = {}
        e_id = e_id.decode('utf-8')
        _, response = imap.uid('fetch', e_id, '(RFC822)')
        html = response[0][1].decode('utf-8')
        email_message = email.message_from_string(html)
        data_dict['mail_to'] = email_message['To']
        data_dict['mail_subject'] = email_message['Subject']
        data_dict['mail_from'] = email.utils.parseaddr(email_message['From'])
        data_dict['body'] = email_message.get_payload()
        data_list.append(data_dict)
    print(data_list)
16
import imaplib

def read(username, password, sender_of_interest):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login(username, password)
    imap.select('INBOX')

    # Use search(), not status()
    status, response = imap.search(None, 'INBOX', '(UNSEEN)')
    unread_msg_nums = response[0].split()

    # Print the count of all unread messages
    print len(unread_msg_nums)

    # Print all unread messages from a certain sender of interest
    status, response = imap.search(None, '(UNSEEN)', '(FROM "%s")' % (sender_of_interest))
    unread_msg_nums = response[0].split()
    da = []
    for e_id in unread_msg_nums:
        _, response = imap.fetch(e_id, '(UID BODY[TEXT])')
        da.append(response[0][1])
    print da

    # Mark them as seen
    for e_id in unread_msg_nums:
        imap.store(e_id, '+FLAGS', '\Seen')

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

撰写回答