Custom response to DATA with Twisted Python SMTP?

2019-08-27 22:20发布

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条回答
Deceive 欺骗
2楼-- · 2019-08-27 22:26

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.

查看更多
登录 后发表回答