Search code examples
androidemailkotlinwebmime

Create file from MIME message


I want to create files from the attachments of a multipart mime message. I can retrieve the information I need and also the creation itself is not a problem. what I struggle is that with the given headers and bodies I am not sure what encoding should be used to create the files.

Let's say we have to attachments:

//HEADER    
Content-Type: application/pdf;
         name="somepdf.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
         filename="somepdf.pdf"
//BODY
 %PDF-1.4
    7 0 obj <</Length1 1501 /Length2 7274 /Length3 0 /Length 8281 /Filter /FlateDecode>>
    .. 
    ..


//HEADER
Content-Type: text/x-tex; charset=UTF-8;
     name="sometex.tex"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
     filename="sometex.tex"

//BODY
    \documentclass[a4paper, 12pt]{article}
    \usepackage[german,english]{babel}
    \usepackage{fullpage, graphicx}
    ..
    ..

If I want to create a file of this information how should I choose the encoding of the files? If I just take the body of the pdf e.g. and use it straight to write a pdf file it results in a not readable pdf, because the encoding is wrong. what is the correct encoding for the corresponding file? I am doing this on android with kotlin if you have some additional tips on how to do this


Solution

  • Parsing emails is hard. There are a range of different encoding methods, character sets and it's quite common to see edge cases and nesting of multipart content within email.

    Attempting to just extract the body section won't cover the encoding methods and each one will be different and will require knowledge of the RFC standards for email (such as RFC 5322, 2822, 822).