bbottema / simple-java-mail

Simple API, Complex Emails (Jakarta Mail smtp wrapper)

Home Page:http://www.simplejavamail.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature: set a maximum email size on Mailer level which throws EmailToBig exception when exceeded

jpnffigueiredo opened this issue · comments

Hi,

Thanks for this amazing java mailing library.

I would like to ask you if is possible to have any (efficient) way to calculate final message size?

In some scenarios we are checking message size before send it.

Currently, we are doing this by converting Email to MimeMessage and then write it an output stream.

Some like this:

final EmailPopulatingBuilder builder = ....;
final Email message = builder.buildEmail();
try (final CountingOutputStream out = new CountingOutputStream(NullOutputStream.NULL_OUTPUT_STREAM)) {
    EmailConverter.emailToMimeMessage(message).writeTo(out);
    if (out.getByteCount() > limit) {
        //Message bigger than limit
    }
}

// Send email
mailer.sendMail(message);

With this solution we are creating MimeMessage twice: one just to check size and other inside mailer.sendEmail.

Do you have any suggestion to calculate this or is possible to (somehow) cache MimeMessage or allow mailer.send(mimeMessage)? Just saying some options.

Thanks in advance.

Best regards,
João Figueiredo.

Is it important to get the size before sending the email or is it fine to get it after sending?

Closing until I get more details.

Hi,

Sorry for the delay.

For current use case we need it before sending email. We want to check message size because we already know the smtp server message limit.

After sending the message, maybe we could catch exception and check message. We are trying to prevent send message that will fail due to message size.

Thanks.

Ahh... that's a good point, actually. I have to think about this though, it's not trivial as the conversion to MimeMessage happens at the end of the chain, in case of batch-module even after a Transport was claimed from the SMTP connection pool.

I think a specific exception might do the trick. I'll have a look.

Feature released in 7.8.0. You can now set the maximum Email size like this:

Mailer mailer = MailerBuilder
      .(..)
      .withMaximumEmailSize(4) // 4 bytes, that's not much
      .buildMailer();

try {
	mailer.sendMail(emailBiggerThan4Bytes)
} catch(Exception e) {
	// cause: EmailTooBigException
	// msg: "Email size of 277 bytes exceeds maximum allowed size of 4 bytes"
	e.getCause().printStrackTrace();
}