如何用Python编写简单的电子邮件监听器

时间:2017-01-07 02:17:43

标签: python python-2.7 email smtp imap

我是Python(v2.7)的新手,我需要编写一个连续运行的简单程序,监听gmail帐户并在所述帐户收到电子邮件时调用函数。到目前为止似乎使用Python的内置IMAP或SMTP库似乎是最好的选择,但我不是很熟悉它们,更不用说Python本身了。

到目前为止,我提出的是能够连接到电子邮件并通过IMAP4查找最新的电子邮件,但它没有办法不断检查是否收到了新的电子邮件:

Source

import imaplib
import email

#logs in to the desired account and navigates to the inbox
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('email@gmail.com','password')
mail.list()
mail.select('inbox')

result, data = mail.search(None,'ALL')

#retrieves the latest (newest) email by sequential ID
ids = data[0]
id_list = ids.split()
latest_email_id = id_list[-1]

有关如何调整此值以继续运行并检查新传入消息的任何帮助都会很棒。谢谢!

1 个答案:

答案 0 :(得分:0)

使用线程模块和子类threading.Thread。可以在此处找到文档:https://docs.python.org/2/library/threading.html

import threading
import time

class MailThread(threading.Thread):

然后您的代码进入run(),您必须添加一些延迟。让我们说1000秒。

def run():
    #your code here
    time.sleep(1000)

您脚本的最后一部分如下所示

if __name__ == '__main__': 
    mail_thread = MailThread()
    mail_thread.start()
    # do other stuff

OR

收到邮件后,只需使用while(True)循环time.sleep()break