如何使用 python smtpd 创建类似 postfix 的服务器

How to create a postfix-like server with python smtpd

关于 python smtpd 库,我尝试覆盖 process_message 方法,但是当我尝试与客户端连接并向其发送消息时,比如 gmail 帐户,它只是打印控制台上的消息,但我希望它实际上像本地机器中的 postfix 一样发送消息。我该如何实现?

我google smtpd,但没找到多少有用的信息

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

引用 , 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 这里有一个很好的教程。然后,您可以使用下面的 Python 代码发送电子邮件。

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

希望这对您有所帮助!