如何拒绝收件人smtpd.SMTPServer.process_消息?

2024-06-03 16:49:55 发布

您现在位置:Python中文网/ 问答频道 /正文

假设您在重写类中处理消息,例如:

class MailProcessorServer(smtpd.SMTPServer):
  def process_message(self, peer, sender, rcpttos, data):
    badrecipients = []
    for rcpt in rcpttos:
      badrecipients.append(rcpt)

    #Here I want to warn the sender via a bounced email
    # that the recipient does not exist
    raise smtplib.SMTPRecipientsRefused(badrecipients)
    #but this just crashes the process and eventually the sender times out,
    # not good enough

我只想立刻回复发信人。相反,发送服务(比如GMail)最终会放弃,并在数小时后警告用户。documentation似乎很稀疏。在


Tags: theself消息messagedefnotprocesssender
3条回答

仅在the sources中记录(抱歉!),process_message的规格包括:

This function should return None, for a normal `250 Ok' response; otherwise it returns the desired response string in RFC 821 format.

因此,您可以“return'554 bad recipients%s”%badrecipients“,而不是使用不完全令人满意的raise语句(不能正确地考虑好的和坏的,它由rfc821应该返回一个'250ok',但稍后也会发送一封警告邮件),但它看起来确实是“立即反弹”的效果,raise。在

拒绝消息的方法是返回一个带有process_message方法的错误代码的字符串;例如

return '550 No such user here'

然而,rfc821不允许在消息数据被传输后返回错误代码550(它应该在RCPT命令之后返回),不幸的是,smtpd模块并没有提供在该阶段返回错误代码的简单方法。此外,smtpd.py公司使用自动损坏的“private”双下划线属性很难对其类进行子类化。在

您可能可以使用smtpd类的以下自定义子类,但我尚未测试此代码:

^{pr2}$

以下内容将丢弃邮件,而不会弹出邮件。在

return '554-5.7.1'

问题:如果您拒绝了一封邮件而没有弹出,则发件人MTA将尝试一次又一次地重新发送邮件。在

错误代码550将弹出电子邮件,这可能是个坏主意,因为您不想向垃圾邮件发送者提供任何有关您的邮件服务器的信息。小心点。在

^{pr2}$

两个错误都将引发smtplib.SMTPException。下面是我用来处理此类异常的简化代码。在

try:
    if bounce:
        return '550 Bad address'
    else:
        self.send_and_quit(sender, recipients, data)
except smtplib.SMTPException as e:
    raise e
except Exception as e:
    # Catch any other exception
    logging.error(traceback.format_exc())

    if not isinstance(e, smtplib.SMTPException):
        self.send_and_quit(sender, recipients, data)
    else:
        raise e

相关问题 更多 >