Python:不断检查新电子邮件并提醒更多新电子邮件

2024-04-25

我有这段代码可以检查最新的电子邮件,然后执行某些操作。是否可以编写一些内容来不断检查收件箱文件夹中是否有新邮件?尽管我希望它继续检查最新的新电子邮件。如果我尝试存储它已经通过了一次,它会变得太复杂吗?因此,它不会针对同一封电子邮件两次发出有关同一封电子邮件的警报。

Code:

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....

尝试使用这种方法:

逻辑与@tripleee 评论相同。

import time
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.
latest_email_uid = ''

while True:
    mail.select("Inbox", readonly=True)
    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

    if data[0].split()[-1] == latest_email_uid:
         time.sleep(120) # put your value here, be sure that this value is sufficient ( see @tripleee comment below)
    else:
         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]
         latest_email_uid == data[0].split()[-1]
         time.sleep(120) # put your value here, be sure that this value is sufficient ( see @tripleee comment below)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:不断检查新电子邮件并提醒更多新电子邮件 的相关文章

随机推荐