opensmtp 是 .net 平臺上一個不錯的郵件發送組件,但是其中存在一些 bug 影響我們的使用,我在使用中遇到了郵件主題長度較大時,郵件出現亂碼的情況。
經過檢查源代碼發現,原來的處理過程存在問題:首先主題是通過 ascii 編碼的,其次,使用了 qp 編碼,但沒有考慮主題與內容的區別。
在主題中編碼時,每一行必須都要單獨編碼,不可將主題全部編碼。
經過與 outlook express 對比,在 mailencoding 類中增加一個方法,專門針對郵件主題進行 base64 編碼
public static string convertheadertobase64(string s, string charset)
{
int linelength = 40; // 每行處理 40 個字節
encoding encoding = encoding.getencoding( charset ); // 取指定編碼
byte[] buffer = encoding.getbytes( s ); // 轉換為字節碼
stringbuilder sb = new stringbuilder(); // 保存最終結果
string linebase64 ;
int block = buffer.length%linelength==0?buffer.length/linelength:buffer.length/linelength + 1;
for(int i=0; i< block; i++)
{
if( buffer.length - i*linelength >=linelength )
linebase64 = convert.tobase64string( buffer, i*linelength, linelength );
else
linebase64 = convert.tobase64string( buffer, i*linelength, buffer.length - i*linelength);
sb.append( "=?" );
sb.append( charset );
sb.append( "?b?" );
sb.append( linebase64 );
sb.append( "?=/r/n/t" );
}
sb.remove( sb.length-3, 3); // 刪除最后的換行符號
return sb.tostring();
}
然后,將 mailmessage 類中的 tostring 方法中對郵件主題的處理修改為調用自定義的方法
// sb.append("subject: " + mailencoder.convertheadertoqp(cleansubject.tostring(), charset) + "/r/n");
sb.append("subject: " + mailencoder.convertheadertobase64( cleansubject.tostring(), charset) + "/r/n");
重新編譯即可
新聞熱點
疑難解答