Skip to main content
 首页 » 编程设计

python之如何拒绝 smtpd.SMTPServer.process_message 中的收件人

2025年05月04日18mq0036

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

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看起来很稀疏。

请您参考如下方法:

仅在 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.

因此您可以“返回 '554 错误收件人 %s' % badrecipents”,而不是使用 raise 语句——不完全令人满意(没有正确说明好的和坏的混合,根据 RFC 821 应该返回“250 Ok”但稍后还会发送警告邮件)但它似乎确实是您正在寻找的“立即反弹”效果 提高。