user1260928
user1260928

Reputation: 3429

Add attachment to mail from bytearrayoutputstream

I am trying to send an email with attachment like this :

MimeMessageHelper message = new MimeMessageHelper(mimeMessage, false, CharEncoding.UTF_8);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
message.addAttachment("facture.pdf",  new ByteArrayResource(IOUtils.toByteArray(is)));

I am getting an error :

java.lang.IllegalStateException: Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.

Is there a way to make it work keeping the addAttachment method?

Upvotes: 4

Views: 10418

Answers (2)

Nicola Pellicanò
Nicola Pellicanò

Reputation: 469

You have to specify as the second parameter of the constructor the multipart mode. There are multiple choices of the multipart mode:

  • MULTIPART_MODE_NO

  • MULTIPART_MODE_MIXED

  • MULTIPART_MODE_RELATED

  • MULTIPART_MODE_MIXED_RELATED

By passing false you are setting ** MULTIPART_MODE_NO**, which doesn't allow you to insert attachments.

By passing true you will set ** MULTIPART_MODE_MIXED_RELATED**, which is described in the docs in this way:

This is arguably the most correct MIME structure, according to the MIME spec: It is known to work properly on Outlook, Outlook Express, Yahoo Mail, and Lotus Notes. Does not work properly on Mac Mail. If you target Mac Mail or experience issues with specific mails on Outlook, consider using MULTIPART_MODE_RELATED instead.

In general you can choose the best for you by using this alternative constructor:

public MimeMessageHelper(MimeMessage mimeMessage,
                     int multipartMode,
                     String encoding)
              throws MessagingException

Which differs by asking for an integer constraint (one of the above) instead of a boolean.

Upvotes: 2

Arnaud
Arnaud

Reputation: 17534

It seems from the documentation of MimeMessageHelper, that you only have to pass a true flag.

MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, CharEncoding.UTF_8);

Upvotes: 13

Related Questions