[Twisted-Python] twisted.mail newbie question

xing at mac.com xing at mac.com
Fri Aug 19 17:55:11 EDT 2005

Hi all,

I have read the twisted.mail.smtp source and ran the sample code 
(included below) in the debugger with break points and yet I still do 
not know where I can inject my code to handle actual message delivery 
where both the email message and all the recipients are available at one 
point in time.

The IMessageDelivery handler doesn't appear to see the message, and the 
IMessage only sees the message and not the recipients. As such, I'm 
thorughly confused. Very new to twisted and async programming model.

Thanks for any pointers.

I have written a basic smtp relayer wrapped around twisted smtp.sendmail 
using my own delivery queue and mx selection management and trying to 
put the last piece in: the smtp server which will hand off all incoming 
messages into my queues.

Xing Li


from twisted.internet import defer
from twisted.protocols import smtp
from twisted.internet import reactor

class ConsoleMessageDelivery:
     __implements__ = (smtp.IMessageDelivery)

     def receivedHeader(self, helo, origin, recipients):
         for i in recipients:
             print i
         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)

class ConsoleMessage:
     __implements__ = (smtp.IMessage,)

     def __init__(self):
         self.lines = []

     def lineReceived(self, 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):
     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
         return p

if __name__ == '__main__':
     f = ConsoleSMTPFactory()

     reactor.listenTCP(25, f)

More information about the Twisted-Python mailing list