扭曲的SMTP服务器限制传入的电子邮件大小

时间:2014-04-23 21:06:58

标签: python email python-2.7 smtp twisted

这是我用来创建使用twisted的SMTP服务器的基本代码:

from email.Header import Header
from twisted.internet import protocol, defer, reactor
from twisted.mail import smtp
from zope.interface import implements


class ConsoleMessageDelivery(object):
    implements(smtp.IMessageDelivery)

    def receivedHeader(self, helo, origin, recipients):
        myHostname, clientIP = helo
        headerValue = "by %s from %s with ESMTP ; %s" % (myHostname,
                                                         clientIP,
                                                         smtp.rfc822date())
        return "Received: %s" % Header(headerValue)

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

    def validateTo(self, user):
        # Only messages directed to the "console@domain" user are accepted.
        if user.dest.local == "console":
            return lambda: ConsoleMessage()
        raise smtp.SMTPBadRcpt(user)


class ConsoleMessage(object):
    implements(smtp.IMessage)

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

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

    def eomReceived(self):
        print "New message received:"
        print "\n".join(self.lines)
        self.lines = None
        return defer.succeed(None)

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


class LocalSMTPFactory(smtp.SMTPFactory):

    def buildProtocol(self, addr):
        smtpProtocol = smtp.ESMTP()
        smtpProtocol.delivery = ConsoleMessageDelivery()
        return smtpProtocol

reactor.listenTCP(2025, LocalSMTPFactory())
reactor.run()

我可以接收电子邮件,但如果我想拒绝1MB或更大的传入邮件,我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

请注意,每条消息都会调用ConsoleMessage.lineReceived。每条线都有一个尺寸(毫无疑问,类似于它的长度)。您可以计算收到的所有行的大小,并根据结果采取行动。

此外,您可以浏览SIZE ESMTP扩展,该扩展允许服务器声明将接受的最大邮件大小。这不会在代码处理消息行中替换检查,因为不能保证客户端会尊重声明的最大值,但在智能协作客户端的情况下,它将节省一些无意义的数据传输

SIZE是一个足够简单的扩展,您可以通过继承twisted.mail.smtp.ESMTP并覆盖extensions方法添加它来将其添加到Twisted的ESMTP服务器。