Python Imaplib:无需重新连接即可获取新的Gmail邮件 [英] Python Imaplib: Get new gmail mails without reconnect

查看:97
本文介绍了Python Imaplib:无需重新连接即可获取新的Gmail邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个python脚本,该脚本会定期检查与特定搜索匹配的新电子邮件.但是,如果不重新连接,它永远不会显示新电子邮件.

I'm writing a python script that regularly checks for new email matching a certain search. However it never shows new emails without reconnecting.

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user,passwd)
mail.select("inbox")
while True:
    result, idData = mail.uid('search', query, "ALL")
    processIDs(idData)
    time.sleep(60)

搜索会在登录时查找与我的查询匹配的所有电子邮件,但从不查找运行时到达的电子邮件.一旦我停止脚本并重新启动它,所有电子邮件都会立即显示.

The search finds all emails that match my query at login time, but it never finds emails that arrive while it's running. As soon as I stop the script and restart it, all emails instantly show up.

如果用Google搜索并浏览了imaplib文档,但找不到有用的东西.

If googled and looked through the imaplib docs, but couldn't find anything useful.

如何在不重新连接到imap服务器的情况下显示新电子邮件?

How can I get the new emails to show without reconnecting to the imap server?

我想避免重新连接的原因是由于gmail速率限制.

The reason I want to avoid reconnecting is because of gmail rate limits.

推荐答案

这是一种成功的尝试方法,最后我们得到了一个解决方案,尽管不是最佳的,但该技巧是每次脚本唤醒后都重新连接从睡眠开始,从头开始获取收件箱,这可以通过刷新页面来轻松完成(就像我们在常规浏览器中重新加载一样),所以看起来像这样:

Well this is a kind of hit and trial approach and finally we get a solution, not optimal though, The hack is to reconnect again every time after the script wakes up from the sleep, to fetch the inbox from start, This can be easily done by refreshing the page(like we reload in the normal browser), So it may look like this :

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user,passwd)
while True:
    mail.select("inbox")
    result, idData = mail.uid('search', query, "ALL")
    processIDs(idData)
    time.sleep(60)

这篇关于Python Imaplib:无需重新连接即可获取新的Gmail邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆