博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

电子邮件解码类(三种解码)

Posted on 2011-05-06 10:59  Fung Gor  阅读(588)  评论(0)    收藏  举报

来源:http://zhangguofuwangyi.blog.163.com/blog/static/17175948720108299389275/

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;

namespace MyEmail.CommonClass
{
    class Decode
    {
        public Decode() { }

        /// <summary>几种解码方法
        /// </summary>
        /// 编码方式:Q   ---   Quote   Printable  
        ///           B   ---   BASE64  
        ///           U   ---   UUENCODE
        /// <param name="code">未解码</param>
        /// <returns name="decode">已解码</returns>

        //1.对邮件标题 base64(GB2312,GBK) 解码
        public string Base64(string code) //string code_type,
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.Default.GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
        //2.对邮件标题 base64(UTF-8) 解码
        public string Base64UTF(string code) //string code_type,
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }
        //3.对邮件标题为Quote Printable解码
        public string DecodeQP(string code, string charset)
        {
            ArrayList aryBytes = new ArrayList();
            char ch;
            int i = 0;
            while (i < code.Length)
            {
                ch = code[i];
                if (ch == '=')
                {
                    if (code.Substring(i, 3) == "=\r\n")
                    {
                        i += 3;
                    }
                    else
                    {
                        string tmp = code.Substring(i + 1, 2);
                        aryBytes.Add((byte)int.Parse(tmp, System.Globalization.NumberStyles.HexNumber));
                        i += 3;
                    }
                }
                else
                {
                    aryBytes.Add((byte)ch);
                    i++;
                }
            }
            byte[] decodeBytes = new byte[aryBytes.Count];
            for (int j = 0; j < aryBytes.Count; j++)
            {
                decodeBytes[j] = (byte)aryBytes[j];
            }
            string decode = Encoding.GetEncoding(charset).GetString(decodeBytes);
            return decode;

        }
    }
}