简体   繁体   English

估计新邮件的大小

[英]Estimate the size of a new mail

We have a postfix server configured with message_size_limit=10240000 (the default) and I would now like to prevent the creation of any mail that is bigger than that.我们有一个配置了message_size_limit=10240000 (默认值)的 postfix 服务器,我现在想阻止创建任何大于该值的邮件。 Because I get otherwise a "connection broken" error, which is difficult to present to the user in a meaningful error message.因为否则我会收到“连接中断”错误,这很难在有意义的错误消息中呈现给用户。

The definition of message_size_limit is: message_size_limit的定义是:

The maximal size in bytes of a message, including envelope information.消息的最大字节数,包括信封信息。

My question is: How can I calculate / predict / estimate the size in bytes of a created mail with lots of different attachments?我的问题是:如何计算/预测/估计带有大量不同附件的已创建邮件的大小(以字节为单位)? javax.mail.Message.size() is only available when receiving a mail. javax.mail.Message.size()仅在接收邮件时可用。

Take your draft Message object and use Message.writeTo to write it to a stream that does nothing with the data but just counts the number of bytes written:获取草稿 Message 对象并使用Message.writeTo将其写入一个流,该流对数据不执行任何操作,只计算写入的字节数:

public long getMessageSize(Message message) {
    CountingOutputStream counter = new CountingOutputStream(new NullOutputStream());
    message.saveChanges();
    message.writeTo(counter);
    return counter.getByteCount();
}

The CountingOutputStream is from commons-io , but the one from Guava or a slower ByteArrayOutputStream will do as well. CountingOutputStream来自commons-io ,但来自Guava或较慢的ByteArrayOutputStream也可以。

That will give you an estimate on the overall size of the message.这将为您提供对消息整体大小的估计。

Doing this is going to be expensive so you can't (for example) do it for every character typed into the message by the user.这样做会很昂贵,所以你不能(例如)对用户输入到消息中的每个字符都这样做。 You need to do it only on certain events (eg, adding an attachment) or after (eg) 5 minutes of typing data into a message.您只需要在某些事件(例如,添加附件)或在(例如)将数据输入消息 5 分钟后执行此操作。 You need a strategy to reduce the cost of the operation while providing timely feedback to the user.您需要一种策略来降低运营成本,同时向用户提供及时的反馈。

If you do this, be sure to call Message.saveChanges before each call to Message.writeTo , and before really sending the message.如果您这样做,请确保在每次调用Message.saveChanges之前以及在真正发送消息之前调用Message.writeTo

One thing which some don't realize is that binary attachments are always base64 encoded, and occasionally, even ASCII attachments.有些人没有意识到的一件事是二进制附件始终是base64编码的,有时甚至是 ASCII 附件。 Any attachment of K bytes will ultimately be 33% larger due to the encoding process.由于编码过程,任何K字节的附件最终都会大33% So you need to know if the folks that configure the server take that into consideration.所以你需要知道配置服务器的人是否考虑到了这一点。

Otherwise, what appears to be an email less than the advertised maximum, can be substantially more.否则,看起来少于广告最大值的电子邮件可能会更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM