Custom response to DATA with Twisted Python SMTP?

こ雲淡風輕ζ 提交于 2020-01-17 07:15:26

问题


How can I specify a custom error code/response to a DATA command using Twisted's SMTP? In eomReceived in the code, I want to return a failure with a custom string. Right now, I can return a Deferred() with an errback set, which sends back a 550 code, but I can't specify the response string and I get an Unhandled Error in my logs.

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

回答1:


You need to:

  • subclass ESTMP
  • implement a do_DATA on your subclass (see twisted.mail.smtp.SMTP for examples)

the SMTP base class's lineReceived will receive your line, pass it on to state_COMMAND (assuming it's in command state), which will look up the method starting with do_ to pass the rest of the line to.



来源:https://stackoverflow.com/questions/12217858/custom-response-to-data-with-twisted-python-smtp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!