首页 > 解决方案 > 如何使用 python smtpd 创建类似后缀的服务器

问题描述

关于 python smtpd 库,我尝试覆盖 process_message 方法,但是当我尝试与客户端连接并将消息发送到 gmail 帐户时,它只是在控制台上打印消息,但我希望它实际发送在本地机器中输出类似后缀的消息。我应该如何实现这一目标?

我谷歌 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()

标签: pythonpostfix-mtasmtpd

解决方案


引用罗伯特·普特(Robert Putt)的回答,您将在可交付性方面遇到困难。您最好的解决方案是在本地托管一个 SMTP 服务器(当然,最好的解决方案是使用AmazonSES或类似MailGun的 API )。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")

希望这会有所帮助!


推荐阅读