2

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()
canton7
  • 37,633
  • 3
  • 64
  • 77
  • Are you trying to send an email or receive an email? The code above is to receive a message. – MJPinfield Apr 14 '19 at 17:56
  • Send an email, but without using smtplib to connect and authenticate to other smtp servers such as gmail, I want this code itself be an smtp server, when it receive the email it can transfer it to other smtp server – Leslie Binbin Apr 15 '19 at 01:48

1 Answers1

0

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!

MJPinfield
  • 796
  • 10
  • 25