pythonsmtpsmtpd

Sending mail through Python SMTP Server


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

Solution

  • 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.