这两天在做POP3邮件收取,收件人信息总是乱码,仔细研究了一下,找到规则如下=?编码规则?编码方式?内容?=

编码方式分两种B代表Base64,Q代表QP

下面是C#解决办法。

另外在开源的LumiSoft.Net.Core.CanonicalDecode 这个类中也能找到解决方法,编译的时候提示 "LumiSoft.Net.Core.CanonicalDecode(string)"已过时:"Use MimeUtils.DecodeWords method instead."其实这个替换类并不好用,有的内容解析不出来,还是老方法管用

测试数据

=?GB2312?B?ufq6vdaq0vQ=?= 国航知音

=?GBK?B?1tDQxdDF08O/qNbQ0MQ=?= 中信信用卡中心

=?gb2312?q?SMS=CA=FD=BE=DD=B1=ED=CB=B5=C3=F7?= SMS数据表说明

#region 邮件标题编码

private string DecodeMailSubject(string subject)

{//格式为 =?编码规则?编码方式?内容?=

try

{

string[] str = subject.Split('?');

string ruler = str[1];

string codetype = str[2];

string code = str[3];

if (codetype.ToLower() == "q")

return DecodeQP(ruler, code);

if (codetype.ToLower() == "b")

return DecodeBase64(ruler, code);

return code;

}

catch

{

return subject;

}

}

private string DecodeBase64(string code_type, string code)

{

string decode = "";

byte[] bytes = Convert.FromBase64String(code);

try

{

decode = Encoding.GetEncoding(code_type).GetString(bytes);

}

catch

{

decode = code;

}

return decode;

}

private string DecodeQP(string code_type, string code)

{

string decode = "";

try

{

char ch, ch1, ch2;

int chint, chint1, chint2;

if (code != null)

{

code = code.Replace("=09", "");

code = code.Replace("==", "=");

}

char[] hz = code.ToCharArray();

 

byte[] bytes = new byte[2];

decode = "";

for (int i = 0; i < code.Length; i++)

{

ch = hz[i];

if (ch == '=')

{

i++;

ch1 = hz[i];

if (ch1 == 13 || ch1 == 10)

{

//i++;

continue;

}

i++;

ch2 = hz[i];

if (ch1 == '3' && ch2 == 'D')

{

//System.Text.Encoding.GetEncoding(54936).GetString(b);

decode += "=";

continue;

}

else

{

 

if (ch1 > '9')

{

chint1 = (ch1 - 'A' + 10) * 16;

}

else

{

chint1 = (ch1 - '0') * 16;

}

if (ch2 > '9')

{

chint2 = ch2 - 'A' + 10;

}

else

{

chint2 = ch2 - '0';

}

 

ch = hz[i + 1];

if (ch != '=')

{

decode += ch1.ToString();

decode += ch2.ToString();

continue;

}

chint = chint1 + chint2;

bytes[0] = Convert.ToByte(chint);

 

 

i = i + 2;

ch1 = hz[i];

while (ch1 == 13 || ch1 == 10)

{

i++;

i++;

ch1 = hz[i];

}

if (ch1 == '=')

{

i++;

ch1 = hz[i];

}

i++;

ch2 = hz[i];

 

if (ch1 > '9')

{

chint1 = (ch1 - 'A' + 10) * 16;

}

else

{

chint1 = (ch1 - '0') * 16;

}

if (ch2 > '9')

{

chint2 = ch2 - 'A' + 10;

}

else

{

chint2 = ch2 - '0';

}

 

chint = chint1 + chint2;

bytes[1] = Convert.ToByte(chint);

 

decode += System.Text.Encoding.GetEncoding(code_type).GetString(bytes);

 

}

 

}

else

{

decode += ch.ToString();

}

}

}

catch

{

decode = code;

}

return decode;

 

 

}

 

#endregion