如果收件箱中有新電子郵件,我正在嘗試設定imaplib為僅作業。我嘗試使用我在網上找到的代碼來執行此操作,并為其添加了一個 while 回圈,它運行良好,但它總是列印訊息,即使它是同一封電子郵件。這是我所做的:
import imaplib
import email
mail = "[email protected]"
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
我怎樣才能做到這一點,它只檢查新的/未讀的電子郵件,或者它只在收件箱中有新電子郵件時激活?也許有什么東西可以讓它進入空閑模式?
uj5u.com熱心網友回復:
我找到了解決方案。它并沒有真正阻止它運行,但它只會列印一次。使用串列,這是一個非常容易解決的問題。我添加了一個串列和一個messagid變數,每次回圈重置時我們都會添加1:
messageid = 0
messagelist = ["first"]
while True:
messageid = 1
而不是 print(body),我所做的是:
messagelist.append(body)
if messagelist[messageid] != messagelist[messageid-1]:
print(body)
如果正文與之前的正文不同,這只會列印正文。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/436922.html
