Python imaplib 只检查未读消息

Python imaplib only check message if its unread

我正在尝试将 imaplib 设置为仅在收件箱中有新电子邮件时才有效。我试着用我在网上找到的代码来做到这一点,并向它添加了一个 while 循环,它工作得很好,但它总是打印消息,即使他是同一封电子邮件。这是我所做的:

import imaplib
import email
mail = "xyz@gmail.com"
password = "password"
imap = imaplib.IMAP4_SSL("imap.gmail.com")
imap.login(mail,password)
N = 1

while True:

            status, messages = imap.select("INBOX")
            messages = int(messages[0])

            for i in range(messages, messages-N, -1):
                res, msg = imap.fetch(str(i), "(RFC822)")
                for response in msg:
                    if isinstance(response, tuple):
                        # parse a bytes email into a message object
                        msg = email.message_from_bytes(response[1])
                        if msg.is_multipart():
                            # iterate over email parts
                            for part in msg.walk():
                                # extract content type of email
                                content_type = part.get_content_type()
                                content_disposition = str(part.get("Content-Disposition"))
                                try:
                                    # get the email body
                                    body = part.get_payload(decode=True).decode()
                                except:
                                    pass
                                if content_type == "text/plain" and "attachment" not in content_disposition:
                                    # print text/plain emails and skip attachments
                                    print(body)
                        else:
                            # extract content type of email
                            content_type = msg.get_content_type()
                            # get the email body
                            body = msg.get_payload(decode=True).decode()

                            if content_type == "text/plain":
                                # print only text email parts
                                print(body)

这完成了工作,并打印最新电子邮件的消息,如果我发送一封新电子邮件,它会读取该消息,将正文更改为新消息并打印。但我的问题是,它会一直打印相同的消息,直到有新消息到达,然后它会一遍又一遍地打印,直到另一条消息到达。像这样:

this is a message # keeps printing it until new email arrives
this is a message
this is a message
this is a message
# new email arrives
this is the message of the new email
this is the message of the new email
this is the message of the new email

我怎样才能让它只检查 new/unread 封电子邮件,或者只在收件箱中有新电子邮件时激活?也许有什么东西可以让它进入空闲模式?

我找到了解决办法。它并没有真正阻止它运行,但它只会打印一次。这是一个非常简单的修复,使用列表。我添加了一个列表和一个 messagid 变量,每次循环重置时我们都会添加 1:

messageid = 0
messagelist = ["first"]
while True:
    messageid += 1

我做的不是 print(body),而是:

messagelist.append(body)
if messagelist[messageid] != messagelist[messageid-1]:
    print(body)

这只会打印与之前不同的正文。