Search code examples
javajakarta-mail

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?


Solution

  • 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);