Search code examples
c#emailmailkitdecodercontent-encoding

How to decode ContentEncoding.SevenBit and ContentEncoding.EightBit MimePart with C# MailKit


I have this piece of code:

private string DecodeMimePart(MimePart mimePart)
{
    var decodedString = "";

    IMimeDecoder mimeDecoder = mimePart.ContentTransferEncoding switch
    {
        ContentEncoding.SevenBit => throw new NotImplementedException(),
        ContentEncoding.EightBit => throw new NotImplementedException(),
        ContentEncoding.Binary => new HexDecoder(),
        ContentEncoding.Base64 => new Base64Decoder(),
        ContentEncoding.QuotedPrintable => new QuotedPrintableDecoder(),
        ContentEncoding.UUEncode => new UUDecoder(),
        _ => throw new Exception($"ContentTransferEncoding '{mimePart.ContentTransferEncoding}' not supported"),
    };
        using var streamReader = new StreamReader(mimePart.Content.Stream, true);
        decodedString = streamReader.ReadToEnd();
        var encodedStringBytes = Encoding.UTF8.GetBytes(decodedString);
        var decodedStringBytes = new byte[4096];
        int decodedBytesNumber = mimeDecoder.Decode(encodedStringBytes, 0, encodedStringBytes.Length, decodedStringBytes);

        decodedString = Encoding.UTF8.GetString(decodedStringBytes, 0, decodedBytesNumber);

    return decodedString;
}

and I need to know what decoder I have to use with SevenBit and EightBit content-encoding. I've checked the documentation here but I didn't find the correct decoder.

Thanks.


Solution

  • Why not use mimePart.Content.DecodeTo() instead of trying to manually do it yourself?