Nearly all emails contain a Content-Type header. It could look like this:
Content-Type: text/plain; charset="UTF-8"
The header specifies what type of content is inside the part being looked at, and what character set (encoding) that is used.
The encoding is used to map the bytes in the email body into characters.
OpenPop uses an EncodingFinder class for mapping from a character set name, in this example
UTF-8, to the encoding,
Encoding.UTF8.
Here is the documentation for how the EncodingFinder class works:
/// <summary>
/// Utility class used by OpenPop for mapping from a characterSet to an Encoding.
///
/// The functionality of the class can be altered by adding mappings
/// using AddMapping and by adding a FallbackDecoder.
///
/// Given a characterSet, it will try to find the Encoding as follows:
/// 1: If a mapping for the characterSet was added, use the specified Encoding from there.
/// Mappings can be added using AddMapping.
/// 2: Try to parse the characterSet and look it up using Encoding.GetEncoding(int) for codepages
/// or Encoding.GetEncoding(string) for named encodings.
/// 3: If an encoding is not found yet, use the FallbackDecoder if defined.
/// The FallbackDecoder is user defined.
/// </summary>
Now, let us change how the EncodingFinder works:
/// <summary>
/// Example showing:
/// - How to provide custom Encoding class
/// - How to use UTF8 as default Encoding
/// </summary>
/// <param name="customEncoding">Own Encoding implementation</param>
public void InsertCustomEncodings(Encoding customEncoding)
{
// Lets say some email contains a characterSet of "iso-9999-9" which
// is fictional, but is really just UTF-8.
// Lets add that mapping to the class responsible for finding
// the Encoding from the name of it
EncodingFinder.AddMapping("iso-9999-9", Encoding.UTF8);
// It is also possible to implement your own Encoding if
// the framework does not provide what you need
EncodingFinder.AddMapping("specialEncoding", customEncoding);
// Now, if the EncodingFinder is not able to find an encoding, lets
// see if we can find one ourselves
EncodingFinder.FallbackDecoder = CustomFallbackDecoder;
}
The CustomFallbackDecoder is defined as:
Encoding CustomFallbackDecoder(string characterSet)
{
// Is it a "foo" encoding?
if (characterSet.StartsWith("foo"))
return Encoding.ASCII; // then use ASCII
// If no special encoding could be found, provide UTF8 as default.
// You can also return null here, which would tell OpenPop that
// no encoding could be found. This will then throw an exception.
return Encoding.UTF8;
}