【发布时间】:2018-08-11 16:36:19
【问题描述】:
我有这段代码可以检查最新的电子邮件,然后去做一些事情。是否可以写一些东西来不断检查收件箱文件夹是否有新邮件?虽然我希望它继续检查最新的新电子邮件。如果我尝试存储它已经通过一次,它会变得太复杂吗?因此,它不会针对同一封电子邮件提醒同一封电子邮件两次。
代码:
import imaplib
import email
import Tkinter as tk
word = ["href=", "href", "<a href="] #list of strings to search for in email body
#connection to the email server
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('xxxx', 'xxxx')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("Inbox", readonly=True) # connect to inbox.
result, data = mail.uid('search', None, "ALL") # search and return uids instead
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)') # fetch the email headers and body (RFC822) for the given ID
raw_email = data[0][1] # here's the body, which is raw headers and html and body of the whole email
# including headers and alternate payloads
.....goes and does other code regarding to email html....
【问题讨论】:
-
在伪代码中,当为真时:获取最新消息;如果它比以前更新,则显示警报;以前的 := 最新的;睡觉;
-
Python 的
imaplib不支持 IMAPIDLE命令,但最好使用它。 -
IIRC 你应该能够摆脱一些比总是“搜索所有”更残酷的事情,但现在不是在 / 好地方检查。