C#及JAVA之邮件服务器IMAP文件夹名称编码解码实现(支持中文名称)
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
IMAP邮件客户端中读取和创建邮件夹时需要对邮件夹名称进行编码和解码。该方法是通过网络上流传的perl语言方法改写的,配合InterIMAP项目可以编写完整IMAP邮件客户端。 InterIMAP项目地址: http://interimap.codeplex.com/ 编码和解码方法,具体含义可以参考国际标准的定义:http://www.faqs.org/rfcs/rfc3501.html C#: //编码 private string IMAPEncode(string folder) { string rtn = "", base64; int index = 0; Regex regAsis = new Regex(@"\G(?:[\x20-\x25\x27-\x7e])+"); Regex reg26 = new Regex(@"\G&"); Regex regEncode = new Regex(@"\G(?:[^\x20-\x7e])+"); Regex regEq = new Regex(@"=+$"); Regex regSlash = new Regex(@"\/"); while (index < folder.Length) { Match m; m = regAsis.Match(folder, index); if (m.Success) { index = index + m.Length; rtn = rtn + m.Value; continue; } m = reg26.Match(folder, index); if (m.Success) { index = index + m.Length; rtn = rtn + "&-"; continue; } m = regEncode.Match(folder, index); if (m.Success) { index = index + m.Length; base64 = Convert.ToBase64String(Encoding.GetEncoding("UTF-16BE").GetBytes(m.Value)); base64 = regEq.Replace(base64, ""); base64 = regSlash.Replace(base64, ","); rtn = rtn + "&" + base64 + "-"; continue; } } return rtn; } // 解码 private string IMAPDeconde(string folder) { string rtn = "", base64; int index = 0; Regex regAsis = new Regex(@"\G([^&]+)"); Regex reg26 = new Regex(@"\G\&-"); Regex regDecode = new Regex(@"\G\&([A-Za-z0-9+,]+)-?"); Regex regComma = new Regex(@","); while (index < folder.Length) { Match m; m = regAsis.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + m.Value; continue; } m = reg26.Match(folder, index); if(m.Success) { index = index + m.Length; rtn = rtn + "&"; continue; } m = regDecode.Match(folder, index); if(m.Success) { index = index + m.Length; base64 = m.Value.Substring(1, m.Value.Length - 2); base64 = regComma.Replace(base64, "/"); int mod = base64.Length % 4; if(mod > 0 ) { int count = 4 - mod; while (count > 0) { base64 += "="; count--; } //base64 = base64.PadRight(base64.Length + (4 - mod), "="); } base64 = Encoding.GetEncoding("UTF-16BE").GetString(Convert.FromBase64String(base64)); rtn = rtn + base64; continue; } } return rtn; } JAVA:
该文章在 2017/10/25 14:27:59 编辑过 |
关键字查询
相关文章
正在查询... |