C # sending and receiving (POP3, IMAP, SMTP)

Source: Internet
Author: User
Tags getstream imap mailmessage smtpclient

Content of this article:
1: Make your own Pop3Helper
Handling of mail formats is troublesome
2: Use the off-the-shelf pop3 class
LumiSoft. Net. POP3.Client;
There are two solutions
3: Use IMAP to receive emails
More functions than pop3.
4: send an email through SMTP
About Mailbox unavailable. The server response was: 5.7.1 Unable to relay for xx error handling

Writing a POP3 receiving program is not very easy. The main problem is how to handle the mail format.
The processing method is not too complicated. You can use a tcp connection.
This is the code
Public class Pop3Helper
{
String _ pop3server;
String _ user;
Int _ port;
String _ pwd;

Public TcpClient _ server;
Public NetworkStream _ netStream;
Public StreamReader _ reader;
Public string _ data;
Public byte [] _ charData;
Public string _ CRLF = "\ r \ n ";

Private string _ log;
Public string LogMSG
{
Get {return _ log ;}
}
/// <Summary>
///
/// </Summary>
/// <Param name = "server"> </param>
/// <Param name = "port"> </param>
/// <Param name = "user"> </param>
/// <Param name = "pwd"> </param>
Public Pop3Helper (string server, int port, string user, string pwd)
{
_ Pop3server = server;
_ Port = port;
_ User = user;
_ Pwd = pwd;
}
/// <Summary>
/// Connect
/// </Summary>
Public void Connect ()
{
// Create a tcp connection
_ Server = new TcpClient (_ pop3server, _ port );

// Prepare
_ NetStream = _ server. GetStream ();
_ Reader = new StreamReader (_ server. GetStream ());
If (! CheckResult (_ reader. ReadLine ()))
Throw new Exception ("Connect Error ");

// Login
_ Data = "USER" + this. _ user + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );
If (! CheckResult (_ reader. ReadLine ()))
Throw new Exception ("User Error ");

_ Data = "PASS" + this. _ pwd + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );
If (! CheckResult (_ reader. ReadLine ()))
Throw new Exception ("Pass Error ");

}
/// <Summary>
/// Get message Numbers
/// </Summary>
/// <Returns> </returns>
Public int GetMailCount ()
{
Try
{
_ Data = "STAT" + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );
String resp = _ reader. ReadLine ();
String [] tokens = resp. Split (new char [] {''});
Return Convert. ToInt32 (tokens [1]);
}
Catch (Exception ex)
{
Return 0;
}
}

Public string GetMail (int id)
{
String line;
String content = "";
Try
{
// Get by id
_ Data = "RETR" + id + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );
Line = _ reader. ReadLine ();

If (line [0]! = '-')
{
// End '.'
While (line! = ".")
{
Line = _ reader. ReadLine ();
Content + = line + "\ r \ n ";
}
}

Return content;

}

Catch (Exception err)
{
Log (err. Message );
Return "Error ";
}
}
Public void DeleteMail (int id)
{
_ Data = "DELE" + id + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );
If (! CheckResult (_ reader. ReadLine ()))
Throw new Exception ("Delete Error ");

}
/// <Summary>
/// Close connection
/// </Summary>
Public void Close ()
{

_ Data = "QUIT" + _ CRLF;
_ CharData = System. Text. Encoding. ASCII. GetBytes (_ data. ToCharArray ());
_ NetStream. Write (_ charData, 0, _ charData. Length );

// Close
_ NetStream. Close ();
_ Reader. Close ();
}

Private bool CheckResult (string reply)
{
Log (reply );
If (reply. IndexOf ("+ OK")>-1)
Return true;
Else
Return false;
}
Private void Log (string msg)
{
_ Log + = msg + "\ r \ n ";
}
}
.....
However, a problem with this method is about parsing the mail format. If it is an attachment, it also provides binary directly, which is not easy to use.
Therefore, you can use a ready-made tool: LumiSoft. Net. POP3.Client. The implementation has been written here, and it is easy to use.
This is a simple usage (two processing methods are used here, and the former is not recommended)
..
Using (POP3_Client pop3 = new POP3_Client ())
{
// Establish a connection with the Pop3 server
Pop3.Connect (_ popServer, _ pop3port, false );
// Verify your identity
Pop3.Authenticate (_ user, _ pwd, false );

// Get all messages
POP3_MessagesInfo infos = pop3.GetMessagesInfo ();
Foreach (POP3_MessageInfo info in infos)
{
Byte [] bytes = pop3.GetMessage (info. MessageNumber );
Mime mime = Mime. Parse (bytes );
HandleMail (mime );
// Delete it at last
// Pop3.DeleteMessage (info. MessageNumber );
}
// The second way to do it
// For (int I = 0; I <pop3.Messages. Count; I ++)
//{
// Byte [] bytes = pop3.Messages [I]. MessageToByte ();
// Mime = mime. Parse (bytes );
// HandleMail (mime );
/// Delete it at last
/// Pop3.DeleteMessage (pop3.Messages [I]. SequenceNumber );
//}.
...
The obtained email can be obtained here.
# Region pop3
// String customer = mime. MainEntity. To. ToAddressListString (); // cargo company
// String sender = mime. MainEntity. From. ToAddressListString (); // this is customer who send

# Endregion
String customer = MailboxesToString (envelope. To); // cargo company
String sender = MailboxesToString (envelope. From); // this is customer who send

...
In addition, it provides another tool, IMAP, which is more convenient to operate. The Code is as follows:
.
IMAP_Client clnt = new IMAP_Client ();
Try
{
Clnt. Connect ("maid", 143, false );
Clnt. Authenticate ("user", "password ");
String [] folders = clnt. GetFolders (); // get all types

String folder = "Inbox ";
Clnt. SelectFolder (folder );

IMAP_SequenceSet sequence_set = new IMAP_SequenceSet ();
// All messages
Sequence_set.Parse (string. Format ("{0 }:{ 1}", 1, clnt. MessagesCount ));

IMAP_FetchItem [] fetchItems = clnt. FetchMessages (
Sequence_set,
IMAP_FetchItem_Flags.UID | IMAP_FetchItem_Flags.MessageFlags | IMAP_FetchItem_Flags.Size | IMAP_FetchItem_Flags.Envelope,
True, false
);
// Int count = 0;
Foreach (IMAP_FetchItem fetchItem in fetchItems)
{
IMAP_Envelope envelope = fetchItem. Envelope;
// Hanldle it, means read and search and reply
Try
{
HandleMail (envelope );
// Count ++;
}
Catch (Exception ex)
{
Log ("Sys", ex. Message );
}
}
// Delete it after hanlde
Clnt. DeleteMessages (sequence_set, false );
// Disconnect
Clnt. Disconnect ();

// MessageBox. Show (count. ToString () + "of" + fetchItems. Length + "Success ");
}
Catch (Exception x)
{
Log ("Sys", x. Message );
// MessageBox. Show (x. Message );
}
 
..
How to receive emails.
It is relatively easy to send emails. Two methods are provided here.
The first method is to use smtp on the Internet. In this way, the user name and password must be provided. This is suitable for web applications. The smtp used is also online. I generally use 163 smtp, which is basically no problem.
The second method is to use local smtp. No Password is required, or the user does not exist (is this the case with spam ?), However, you must provide the smtp port number.
The second method sometimes reports the error "Mailbox unavailable. the server response was: 5.7.1 Unable to relay for xxx ", after checking The information (not found on baidu, or a little more google information ), it turns out that the SMTP service configuration in IIS is incorrect.
To solve this problem, go to the SMTP properties-> Access page Reply Restrictions/Reply-Only this Below option, and add your own ip Address: 127.0.0.1 (allow local machines to use loalhost, if other machines are allowed, similar settings)
The Code is as follows:
Public class EMail
{
Static public string accountName;
Static public string password;
Static public string smtpServer;
Static public int smtpPort;

/// <Summary>
/// Need password, username, smtpserver
/// </Summary>
/// <Param name = "to"> </param>
/// <Param name = "subject"> </param>
/// <Param name = "body"> </param>
Static public void SendMail (string sendTo, string subject, string body)
{
//. Net smtp
System. Web. Mail. MailMessage mailmsg = new System. Web. Mail. MailMessage ();
Mailmsg. To = sendTo;
// Mailmsg. Cc = cc;
Mailmsg. Subject = subject;
Mailmsg. Body = body;

// Sender here
Mailmsg. From = EMail. accountName;
// Certify needed
Mailmsg. Fields. Add ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); // 1 is to cer.pdf
// The user id
Mailmsg. Fields. Add (
"Http://schemas.microsoft.com/cdo/configuration/sendusername ",
EMail. accountName );
// The password
Mailmsg. Fields. Add (
"Http://schemas.microsoft.com/cdo/configuration/sendpassword ",
EMail. password );

System. Web. Mail. SmtpMail. SmtpServer = EMail. smtpServer;
System. Web. Mail. SmtpMail. Send (mailmsg );

}

# Region send mail2
/// <Summary>
/// Need username, smtp, smtp port
/// </Summary>
/// <Param name = "sendTo"> </param>
/// <Param name = "subject"> </param>
/// <Param name = "body"> </param>
Static public void SendMail2 (string sendTo, string subject, string body)
{
System. Net. Mail. MailMessage msg = new System. Net. Mail. MailMessage ();
Msg. To. Add (sendTo );
Msg. From = new System. Net. Mail. MailAddress (accountName );

Msg. Subject = subject;
Msg. SubjectEncoding = System. Text. Encoding. UTF8;
Msg. Body = body ;//
Msg. BodyEncoding = System. Text. Encoding. UTF8;
Msg. IsBodyHtml = false;
// Msg. Priority = MailPriority. High ;//

System. Net. Mail. SmtpClient client = new System. Net. Mail. SmtpClient ();
Client. Host = smtpServer;
Client. Port = smtpPort;
// Client. Credentials = new System. Net. NetworkCredential ("user@xxx.com", "pass ");
Client. Send (msg );

}
# Endregion

}

 

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.