A simple SMTP server (in Python)
Take a look at this SMTP sink server:
from __future__ import print_function
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():
# start the smtp server on localhost:1025
foo = EmlServer(('localhost', 1025), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
run()
It uses smtpd.SMTPServer
to dump emails to files.
To get Hasen's script working in Python 3 I had to tweak it slightly:
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()
There are really 2 things required to send an email:
- An SMTP Server - This can either be the Python SMTP Server or you can use GMail or your ISP's server. Chances are you don't need to run your own.
- An SMTP Library - Something that will send an email request to the SMTP server. Python ships with a library called smtplib that can do that for you. There is tons of information on how to use it here: http://docs.python.org/library/smtplib.html
For reading, there are two options depending on what server you are reading the email from.
- For a POP Email Server - You can use the poplib python library: http://docs.python.org/library/poplib.html
- For an IMAP Email Server - You can use the imaplib python library: http://docs.python.org/library/imaplib.html