1

我想收到一封带有 python 的电子邮件。然后我想退出邮件服务器并在我的脚本中使用电子邮件的内容。

例如:

if "any_string" in data:
    print "success"
    << exit mailserver >>
    << any other commands >>

代码:

import smtpd
import asyncore

class FakeSMTPServer(smtpd.SMTPServer):
    __version__ = 'TEST EMAIL SERVER'

    def process_message(self, peer, mailfrom, rcpttos, data):
        print 'Receiving message from:', peer
        print 'Message addressed from:', mailfrom
        print 'Message addressed to  :', rcpttos
        print 'Message length        :', len(data)
        print 'Message               :', data
        return

if __name__ == "__main__":
    smtp_server = FakeSMTPServer(('0.0.0.0', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()
4

2 回答 2

2

您可以使用SMTP.quit()关闭 SMTP 会话。在您的情况下,您可以像这样使用它smtp_server.quit()

关于在字符串中搜索单词,您可以这样做

data = 'my Test data'
for word in data.split():
    if 'test' in word:
        print "success"

如果您想忽略大小写(大写/小写),只需使用lower()将字符串转换为小写,然后检查如下所示:

data = 'my Test data'
for word in data.lower().split():
    if 'test' in word:
        print "success"

如果您想在使用时停止脚本,asyncore.loop()那么您可能需要使用不同的线程来启动 SMTP 服务器,然后您才能控制它。这个问题解释了细节。如何在 python 的一个类中处理 asyncore,而不阻塞任何东西?

于 2014-06-18T11:47:53.717 回答
1

You can exit from the asyncore loop by calling asyncore.close_all in you process_message method :

def process_message(self, peer, mailfrom, rcpttos, data):
    # ...
    print 'Message               :', data
    asyncore.close_all()
    return

EDIT

If you want to have access to the text of the message after exiting from asyncore loop, you simply store it as an attribute of your smtp server

#...
class FakeSMTPServer(smtpd.SMTPServer):
    def process_message(self, peer, mailfrom, rcpttos, data):
        # ...
        self.data = data
        # ...

if __name__ == "__main__":
    smtp_server = FakeSMTPServer(('0.0.0.0', 25), None)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        smtp_server.close()
    # smtp_server.data contains text of message
于 2014-06-18T13:28:37.447 回答