【问题标题】:twisted SMTP server limit incoming email message size扭曲的 SMTP 服务器限制传入电子邮件的大小
【发布时间】:2014-06-08 22:16:45
【问题描述】:

这是我用来创建使用 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 或更大的传入消息,我该怎么做?

【问题讨论】:

    标签: python email python-2.7 smtp twisted


    【解决方案1】:

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

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

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

    【讨论】:

    • 知道如何使用/声明扩展吗?
    • 我正在尝试使用 def extensions(self): ext = {'SIZE': 1048576} return ext 定义 SIZE 扩展名,但由于 --> r.append('%s %s' % (c, ' '.join(v ))) 添加扩展的正确方法是什么,这样我就可以得到类似'250-SIZE 1048576'
    • 也许你可以想到一个数据结构,当" ".join(it)被应用到它时,会产生"1048576"?
    • 我结束使用 ext['SIZE'] = ['1048576'],最后一个问题,250 之后的“-”是否也不需要扩展?
    • - 是与响应终止有关的通用 SMTP 语法。
    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2019-06-19
    • 1970-01-01
    • 2016-11-23
    相关资源
    最近更新 更多