2010-04-22 267 views
14

你可以请建议一个简单的SMTP服务器与非常基本的API(非常基本,我的意思是,读,写,删除电子邮件),可以在Linux上运行? 我只需要将电子邮件的症结转换为XML格式,并将其FTP到另一台机器。一个简单的smtp服务器

+0

一些关于用代码发送电子邮件的有趣阅读:http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html – tgray 2010-04-22 18:59:00

回答

27

看看这个SMTP sink server

from datetime import datetime 
import asyncore 
from smtpd import SMTPServer 

class EmlServer(SMTPServer): 
    no = 0 
    def process_message(self, peer, mailfrom, rcpttos, data): 
     filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), 
       self.no) 
     f = open(filename, 'w') 
     f.write(data) 
     f.close 
     print '%s saved.' % filename 
     self.no += 1 


def run(): 
    foo = EmlServer(('localhost', 25), None) 
    try: 
     asyncore.loop() 
    except KeyboardInterrupt: 
     pass 


if __name__ == '__main__': 
    run() 

它使用smtpd.SMTPServer转储电子邮件,文件。

+0

这太棒了! – fixxxer 2010-04-22 13:51:25

+0

谢谢,我是SMTP宿主服务器的作者。我刚从@zero了解到,该命令对测试更加简单:'sudo /usr/lib/python2.4/smtpd.py -n -c DebuggingServer localhost:25' – twinsant 2013-03-19 07:08:48

+2

hmm,用下面的命令调整它:'sudo python -m smtpd -c DebuggingServer -n localhost:25' – twinsant 2013-03-19 07:14:19

1

Python SMTP server

该模块提供了几个类来实现SMTP服务器。一种是 通用无所作为的实现,可以被覆盖,而另外两个提供特定的邮件发送策略。

+1

是的,我知道。但是,我无法弄清楚如何阅读那个lib的电子邮件! 解决这个问题的方法,也许呢? – fixxxer 2010-04-22 13:12:10

+0

尽管这个链接可能回答这个问题,但最好在这里包含答案的重要部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 – 2012-08-24 00:27:37

16

实际上有发送电子邮件需要两两件事:

  • SMTP服务器 - 这可以是Python SMTP Server或者您可以使用Gmail或您的ISP的服务器。有机会你不需要自己运行。
  • SMTP库 - 将向SMTP服务器发送电子邮件请求的内容。 Python附带一个名为smtplib的库,可以为你做到这一点。关于如何在这里使用它有很多信息:http://docs.python.org/library/smtplib.html

对于阅读,有两个选项,取决于您正在阅读电子邮件的服务器。

0

要获得哈森的剧本在Python 3个工作我不得不调整它稍微:

from datetime import datetime 
import asyncore 
from smtpd import SMTPServer 

class EmlServer(SMTPServer): 
    no = 0 
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): 
     filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), 
      self.no) 
     print(filename) 
     f = open(filename, 'wb') 
     f.write(data) 
     f.close 
     print('%s saved.' % filename) 
     self.no += 1 

def run(): 
    EmlServer(('localhost', 25), None) 
    try: 
     asyncore.loop() 
    except KeyboardInterrupt: 
     pass 

if __name__ == '__main__': 
    run() 
1

Twisted有一个SMTP服务器内置。见http://twistedmatrix.com/documents/current/mail/examples/index.html

# Copyright (c) Twisted Matrix Laboratories. 
# See LICENSE for details. 

# You can run this module directly with: 
# twistd -ny emailserver.tac 

""" 
A toy email server. 
""" 
from __future__ import print_function 

from zope.interface import implementer 

from twisted.internet import defer 
from twisted.mail import smtp 
from twisted.mail.imap4 import LOGINCredentials, PLAINCredentials 

from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse 
from twisted.cred.portal import IRealm 
from twisted.cred.portal import Portal 



@implementer(smtp.IMessageDelivery) 
class ConsoleMessageDelivery: 
    def receivedHeader(self, helo, origin, recipients): 
     return "Received: ConsoleMessageDelivery" 


    def validateFrom(self, helo, origin): 
     # All addresses are accepted 
     return origin 


    def validateTo(self, user): 
     # Only messages directed to the "console" user are accepted. 
     if user.dest.local == "console": 
      return lambda: ConsoleMessage() 
     raise smtp.SMTPBadRcpt(user) 



@implementer(smtp.IMessage) 
class ConsoleMessage: 
    def __init__(self): 
     self.lines = [] 


    def lineReceived(self, line): 
     self.lines.append(line) 


    def eomReceived(self): 
     print("New message received:") 
     print("\n".join(self.lines)) 
     self.lines = None 
     return defer.succeed(None) 


    def connectionLost(self): 
     # There was an error, throw away the stored lines 
     self.lines = None 



class ConsoleSMTPFactory(smtp.SMTPFactory): 
    protocol = smtp.ESMTP 

    def __init__(self, *a, **kw): 
     smtp.SMTPFactory.__init__(self, *a, **kw) 
     self.delivery = ConsoleMessageDelivery() 


    def buildProtocol(self, addr): 
     p = smtp.SMTPFactory.buildProtocol(self, addr) 
     p.delivery = self.delivery 
     p.challengers = {"LOGIN": LOGINCredentials, "PLAIN": PLAINCredentials} 
     return p 



@implementer(IRealm) 
class SimpleRealm: 
    def requestAvatar(self, avatarId, mind, *interfaces): 
     if smtp.IMessageDelivery in interfaces: 
      return smtp.IMessageDelivery, ConsoleMessageDelivery(), lambda: None 
     raise NotImplementedError() 



def main(): 
    from twisted.application import internet 
    from twisted.application import service  

    portal = Portal(SimpleRealm()) 
    checker = InMemoryUsernamePasswordDatabaseDontUse() 
    checker.addUser("guest", "password") 
    portal.registerChecker(checker) 

    a = service.Application("Console SMTP Server") 
    internet.TCPServer(2500, ConsoleSMTPFactory(portal)).setServiceParent(a) 

    return a 

application = main()