使用Twisted Python SMTP定制对数据的响应?

2022-04-18 00:00:00 python twisted smtp

问题描述

如何使用Twisted的SMTP为数据命令指定自定义错误代码/响应?在代码中的eomReceired中,我想用自定义字符串返回一个失败。现在,我可以返回一个带错误返回集的Defered(),它返回一个550代码,但我无法指定响应字符串,并且在我的日志中收到一个未处理的错误。

class ConsoleMessageDelivery:
    implements(smtp.IMessageDelivery)

    def receivedHeader(self, helo, origin, recipients):
        myHostname, clientIP = helo
        headerValue = "by %s from %s with ESMTP ; %s" % (myHostname, clientIP, smtp.rfc822date())
        # email.Header.Header used for automatic wrapping of long lines
        return "Received: %s" % Header(headerValue)

    def validateFrom(self, helo, origin):
        # All addresses are accepted
        return origin

    def validateTo(self, user):
        if user.dest.local == "console":
            return lambda: ConsoleMessage()
        raise smtp.SMTPBadRcpt(user)

class ConsoleMessage:
    implements(smtp.IMessage)

    def __init__(self):
        self.lines = []

    def lineReceived(self, line):
        self.lines.append(line)

    def eomReceived(self):
        # do something here, return defer.succeed(None) on success
        # right now on error, I do the following:
        d = defer.Deferred()
        d.errback("An error occurred")
        return d

    def connectionLost(self):
        # There was an error, throw away the stored lines
        self.lines = None

class ConsoleSMTPFactory(smtp.SMTPFactory):
    protocol = smtp.ESMTP

    def __init__(self, *a, **kw):
        smtp.SMTPFactory.__init__(self, *a, **kw)
        self.delivery = ConsoleMessageDelivery()

    def buildProtocol(self, addr):
        p = smtp.SMTPFactory.buildProtocol(self, addr)
        p.delivery = self.delivery
        return p

解决方案

您需要:

  • 子类ESTMP
  • 在您的子类上实现do_data(参见twisted.mail.smtp.SMTP示例)

SMTP基类的lineRecept将接收您的行,并将其传递给STATE_COMMAND(假设它处于COMMAND状态),它将查找以do_开头的方法,将该行的其余部分传递给。

相关文章