pythonpostfix-mtasmtpd

How to create a postfix-like server with python smtpd


About the python smtpd library, I try to override the process_message method, but when I try to connect to it with client and send message to, say a gmail account, it just print the message out on console, but I want it actually to send out the message like postfix in local machine. How should I achieve this?

I google smtpd, but not much useful message to find

import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):

    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        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()

Solution

  • Citing Robert Putt's answer, you're going to struggle with deliverability. You're best solution would be to locally host an SMTP server (of course the supreme solution would be to use AmazonSES or an API like MailGun). DigialOcean has a good tutorial here. You can then use the below Python code to send out an email.

    import smtplib
    
    sender = 'no_reply@mydomain.com'
    receivers = ['person@otherdomain.com']
    
    message = """From: No Reply <no_reply@mydomain.com>
    To: Person <person@otherdomain.com>
    Subject: Test Email
    
    This is a test e-mail message.
    """
    
    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message)         
        print("Successfully sent email")
    except SMTPException:
        print("Error: unable to send email")
    

    Hopefully this helps!