C # receive emails

Source: Internet
Author: User
Tags getstream

//////////////////////////////////////// /////

// Class Name: POP3 //

// Function: receive email //

//////////////////////////////////////// /////

Using system;
Using system. net. Sockets;
Using system. net;
Using system. Security. cryptography;
Using system. IO;

Namespace ztsx. Email
{
/// <Summary>
/// Summary of POP3.
/// </Summary>
Public class POP3
{
Private string mstrhost = NULL; // host name or IP address
Private int mintport = 110; // host port number (110 by default)
Private tcpclient mtcpclient = NULL; // Client
Private networkstream mnetstream = NULL; // basic network data stream
Private streamreader m_stmreader = NULL; // read byte streams
Private string mstrstatmessage = NULL; // The message obtained after the STAT command is executed (the number of mails obtained)

/// <Summary>
/// Constructor
/// </Summary>
/// <Remarks> one email recipient </remarks>
Public POP3 ()
{
}

/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "host"> host name or IP address </param>
Public POP3 (string host)
{
Mstrhost = host;
}

/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "host"> host name or IP address </param>
/// <Param name = "Port"> host port number </param>
/// <Remarks> one email recipient </remarks>
Public POP3 (string host, int port)
{
Mstrhost = host;
Mintport = port;
}

# Region attributes

/// <Summary>
/// Host name or IP address
/// </Summary>
/// <Remarks> host name or IP address </remarks>
Public String hostname
{
Get {return mstrhost ;}
Set {mstrhost = value ;}
}

/// <Summary>
/// Host port number
/// </Summary>
/// <Remarks> host port number </remarks>
Public int Port
{
Get {return mintport ;}
Set {mintport = value ;}
}

# Endregion

# Region private Method

/// <Summary>
/// Write data to the basic data stream accessed by the Network (send the command code)
/// </Summary>
/// <Param name = "netstream"> basic data streams that can be used for network access </param>
/// <Param name = "command"> command line </param>
/// <Remarks> write data (send a command code) to the basic data stream accessed by the Network </remarks>
Private void writetonetstream (ref networkstream netstream, string command)
{
String strtosend = command + "/R/N ";
Byte [] arraytosend = system. Text. encoding. ASCII. getbytes (strtosend. tochararray ());
Netstream. Write (arraytosend, 0, arraytosend. Length );
}

/// <Summary>
/// Check whether the command line result is correct
/// </Summary>
/// <Param name = "message"> command line execution result </param>
/// <Param name = "check"> correct flag </param>
/// <Returns>
/// Type: Boolean
/// Content: True indicates no error. False indicates an error.
/// </Returns>
/// <Remarks> check whether the command line result is incorrect </remarks>
Private bool checkcorrect (string message, string check)
{
If (message. indexof (check) =-1)
Return false;
Else
Return true;
}

/// <Summary>
/// Number of unread mails in the mailbox
/// </Summary>
/// <Param name = "message"> result after the LIST command is executed </param>
/// <Returns>
/// Type: integer
/// Content: Number of unread mails in the mailbox
/// </Returns>
/// <Remarks> Number of unread emails in the mailbox </remarks>
Private int getmailnumber (string message)
{
String [] strmessage = message. Split ('');
Return int32.parse (strmessage [1]);
}

/// <Summary>
/// Get the decoded email content
/// </Summary>
/// <Param name = "encodingcontent"> content of the email before decoding </param>
/// <Returns>
/// Type: String
/// Content: the decoded email content
/// </Returns>
/// <Remarks> get the decoded email content </remarks>
Private string getdecodemailcontent (string encodingcontent)
{
String strcontent = encodingcontent. Trim ();
String strencode = NULL;

Int istart = strcontent. indexof ("base64 ");
If (istart =-1)
Throw new pop3exception ("the email content is not base64 encoded. Please check ");
Else
{
Strencode = strcontent. substring (istart + 6, strcontent. Length-istart-6 );
Try
{
Return Sx. encode. transformtostring (strencode );
}
Catch (sx. encodeexception exc)
{
Throw new pop3exception (EXC. Message );
}
}
}

# Endregion

/// <Summary>
/// Establish a connection with the host
/// </Summary>
/// <Returns>
/// Type: Boolean
/// Content: Connection result (true indicates that the connection is successful, and false indicates that the connection fails)
/// </Returns>
/// <Remarks> establish a connection with the host </remarks>
Public bool connect ()
{
If (mstrhost = NULL)
Throw new exception ("Please provide the SMTP host name or IP address! ");
If (mintport = 0)
Throw new exception ("Please provide the SMTP host port number ");
Try
{
Mtcpclient = new tcpclient (mstrhost, mintport );
Mnetstream = mtcpclient. getstream ();
M_stmreader = new streamreader (mtcpclient. getstream ());

String strmessage = m_javasreader.readline ();
If (checkcorrect (strmessage, "+ OK") = true)
Return true;
Else
Return false;
}
Catch (socketexception exc)
{
Throw new pop3exception (EXC. tostring ());
}
Catch (nullreferenceexception exc)
{
Throw new pop3exception (EXC. tostring ());
}
}

# Region POP3 command

/// <Summary>
/// Execute the POP3 command and check the execution result
/// </Summary>
/// <Param name = "command"> POP3 command line </param>
/// <Returns>
/// Type: String
/// Content: the result of executing the POP3 command
/// </Returns>
Private string executecommand (string command)
{
String strmessage = NULL; // The message returned after the POP3 command is executed

Try
{
// Send command
Writetonetstream (ref mnetstream, command );

// Read multiple rows
If (command. substring (0, 4 ). equals ("list") | command. substring (0, 4 ). equals ("retr") | command. substring (0, 4 ). equals ("UIDL") // record the message after Stat (including the number of mails)
{
Strmessage = readmultiline ();

If (command. Equals ("list") // record the message after the list (including the number of mails)
Mstrstatmessage = strmessage;
}
// Read a single row
Else
Strmessage = m_inclureader.readline ();

// Determine whether the execution result is correct
If (checkcorrect (strmessage, "+ OK "))
Return strmessage;
Else
Return "error ";
}
Catch (ioexception exc)
{
Throw new pop3exception (EXC. tostring ());
}
}

/// <Summary>
/// In the POP3 command, the results of the list, RETR, and UIDL commands must return multiple lines ending with the dot,
/// If you want to get the correct result, you must read multiple rows.
/// </Summary>
/// <Returns>
/// Type: String
/// Content: the result after executing the POP3 command
/// </Returns>
Private string readmultiline ()
{
String strmessage = m_javasreader.readline ();
String strtemp = NULL;
While (strmessage! = ".")
{
Strtemp = strtemp + strmessage;
Strmessage = m_inclureader.readline ();
}
Return strtemp;
}

// USER command
Private string user (string user)
{
Return executecommand ("user" + User) + "/R/N ";
}

// PASS Command
Private string pass (string password)
{
Return executecommand ("pass" + password) + "/R/N ";
}

// LIST Command
Private string list ()
{
Return executecommand ("list") + "/R/N ";
}

// UIDL Command
Private string UIDL ()
{
Return executecommand ("UIDL") + "/R/N ";
}

// Noop command
Private string Noop ()
{
Return executecommand ("Noop") + "/R/N ";
}

// STAT command
Private string Stat ()
{
Return executecommand ("stat") + "/R/N ";
}

// RETR command
Private string RETR (INT number)
{
Return executecommand ("retr" + number. tostring () + "/R/N ";
}

// DELE Command
Private string DELE (INT number)
{
Return executecommand ("DELE" + number. tostring () + "/R/N ";
}

// Quit command
Private void quit ()
{
Writetonetstream (ref mnetstream, "quit ");
}

/// <Summary>
/// Receive email
/// </Summary>
/// <Param name = "user"> User Name </param>
/// <Param name = "password"> password </param>
/// <Returns>
/// Type: String Array
/// Content: the email content before Decoding
/// </Returns>
Private string [] receivemail (string user, string password)
{
Int imailnumber = 0; // Number of mails

If (user (User). Equals ("error "))
Throw new pop3exception ("incorrect user name! ");
If (Pass (password). Equals ("error "))
Throw new pop3exception ("the user password is incorrect! ");
If (STAT (). Equals ("error "))
Throw new pop3exception ("An error occurred while preparing to receive the email! ");
If (List (). Equals ("error "))
Throw new pop3exception ("an error occurred when obtaining the mail list! ");

Try
{
Imailnumber = getmailnumber (mstrstatmessage );

// No new email
If (imailnumber = 0)
Return NULL;
Else
{
String [] strmailcontent = new string [imailnumber];

For (INT I = 1; I <= imailnumber; I ++)
{
// Read the email content
Strmailcontent [I-1] = getdecodemailcontent (RETR (I ));
}
Return strmailcontent;
}
}
Catch (pop3exception exc)
{
Throw new pop3exception (EXC. tostring ());
}
}

# Endregion

/// <Summary>
/// Receive email
/// </Summary>
/// <Param name = "user"> User Name </param>
/// <Param name = "password"> password </param>
/// <Returns>
/// Type: String Array
/// Content: the email content before Decoding
/// </Returns>
/// <Remarks> receive unread emails from the mailbox </remarks>
Public String [] receive (string user, string password)
{
Try
{
Return receivemail (user, password );
}
Catch (pop3exception exc)
{
Throw new pop3exception (EXC. tostring ());
}
}

/// <Summary>
/// Disconnect all sessions with the server
/// </Summary>
/// <Remarks> disconnect all sessions with the server </remarks>
Public void disconnect ()
{
Try
{
Quit ();
If (m_stmreader! = NULL)
M_inclureader.close ();
If (mnetstream! = NULL)
Mnetstream. Close ();
If (mtcpclient! = NULL)
Mtcpclient. Close ();
}
Catch (socketexception exc)
{
Throw new pop3exception (EXC. tostring ());
}
}

/// <Summary>
/// Delete the email
/// </Summary>
/// <Param name = "Number"> email number </param>
Public void deletemail (INT number)
{
// Delete the email
Int imailnumber = Number + 1;
If (DELE (imailnumber). Equals ("error "))
Throw new pop3exception ("delete th" + imailnumber. tostring () + "error! ");
}

}
}

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.