📄 mailmanager.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace MobileMailSer
{
public class MailManager
{
private TcpClient tcpClient;
private NetworkStream networkStream;
private StreamReader sr;
private StreamWriter sw;
#region //mail的基本操作
public bool Connect(string pop3Sever)//连接服务器
{
try
{
tcpClient = new TcpClient(pop3Sever, 110);
networkStream = tcpClient.GetStream();
sr = new StreamReader(networkStream);
sw = new StreamWriter(networkStream);
string str = ReadData();
if (str == null)
{
return false;
}
return true;
}
catch
{
return false;
}
}
private bool SendData(string str)//想服务器发送数据
{
try
{
sw.WriteLine(str);
sw.Flush();
return true;
}
catch
{
return false;
}
}
private String ReadData()//从服务器读数据
{
String str = null;
try
{
str = sr.ReadLine();
if (str[0] == '-')
{
str = null;
}
}
catch
{
str = null;
}
return str;
}
public bool Logon(string username, string password)//登陆服务器
{
if (SendData("USER " + username) == false) return false;
if (ReadData() == null) return false;
if (SendData("PASS " + password) == false) return false;
if (ReadData() == null) return false;
return true;
}
public int TotalMail()//获得总的邮件数量
{
string str;
if (SendData("STAT") == false) return 0;
if ((str = ReadData()) == null) return 0;
string[] splitString = str.Split(' ');
int count = int.Parse(splitString[1]);
return count;
}
public string GetUID(int index)//获得指定的邮件的UID
{
string str;
if (SendData("UIDL " + index.ToString()) == false) str = null;
str = ReadData();
return str.Substring(str.LastIndexOf(' ') + 1);
}
public string GetEmailContent(int index)//有得邮件的内容
{
string str = null;
if (SendData("RETR " + index.ToString()) == false) return str;
StringBuilder totalText = new StringBuilder();
if ((str = ReadData()) == null) return str;
while ((str = sr.ReadLine()) != ".")
{
totalText.Append(str);
totalText.Append("\n");
}
return totalText.ToString();
}
public string ParseSender(string emailContent)
{
string pat = @"^From\s*:\s*(?<sender>.*)\n";
Match m = Regex.Match(emailContent, pat, RegexOptions.IgnoreCase | RegexOptions.Multiline);
string sender = m.Groups["sender"].ToString();
pat = "\"?=\\?(?<TextEncoding>.+)\\?(?<encodingmethod>[A-Z])\\?(?<encodedText>.*)\\?=\"?(?<other>.*)$";
m = Regex.Match(sender, pat, RegexOptions.IgnoreCase);
string TextEncoding = m.Groups["TextEncoding"].ToString();
string encodingmethod = m.Groups["encodingmethod"].ToString();
string encodedText = m.Groups["encodedText"].ToString();
string other = m.Groups["other"].ToString();
if (encodingmethod.ToUpper().Equals("B"))//对base64方式加码的字符串进行解码
{
byte[] inputBytes = Convert.FromBase64String(encodedText);
string str = System.Text.Encoding.GetEncoding(54936).GetString(inputBytes, 0, inputBytes.Length);
sender = str + other;
}
else if (encodingmethod.ToUpper().Equals("Q"))
{
sender = ConvertFromQPString(encodedText, System.Text.Encoding.GetEncoding(TextEncoding)) + other;
}
return
sender;
}
public string ParseEmailText(string emailContent)
{
string isTextOnly =@"^Content-Type:\s*multipart";
bool t = Regex.IsMatch(emailContent,isTextOnly,RegexOptions.Multiline);
if( t)
{
string pat = @"^(?<boundary>.*)\nContent-Type:\s*text/plain";
Match match = Regex.Match(emailContent, pat, RegexOptions.Multiline);
string boundary = match.Groups["boundary"].ToString();
pat = @"^Content-Type:\s*text/plain[\s\S]*?Content-Transfer-Encoding:\s*(?<encodingMethod>.*)\n(?<crytext>[\s\S]*?)"+boundary;
Match myMatches = Regex.Match(emailContent, pat, RegexOptions.IgnoreCase | RegexOptions.Multiline);
GroupCollection myGroup = myMatches.Groups;
string crytext = myGroup["crytext"].ToString();//title变量存储From域的内容
string encodingMethod = myGroup["encodingMethod"].ToString();
if (encodingMethod.ToUpper().Equals("BASE64"))
{
crytext = crytext.Replace("\n", "");
byte[] inputBytes = Convert.FromBase64String(crytext);
string EmailText = System.Text.Encoding.GetEncoding(54936).GetString(inputBytes, 0, inputBytes.Length);
return EmailText;
}
else
{
return ConvertFromQPString(crytext,System.Text.Encoding.GetEncoding(54936)).Replace("\n","\r\n");
}
}
else
{
string pat = @"^Content-Type:\s*text/plain[\s\S]*?Content-Transfer-Encoding:\s*(?<encodingMethod>.*)\n(.*\n)*?\s*\n(?<crytext>[\s\S]+)";
Match myMatches = Regex.Match(emailContent, pat, RegexOptions.IgnoreCase | RegexOptions.Multiline);
GroupCollection myGroup = myMatches.Groups;
string crytext = myGroup["crytext"].ToString();//title变量存储From域的内容
string encodingMethod = myGroup["encodingMethod"].ToString();
if (encodingMethod.ToUpper().Equals("BASE64"))
{
crytext = crytext.Replace("\n", "");
byte[] inputBytes = Convert.FromBase64String(crytext);
string EmailText = System.Text.Encoding.GetEncoding(54936).GetString(inputBytes, 0, inputBytes.Length);
return EmailText;
}
else
{
return ConvertFromQPString(crytext, System.Text.Encoding.GetEncoding(54936)).Replace("\n", "\r\n");
}
}
}
public void getSender_Text(int index, out string sender, out string mailText)
{
string mailContent = GetEmailContent(index);
sender = ParseSender(mailContent);
mailText = ParseEmailText(mailContent);
}
#endregion
public string ConvertFromQPString(string quoted_printableString, System.Text.Encoding encoding)
{
string InputString = quoted_printableString;
StringBuilder builder1 = new StringBuilder();
// InputString = InputString.Replace("=\r\n", "");
for (int num1 = 0; num1 < InputString.Length; num1++)
{
if (InputString[num1] == '=')
{
try
{
if (HexToDec(InputString.Substring(num1 + 1, 2)) < 0x80)
{
if (HexToDec(InputString.Substring(num1 + 1, 2)) >= 0)
{
byte[] buffer1 = new byte[1] { (byte)HexToDec(InputString.Substring(num1 + 1, 2)) };
builder1.Append(encoding.GetString(buffer1, 0, buffer1.Length));
num1 += 2;
}
}
else if (InputString[num1 + 1] != '=')
{
byte[] buffer2 = new byte[2] { (byte)HexToDec(InputString.Substring(num1 + 1, 2)), (byte)HexToDec(InputString.Substring(num1 + 4, 2)) };
builder1.Append(encoding.GetString(buffer2, 0, buffer2.Length));
num1 += 5;
}
}
catch
{
builder1.Append(InputString.Substring(num1, 1));
}
}
else
{
builder1.Append(InputString.Substring(num1, 1));
}
}
return builder1.ToString();
}
private static int HexToDec(string hex)
{
int num1 = 0;
string text1 = "0123456789ABCDEF";
for (int num2 = 0; num2 < hex.Length; num2++)
{
if (text1.IndexOf(hex[num2]) == -1)
{
return -1;
}
num1 = (num1 * 0x10) + text1.IndexOf(hex[num2]);
}
return num1;
}
~MailManager()
{
if (sr != null)
{
sr.Close();
}
if (sw != null)
{
sw.Close();
}
if (tcpClient != null)
{
tcpClient.Close();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -