C # get mail code (body and attachments) through POP3-practical tips

Source: Internet
Author: User
Tags base64 mail code
How to use:
Get 1th Message
Copy Code code as follows:

Zgke.Net.POP3 _popt = new Zgke.Net.POP3 ("192.168.0.1", 110);
DataTable _mail = _popt.getmail ("ZK", "ZK", 1);

Returns the contents of the DataTable data as
Type is typed as text if the attachment is byte[] name if the file name is stored in the attachment

Here are all the classes
Copy Code code as follows:

Using System;
Using System.Net.Sockets;
Using System.Net;
Using System.Security.Cryptography;
Using System.IO;
Using System.Data;

Namespace Zgke.net
{

<summary>
Get the class of the message
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>
Get mail List
</summary>
<param name= "P_name" > Username </param>
<param name= "P_password" > Password </param>
<returns>mail Information </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 ("error message!" + _client.error);
return _client.maildatatable;
}


<summary>
Get message Content
</summary>
<param name= "P_name" > Name </param>
<param name= "P_password" > Password </param>
<param name= "P_mailindex" > Message number </param>
<returns> Data Set </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, M_port, New AsyncCallback (Onconnectrequest), _client);
while (!_client.returnend)
{
System.Windows.Forms.Application.DoEvents ();
}
if (_client.error.length!= 0) throw new Exception ("error message!" + _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>
Get the next command required to log on to the Get list
</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 ("", "");
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>
Convert character Set in text
</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 Get message body and attachments
<summary>
Get text body
</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\ncontent-type:", "\ 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, "\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/plain", _returntext});
Break
Case "multipart/alternative;":
_boundary = Gettexttype (P_mail, "boundary=\", "\"). Replace ("\", "");
_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, "boundary=\", "\"). Replace ("\", "");
_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
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\ncontent-transfer-encoding:", "\ r \ n"). Trim ();
string _name = Gettexttype (P_mail, "filename=\", "\"). Replace ("\", "");
_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>
Get Type (Regular)
</summary>
<param name= "P_mail" > Original text </param>
<param name= "P_typetext" > Pre-text </param>
<param name= "P_end" > End text </param>
<returns> Compliance Records </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 Code Access Code
</summary>
<param name= "P_text" > Original text </param>
<param name= "p_encoding" > Coding mode </param>
<returns> after-code information </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>
Decoding 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>
Connection Events
</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, 0, 0, Socketflags.none, new AsyncCallback (Onwrite), _Client);
}

<summary>
Connection Events
</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, 0, 0, Socketflags.none, new AsyncCallback (Onwrite), _Client);
}

<summary>
Connection Events
</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, 0, _sendbytes.length, Socketflags.none, New AsyncCallback (OnSend), _ Client);
}

<summary>
Get to know get to. Otherwise get the data all the time
</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, 0, p_value.length);
while (true)
{
byte[] _writebytes = new Byte[p_client.client.receivebuffersize];
P_Client.Client.Client.Receive (_writebytes);
_stream.write (_writebytes, 0, _writebytes.length);
System.Threading.Thread.Sleep (100);
if (System.Text.Encoding.ASCII.GetString (_writebytes). IndexOf ("\r\n.\r\n")!=-1) return _stream.toarray ();
}
}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.