IndianerJones
IndianerJones

Reputation: 1075

How to save an Email as Text

As backup I want to store the original received emails that were fetched with Java.

My current approach is to use the writeTo method:

MimeMessage mimeMessage;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
     mimeMessage.writeTo(out);
     String rawContent = out.toString();
     FileUtiles.writeStringToFile("email.txt", rawContent);
}

But when I send this Email via Telnet:

Return-Path: <[email protected]>
To: <[email protected]>
Subject: test special chars
Content-Type: multipart/mixed; boundary="=_1c4a520f54326063ea347cd3da780d5a"

--=_1c4a520f54326063ea347cd3da780d5a
Content-Type: text/plain; charset="IBM850"
Content-Transfer-Encoding: 7bit

Test
ä ü Ö ß
Test

--=_1c4a520f54326063ea347cd3da780d5a
Content-Type: application/zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="archive.zip"

--=_1c4a520f54326063ea347cd3da780d5a--

The "ä ü Ö ß" part is broken in the Textfile (replaced by "� � � �". In Outlook everything looks fine.

My understanding of the Email protocol is, that only ascii chars are sent. Why isn't it working, and what can I do to have it working?

EDIT: The Email should be in it's original state as backup if anything goes wrong. As the email protocol works with only ASCII chars, there should be no issue saving the whole email. Quoted printable Encoding (like in the supposed dublicate I much prefer over this 7bit stuff, but I don't have control over the Emails coming in.

Upvotes: 1

Views: 504

Answers (1)

Peter Salomonsen
Peter Salomonsen

Reputation: 5683

You shouldn't convert the message to string - rather let mimeMessage.writeTo(fileOutputStream) - write directly to a FileOutputStream. (Converting to string puts you in risk of charset problems)

Upvotes: 1

Related Questions