// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Globalization; using System.IO; using System.Text; namespace E { public class Mime { private static string FromQP(string s) { StringBuilder sb = new StringBuilder(""); int ix = 0; while(ix < s.Length) { if(s[ix] == '=') { sb.Append((char)int.Parse(s.Substring(ix + 1, 2), NumberStyles.HexNumber)); ix += 3; } else { sb.Append(s[ix]); ix++; } } return sb.ToString(); } private const string SEP = "\r\n\r\n"; private const string TYPE = "Content-Type:"; private const string CHARSET = "charset="; private const string TRANSFER = "Content-Transfer-Encoding:"; private const string QP = "quoted-printable"; public static string DecodeBody(byte[] b) { int split = Encoding.ASCII.GetString(b).IndexOf(SEP); bool qp = false; Encoding enc = Encoding.ASCII; using(StreamReader hdr = new StreamReader(new MemoryStream(b, 0, split))) { string line; while((line = hdr.ReadLine()) != null) { if(line.Contains(TYPE) && line.Contains(CHARSET)) { int ix = line.IndexOf(CHARSET) + CHARSET.Length; enc = Encoding.GetEncoding(line.Substring(ix)); } if(line.Contains(TRANSFER) && line.Contains(QP)) { qp = true; } } } StringBuilder sb = new StringBuilder(); using(StreamReader body = new StreamReader(new MemoryStream(b, split + SEP.Length, b.Length - split - SEP.Length), enc)) { string line; while((line = body.ReadLine()) != null) { if(!qp) { sb.Append(line); } else { sb.Append(FromQP(line)); } sb.Append(Environment.NewLine); } } return sb.ToString(); } } public class Test { public static void Main(string[] args) { byte[] tst1 = Encoding.UTF8.GetBytes( @"Content-Type: text/plain;charset=UTF-8 Content-Transfer-Encoding: 8bit Dette er en test. øøø"); byte[] tst2 = Encoding.ASCII.GetBytes( @"Content-Type: text/plain;charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Dette er en test. =F8=F8=F8"); Console.WriteLine(Mime.DecodeBody(tst1)); Console.WriteLine(Mime.DecodeBody(tst2)); } } }