C # obtain the email code (body and attachment) through POP3)

Source: Internet
Author: User

Usage:
Get 1st emails CopyCode The Code is as follows: zgke. net. POP3 _ popt = new zgke. net. POP3 ("192.168.0.1", 110 );
Datatable _ mail = _ popt. getmail ("zk", "zk", 1 );

The returned datatable data content is
Type is type text is text, if the attachment is byte [] Name, if the attachment is stored as the file name

Below are all classesCopy codeThe Code is 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>
/// Obtain mail class
// 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>
/// Obtain the mail list
/// </Summary>
/// <Param name = "p_name"> User Name </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>
/// Obtain the email content
/// </Summary>
/// <Param name = "p_name"> name </param>
/// <Param name = "p_password"> password </param>
/// <Param name = "p_mailindex"> email no. </param>
/// <Returns> dataset </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 ("");
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>
/// Obtain the command required for the next login to obtain the 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 ("\ 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 (@"(? <= :).*? (\ 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 the character set in the 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
/// <Summary>
/// Obtain the text subject
/// </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 ");
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 ");
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 ");
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>
/// Obtain the type (regular)
/// </Summary>
/// <Param name = "p_mail"> original text </param>
/// <Param name = "p_typetext"> prefix text </param>
/// <Param name = "p_end"> end text </param>
/// <Returns> matched 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 Encoding
/// </Summary>
/// <Param name = "p_text"> original text </param>
/// <Param name = "p_encoding"> encoding method </param>
/// <Returns> post-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>
/// Decodes 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 event
/// </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 );
}

///


// connection event
///
///
private void onsend (iasyncresult AR)
{< br> pop3client _ client = (pop3client) ar. asyncstate;
byte [] _ readbytes = new byte [0];
_ client. client. client. beginreceive (_ readbytes, 0, 0, socketflags. none, new asynccallback (onwrite), _ client);
}

///


// connection event
///
///
private void onwrite (iasyncresult AR)
{< br> 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>
/// Obtain the data. Otherwise, the data is always obtained.
/// </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 ();
}
}

}
}

Related Article

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.