我正在编写一个 Python 脚本,该脚本使用 imap_tools 库持续检查 IMAP 邮箱中的新电子邮件。我的目标是获取最新的电子邮件,而不必每次都重新登录。但是,我遇到了一个问题,即除非我重新连接到 IMAP 服务器,否则脚本在初次登录后无法检索新电子邮件。
下面是我的脚本的简化版本:
from imap_tools import MailBox, A
import time
# Email account credentials
email_address = '[email protected]'
password = 'yourpassword'
imap_server = 'imap.example.com'
def maintain_connection():
mailbox = MailBox(imap_server)
mailbox.login(email_address, password, initial_folder='INBOX')
return mailbox
def check_new_emails(mailbox):
try:
# Fetch all unseen emails and print their subjects
for msg in mailbox.fetch(A(seen=False)):
print(f"New email: {msg.subject}")
# Here you can mark the email as seen, parse it, or take other actions
except Exception as e:
print(f"An error occurred: {e}")
# Attempt to re-establish connection
print("Attempting to re-establish connection...")
mailbox.logout()
time.sleep(5) # wait a bit before reconnecting
return maintain_connection()
return mailbox
# Initial connection setup
mailbox = maintain_connection()
while True:
mailbox = check_new_emails(mailbox)
print("Waiting for new emails...")
time.sleep(60) # Check every 60 seconds
我面临的问题是脚本在第一次连接后似乎没有接收新电子邮件。如果我强制重新登录,它只会检索新电子邮件。
这是我的具体问题:
如何修改脚本以连续检查和获取新电子邮件,而无需每次重新登录?
是否有更有效的方法来保持 IMAP 连接处于活动状态并响应新电子邮件? 我正在寻找有关如何解决此问题的见解或建议。任何帮助或指导将不胜感激。
imap-tools 支持 IDLE:
from imap_tools import MailBox, A
# waiting for updates 60 sec, print unseen immediately if any update
with MailBox('imap.my.moon').login('acc', 'pwd', 'INBOX') as mailbox:
responses = mailbox.idle.wait(timeout=60)
if responses:
for msg in mailbox.fetch(A(seen=False)):
print(msg.date, msg.subject)
else:
print('no updates in 60 sec')
查看文档了解更多信息