编程语言
首页 > 编程语言> > Python:继续检查新电子邮件并提醒更多新电子邮件

Python:继续检查新电子邮件并提醒更多新电子邮件

作者:互联网

我有这个代码检查最新的电子邮件,然后去做一些事情.是否有可能写一些不断检查收件箱文件夹的新邮件?虽然我希望它继续检查最新的新电子邮件.如果我尝试存储它已经通过一次会变得太复杂吗?因此,它不会就同一封电子邮件两次发送同一封邮件.

码:

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)

标签:python,email,imaplib
来源: https://codeday.me/bug/20191003/1849315.html