Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
SMTP Client for Tornado
from tornado import ioloop
from tornado import iostream
import socket
class Envelope(object):
def __init__(self, sender, rcpt, body, callback):
self.sender = sender
self.rcpt = rcpt[:]
self.body = body
self.callback = callback
class SMTPClient(object):
IDLE = 0
EHLO = 1
MAIL = 2
RCPT = 3
DATA = 4
QUIT = 6
def __init__(self, host='localhost', port=25): = host
self.port = port
self.msgs = [] = None
self.state = self.CLOSED
def send_message(self, msg, callback=None):
"""Message is a django style EmailMessage object"""
if not msg:
self.msgs.append(Envelope(msg.from_email, msg.recipients(), msg.message().as_string(), callback))
def send(self, sender=None, rcpt=[], body="", callback=None):
"""Very simple sender, just take the necessary parameters to create an envelope"""
self.msgs.append(Envelope(sender, rcpt, body, callback))
def begin(self):
"""Start the sending of a message, if we need a connection open it"""
if not
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) = iostream.IOStream(s), self.port), self.connected)
def work_or_quit(self, callback=None):
callback is provided, for the startup case where we're not in the main processing loop
if self.state == self.IDLE:
if self.msgs:
self.state = self.MAIL'MAIL FROM: <%s>\r\n' % self.msgs[0].sender)
self.state = self.QUIT'QUIT\r\n')
if callback:'\r\n', callback)
def connected(self):
"""Socket connect callback"""
self.state = self.CONNECTED'\r\n', self.process)
def process(self, data):
# print self.state, data,
code = int(data[0:3])
if data[3] not in (' ', '\r', '\n'):'\r\n', self.process)
if self.state == self.CONNECTED:
if not 200 <= code < 300:
return self.error("Unexpected status %d from CONNECT: %s" % (code, data.strip()))
self.state = self.EHLO'EHLO localhost\r\n')
elif self.state == self.EHLO:
if not 200 <= code < 300:
return self.error("Unexpected status %d from EHLO: %s" % (code, data.strip()))
self.state = self.IDLE
elif self.state == self.MAIL:
if not 200 <= code < 300:
return self.error("Unexpected status %d from MAIL: %s" % (code, data.strip()))
if self.msgs[0].rcpt:'RCPT TO: <%s>\r\n' % self.msgs[0].rcpt.pop(0))
self.state = self.RCPT
elif self.state == self.RCPT:
if not 200 <= code < 300:
return self.error("Unexpected status %d from RCPT: %s" % (code, data.strip()))
if self.msgs[0].rcpt:'RCPT TO: <%s>\r\n' % self.msgs[0].rcpt.pop(0))
self.state = self.DATA
elif self.state == self.DATA:
if code not in (354,) :
return self.error("Unexpected status %d from DATA: %s" % (code, data.strip()))[0].body)
if self.msgs[0].body[-2:] != '\r\n':'\r\n')'.\r\n')
self.state = self.DATA_DONE
elif self.state == self.DATA_DONE:
if not 200 <= code < 300:
return self.error("Unexpected status %d from DATA END: %s" % (code, data.strip()))
if self.msgs[0].callback:
self.state = self.IDLE
elif self.state == self.QUIT:
if not 200 <= code < 300:
return self.error("Unexpected status %d from QUIT: %s" % (code, data.strip()))
if'\r\n', self.process)
def error(self, msg):
def close(self):
for msg in self.msgs:
if msg.callback:
msg.callback(False) = None
self.state = self.CLOSED
if __name__ == '__main__':
client = SMTPClient('localhost', 25)
body = """Subject: Testing
Just a test
client.send('', [''], body)

How to use
Run but it does not work
self.state is -2


koblas commented Apr 9, 2012

Do you have a smtp server running on your localhost?

I have not run a smtp server in localhost.
Whether to support the Gmail or hotmail?


koblas commented Apr 10, 2012

To support gmail or hotmail as your mail sending agent - that's a very different library.

On my localhost running an SMTP server. Send mail sucessfully! But receive are spam. How to set a sender?

Hi @koblas,

I've added this to a git repo



koblas commented May 21, 2012



koblas commented Jul 11, 2012

Any details on the issues, something that could be fixed in the fragment or something larger?

Basically messages were not going out. It seemed like something in the SMTP conversation was falling into stalemate.

Sorry, it's a couple of months so bit hazy. I didn't have time at the time to debug it thoroughly and I need some resilient over ioloop integrated.

One thing you should watch is expecting '\r\n' from SMTP servers. Not all servers use the same line endings and this is common gotcha when writing SMTP handlers that will leads stalemate. You'll wait all day for '\r\n' when the client already sent '\n'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment