C#通过POP3获取邮件的代码(正文和附件)

C#通过POP3获取邮件的代码(正文和附件),第1张

概述使用方法:获取第1封邮件复制代码代码如下:Zgke.Net.POP3_Popt=newZgke.Net.POP3(\"192.168.0.1\",110);DataTable_Mail=_Popt.GetMail(\"zk\",\"zk\",1);返回DataTable数据内容为Type为类型Text为文字如果是附件为byt 使用方法:
获取第1封邮件
复制代码 代码如下:
Zgke.Net.POP3 _Popt = new Zgke.Net.POP3("192.168.0.1",110);
Datatable _Mail = _Popt.GetMail("zk","zk",1);

返回Datatable 数据内容为
Type为类型 Text为文字 如果是附件 为byte[] name 如果是附件里存放的为文件名

 
下面是全部的类
复制代码 代码如下:
using System;
using System.Net.sockets;
using System.Net;
using System.Security.Cryptography;
using System.IO;
using System.Data;

namespace Zgke.Net
{

/// <summary>
/// 获取邮件的类
/// zgke@sina.com
/// qq:116149
/// </summary>
public class POP3
{
private string m_Address = "127.0.0.1";

private int m_Port = 110;

public POP3(string p_Address,int p_Port)
{
m_Address = p_Address;
m_Port = p_Port;
}

/// <summary>
/// 获取Mail列表
/// </summary>
/// <param name="p_name">用户名</param>
/// <param name="p_PassWord">密码</param>
/// <returns>Mail信息</returns>
public Datatable GetMailtable(string p_name,string p_PassWord)
{
POP3ClIEnt _ClIEnt = new POP3ClIEnt();
_ClIEnt.Username = p_name;
_ClIEnt.PassWord = p_PassWord;
_ClIEnt.ClIEnt = new TcpClIEnt();
_ClIEnt.ClIEnt.BeginConnect(m_Address,m_Port,new AsyncCallback(OnConnectRequest),_ClIEnt);
while (!_ClIEnt.ReturnEnd)
{
System.windows.Forms.Application.DoEvents();
}
if (_ClIEnt.Error.Length != 0) throw new Exception("错误信息!" + _ClIEnt.Error);
return _ClIEnt.MailDatatable;
}


/// <summary>
/// 获取邮件内容
/// </summary>
/// <param name="p_name">名称</param>
/// <param name="p_PassWord">密码</param>
/// <param name="p_Mailindex">邮件编号</param>
/// <returns>数据集</returns>
public Datatable GetMail(string p_name,string p_PassWord,int p_Mailindex)
{
POP3ClIEnt _ClIEnt = new POP3ClIEnt();
_ClIEnt.Username = p_name;
_ClIEnt.PassWord = p_PassWord;
_ClIEnt.ClIEnt = new TcpClIEnt();
_ClIEnt.Readindex = p_Mailindex;
_ClIEnt.ClIEnt.BeginConnect(m_Address,_ClIEnt);
while (!_ClIEnt.ReturnEnd)
{
System.windows.Forms.Application.DoEvents();
}
if (_ClIEnt.Error.Length != 0) throw new Exception("错误信息!" + _ClIEnt.Error);
return _ClIEnt.Mailtable;
}

private class POP3ClIEnt
{
public TcpClIEnt ClIEnt;

public string Username = "";

public string PassWord = "";

public bool ReturnEnd = false;

public Datatable MailDatatable = new Datatable();

public Datatable Mailtable = new Datatable();

public string Error = "";

public bool ReadEnd = false;

public int Readindex = -1;


public POP3ClIEnt()
{
MailDatatable.Columns.Add("NUM");
MailDatatable.Columns.Add("Size");
MailDatatable.Columns.Add("Form");
MailDatatable.Columns.Add("To");
MailDatatable.Columns.Add("Subject");
MailDatatable.Columns.Add("Date");

Mailtable.Columns.Add("Type",typeof(string));
Mailtable.Columns.Add("Text",typeof(object));
Mailtable.Columns.Add("name",typeof(string));
}

private int m_SendMessage = 0;
private int m_topIndex = 1;

/// <summary>
/// 获取下一个登陆到获取列表需要的命令
/// </summary>
/// <param name="p_Value"></param>
/// <returns></returns>
public byte[] GetSendBytes(byte[] p_Value)
{
ReadEnd = false;
string _Value = System.Text.EnCoding.Default.GetString(p_Value).Replace("\0","");
if (_Value.IndexOf("+OK") == 0)
{
m_SendMessage++;
switch (m_SendMessage)
{
case 1:
return System.Text.EnCoding.ASCII.GetBytes("USER " + Username + "\r\n");
case 2:
return System.Text.EnCoding.ASCII.GetBytes("PASS " + PassWord + "\r\n");
case 3:
ReadEnd = true;
if (Readindex != -1)
{
m_SendMessage = 5;
return System.Text.EnCoding.ASCII.GetBytes("RETR " + Readindex.ToString() + "\r\n");
}
else
{
return System.Text.EnCoding.ASCII.GetBytes("List\r\n");
}
case 4:
string[] _List = _Value.Split(new char[] { '\r','\n','.' },StringSplitoptions.RemoveEmptyEntrIEs);
for (int i = 1; i != _List.Length; i++)
{
string[] _MaliSize = _List[i].Split(' ');
MailDatatable.Rows.Add(new object[] { _MaliSize[0],_MaliSize[1] });
}
if (MailDatatable.Rows.Count == 0)
{
ReturnEnd = true;
return new byte[0];
}
else
{
ReadEnd = true;
m_topIndex = 1;
return System.Text.EnCoding.ASCII.GetBytes("top 1\r\n");
}
case 5:
System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"(?<=Date: ).*?(\r\n)+");
System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(_Value);
if (_Collection.Count != 0) MailDatatable.Rows[m_topIndex - 1]["Date"] = GetReadText(_Collection[0].Value);

System.Text.RegularExpressions.Regex _RegexFrom = new System.Text.RegularExpressions.Regex(@"(?<=From: ).*?(\r\n)+");
System.Text.RegularExpressions.MatchCollection _CollectionForm = _RegexFrom.Matches(_Value);
if (_CollectionForm.Count != 0) MailDatatable.Rows[m_topIndex - 1]["Form"] = GetReadText(_CollectionForm[0].Value);


System.Text.RegularExpressions.Regex _RegexTo = new System.Text.RegularExpressions.Regex(@"(?<=To: ).*?(\r\n)+");
System.Text.RegularExpressions.MatchCollection _CollectionTo = _RegexTo.Matches(_Value);
if (_CollectionTo.Count != 0) MailDatatable.Rows[m_topIndex - 1]["To"] = GetReadText(_CollectionTo[0].Value);

System.Text.RegularExpressions.Regex _RegexSubject = new System.Text.RegularExpressions.Regex(@"(?<=Subject: ).*?(\r\n)+");
System.Text.RegularExpressions.MatchCollection _CollectionSubject = _RegexSubject.Matches(_Value);
if (_CollectionSubject.Count != 0) MailDatatable.Rows[m_topIndex - 1]["Subject"] = GetReadText(_CollectionSubject[0].Value);

m_topIndex++;
m_SendMessage--;
ReadEnd = true;
if (m_topIndex > MailDatatable.Rows.Count)
{
ReturnEnd = true;
return System.Text.EnCoding.ASCII.GetBytes("QUIT");
}
else
{
return System.Text.EnCoding.ASCII.GetBytes("top " + m_topIndex.ToString() + "\r\n");
}
case 6:
GetMailText(_Value);
ReturnEnd = true;
return System.Text.EnCoding.ASCII.GetBytes("QUIT");

}
}
Error = _Value;
ReturnEnd = true;
return new byte[0];
}

/// <summary>
/// 转换文字里的字符集
/// </summary>
/// <param name="p_Text"></param>
/// <returns></returns>
public string GetReadText(string p_Text)
{
System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"(?<=\=\?).*?(\?\=)+");
System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(p_Text);
string _Text = p_Text;
foreach (System.Text.RegularExpressions.Match _Match in _Collection)
{
string _Value = "=?" + _Match.Value;
if (_Value[0] == '=')
{
string[] _BaseData = _Value.Split('?');
if (_BaseData.Length == 5)
{
System.Text.EnCoding _Coding = System.Text.EnCoding.GetEnCoding(_BaseData[1]);
_Text = _Text.Replace(_Value,_Coding.GetString(Convert.FromBase64String(_BaseData[3])));
}
}
else
{
}
}
return _Text;
}


#region 获取邮件正文 和 附件
/// <summary>
/// 获取文字主体
/// </summary>
/// <param name="p_Mail"></param>
/// <returns></returns>
public voID GetMailText(string p_Mail)
{
string _ConvertType = GetTextType(p_Mail,"\r\nContent-Type: ",";");
if (_ConvertType.Length == 0)
{
_ConvertType = GetTextType(p_Mail,"\r");
}
int _StarIndex = -1;
int _Endindex = -1;
string _ReturnText = "";
string _Transfer = "";
string _Boundary = "";
string _EnCodingname = GetTextType(p_Mail,"charset=\"","\"").Replace("\"","");
System.Text.EnCoding _EnCoding = System.Text.EnCoding.Default;
if(_EnCodingname!="")_EnCoding = System.Text.EnCoding.GetEnCoding(_EnCodingname);
switch (_ConvertType)
{
case "text/HTML;":
_Transfer = GetTextType(p_Mail,"\r\nContent-transfer-encoding: ","\r\n").Trim();
_StarIndex = p_Mail.IndexOf("\r\n\r\n");
if (_StarIndex != -1) _ReturnText = p_Mail.Substring(_StarIndex,p_Mail.Length - _StarIndex);
switch (_Transfer)
{
case "8bit":

break;
case "quoted-printable":
_ReturnText = DecodeQuotedPrintable(_ReturnText,_EnCoding);
break;
case "base64":
_ReturnText = DecodeBase64(_ReturnText,_EnCoding);
break;
}
Mailtable.Rows.Add(new object[] { "text/HTML",_ReturnText });
break;
case "text/plain;":
_Transfer = GetTextType(p_Mail,_EnCoding);
break;
}
Mailtable.Rows.Add(new object[] { "text/plain",_ReturnText });
break;
case "multipart/alternative;":
_Boundary = GetTextType(p_Mail,"boundary=\"","");
_StarIndex = p_Mail.IndexOf("--" + _Boundary + "\r\n");
if (_StarIndex == -1) return;
while (true)
{
_Endindex = p_Mail.IndexOf("--" + _Boundary,_StarIndex + _Boundary.Length);
if (_Endindex == -1) break;
GetMailText(p_Mail.Substring(_StarIndex,_Endindex - _StarIndex));
_StarIndex = _Endindex;
}
break;
case "multipart/mixed;":
_Boundary = GetTextType(p_Mail,_Endindex - _StarIndex));
_StarIndex = _Endindex;
}
break;
default:
if (_ConvertType.IndexOf("application/") == 0)
{
_StarIndex = p_Mail.IndexOf("\r\n\r\n");
if (_StarIndex != -1) _ReturnText = p_Mail.Substring(_StarIndex,p_Mail.Length - _StarIndex);
_Transfer = GetTextType(p_Mail,"\r\n").Trim();
string _name = GetTextType(p_Mail,"filename=\"","");
_name = GetReadText(_name);
byte[] _fileBytes = new byte[0];
switch (_Transfer)
{
case "base64":
_fileBytes = Convert.FromBase64String(_ReturnText);
break;
}
Mailtable.Rows.Add(new object[] { "application/octet-stream",_fileBytes,_name });

}
break;
}
}

/// <summary>
/// 获取类型(正则)
/// </summary>
/// <param name="p_Mail">原始文字</param>
/// <param name="p_TypeText">前文字</param>
/// <param name="p_End">结束文字</param>
/// <returns>符合的记录</returns>
public string GetTextType(string p_Mail,string p_TypeText,string p_End)
{
System.Text.RegularExpressions.Regex _Regex = new System.Text.RegularExpressions.Regex(@"(?<=" + p_TypeText + ").*?(" + p_End + ")+");
System.Text.RegularExpressions.MatchCollection _Collection = _Regex.Matches(p_Mail);
if (_Collection.Count == 0) return "";
return _Collection[0].Value;
}

/// <summary>
/// QuotedPrintable编码接码
/// </summary>
/// <param name="p_Text">原始文字</param>
/// <param name="p_EnCoding">编码方式</param>
/// <returns>接码后信息</returns>
public string DecodeQuotedPrintable(string p_Text,System.Text.EnCoding p_EnCoding)
{
System.IO.MemoryStream _Stream = new System.IO.MemoryStream();
char[] _CharValue = p_Text.tochararray();
for (int i = 0; i != _CharValue.Length; i++)
{
switch (_CharValue[i])
{
case '=':
if (_CharValue[i + 1] == '\r' || _CharValue[i + 1] == '\n')
{
i += 2;
}
else
{
try
{
_Stream.WriteByte(Convert.ToByte(_CharValue[i + 1].ToString() + _CharValue[i + 2].ToString(),16));
i += 2;
}
catch
{
_Stream.WriteByte(Convert.ToByte(_CharValue[i]));
}
}
break;
default:
_Stream.WriteByte(Convert.ToByte(_CharValue[i]));
break;
}
}
return p_EnCoding.GetString(_Stream.ToArray());
}

/// <summary>
/// 解码BASE64
/// </summary>
/// <param name="p_Text"></param>
/// <param name="p_EnCoding"></param>
/// <returns></returns>
public string DecodeBase64(string p_Text,System.Text.EnCoding p_EnCoding)
{
if (p_Text.Trim().Length == 0) return "";
byte[] _ValueBytes = Convert.FromBase64String(p_Text);
return p_EnCoding.GetString(_ValueBytes);
}
#endregion


}

/// <summary>
/// 连接事件
/// </summary>
/// <param name="ar"></param>
private voID OnConnectRequest(IAsyncResult ar)
{
POP3ClIEnt _ClIEnt = (POP3ClIEnt)ar.AsyncState;
byte[] _ReadBytes =new byte[0];
_ClIEnt.ClIEnt.ClIEnt.BeginReceive(_ReadBytes,SocketFlags.None,new AsyncCallback(OnWrite),_ClIEnt);
}

/// <summary>
/// 连接事件
/// </summary>
/// <param name="ar"></param>
private voID OnSend(IAsyncResult ar)
{
POP3ClIEnt _ClIEnt = (POP3ClIEnt)ar.AsyncState;
byte[] _ReadBytes = new byte[0];
_ClIEnt.ClIEnt.ClIEnt.BeginReceive(_ReadBytes,_ClIEnt);
}

/// <summary>
/// 连接事件
/// </summary>
/// <param name="ar"></param>
private voID OnWrite(IAsyncResult ar)
{
POP3ClIEnt _ClIEnt = (POP3ClIEnt)ar.AsyncState;
byte[] _WriteBytes = new byte[_ClIEnt.ClIEnt.ClIEnt.ReceiveBufferSize];
_ClIEnt.ClIEnt.ClIEnt.Receive(_WriteBytes);
if (_ClIEnt.ReadEnd) _WriteBytes = ReadEnd(_WriteBytes,_ClIEnt);
byte[] _SendBytes = _ClIEnt.GetSendBytes(_WriteBytes);
if (_SendBytes.Length == 0) return;
_ClIEnt.ClIEnt.ClIEnt.BeginSend(_SendBytes,_SendBytes.Length,new AsyncCallback(OnSend),_ClIEnt);
}

/// <summary>
/// 获取知道获取到. 否则一直获取数据
/// </summary>
/// <param name="p_Value"></param>
/// <returns></returns>
private byte[] ReadEnd(byte[] p_Value,POP3ClIEnt p_ClIEnt)
{
if (System.Text.EnCoding.ASCII.GetString(p_Value).IndexOf("\r\n.\r\n") != -1) return p_Value;
MemoryStream _Stream = new MemoryStream();
_Stream.Write(p_Value,p_Value.Length);
while (true)
{
byte[] _WriteBytes = new byte[p_ClIEnt.ClIEnt.ReceiveBufferSize];
p_ClIEnt.ClIEnt.ClIEnt.Receive(_WriteBytes);
_Stream.Write(_WriteBytes,_WriteBytes.Length);
System.Threading.Thread.Sleep(100);
if (System.Text.EnCoding.ASCII.GetString(_WriteBytes).IndexOf("\r\n.\r\n") != -1) return _Stream.ToArray();
}
}

}
}
总结

以上是内存溢出为你收集整理的C#通过POP3获取邮件的代码(正文和附件)全部内容,希望文章能够帮你解决C#通过POP3获取邮件的代码(正文和附件)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1255300.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存