2

I am trying to build a small SMTP Server through which I can be able to send some messages. Looking at the smtpd library found that there was something. But I only was able to create a server that reads the email received, but never sent it to the address requested.

import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):

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)
    return

server = CustomSMTPServer(('127.0.0.1', 1025), None)

asyncore.loop()

client:

import smtplib
import email.utils
from email.mime.text import MIMEText

# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'recipient@example.com'))
msg['From'] = email.utils.formataddr(('Author', 'author@example.com'))
msg['Subject'] = 'Simple test message'

server = smtplib.SMTP('127.0.0.1', 1025)
server.set_debuglevel(True) # show communication with the server
try:
    server.sendmail('author@example.com', ['myadress@gmail.com'], msg.as_string())
finally:
    server.quit()
blasrodri
  • 448
  • 5
  • 16
  • Why do you want to write your own MTA? – James Mills Dec 10 '13 at 15:05
  • To be able to customize and have everything stored conveniently – blasrodri Dec 10 '13 at 15:07
  • See my answer below. Many good MTA implementations offer quite a lot of configuration options. – James Mills Dec 10 '13 at 15:08
  • 1
    While I agree that you should not write your own MTA, the class [`smtpd.PureProxy`](http://docs.python.org/2/library/smtpd.html#pureproxy-objects). The [source code](http://hg.python.org/cpython/file/2.7/Lib/smtpd.py#l345) shows how. – Robᵩ Dec 10 '13 at 17:46

1 Answers1

4

If you really want to do this then check out the Twisted examples:

http://twistedmatrix.com/documents/current/mail/examples/index.html#auto0

I really don't recommend you write your own MTA (Mail Transfer Agent) as this is a complex task with many edge cases and standards to have to worry about.

Use an existing MTA such as Postfix, Exim, or Sendmail.

James Mills
  • 18,669
  • 3
  • 49
  • 62