0
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mimeMessage.writeTo(outputStream);

That's the code where I write the entire email Mime content (including the headers) to an output stream because I didn't find any other way to copy the entire content as a string. This email needs to go out on an HTTP response as string. The getContent() only gives the body of the email. I need the entire header info, encoding, charset, content-type all on a string.

But when I have an html with the below content as the body of the email, the (') gets replaced with (?). I know this an encoding issue. But how to set the right encoding while writing to output stream?

<td class="email_monthlySummaryGraph_subTitle chart-subtitle" style="border: 0; color: #1D1D1D; font-family: Arial, sans-serif; font-size: 16px; line-height: 1.4; margin: 0; padding-bottom: 20px; padding-left: 0; padding-right: 0; padding-top: 0; text-align: center;" align="center">
That’s 5 kWh less than your highest week this month
</td>

I tried setting the encoding on

String response =
                    new String(
                            ((ByteArrayOutputStream) resp).toByteArray(), StandardCharsets.UTF_8);

But I think it doesn't matter here coz by then, the characters are already replaced.

  • Does this answer your question? [Java: Encode String in quoted-printable](https://stackoverflow.com/questions/21574745/java-encode-string-in-quoted-printable) – JosefZ Apr 07 '23 at 14:50
  • *unrelated: between the `5` and `kWh` there is another non-ASCII character that looks like a space* – JonathanDavidArndt Apr 07 '23 at 18:47
  • The output of `mimeMessage.writeTo` is essentially a **binary** stream. You're treating it as if it is text with a single character set. It is not. Each MIME part can have its own character set and/or Transfer-Encoding. An additional problem may be that this actually works fine, but how you're printing the string applies a conversion so that those characters are replaced with a ?. This is especially common on Windows. – Mark Rotteveel Apr 08 '23 at 12:28
  • @JosefZ That doesn't. Because the user has a string that needs to be encoded to QP. But I have an entire mail that's already QP encoded. Everything is in place but I cannot send the full mail as a String response unless I write it to an outputstream. But when I do, it messes up with the encoding. – Srinidhi Murthy Apr 11 '23 at 13:19

0 Answers0