e-mail processing in C # (POP3,IMAP,SMTP)

Source: Internet
Author: User
Tags getstream imap readline mailmessage smtpclient
Source: Whim-Blog Park
What this article covers:
1: Own making Pop3helper
The handling of the letter format has trouble
2: Use the ready-made POP3 class
LumiSoft.Net.POP3.Client;
There are two ways of handling
3: Use IMAP to receive mail
Function seems more, than POP3 to come.
4:smtp Send mail
About Mailbox unavailable. The server response was:5.7.1 unable to relay error handling for XX

It's not easy to write your own POP3 receive program. The main problem is how to deal with the format of the letter.
The processing method is not too complex, a TCP join is OK.
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;}
}
///
///
///
///
///
///
///
Public Pop3helper (string server, int port, string user, string pwd)
{
_pop3server = server;
_port = port;
_user = user;
_pwd = pwd;
}
///
Connect
///
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");

}
///
Get Message Numbers
///
///
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 With '. '
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");

}
///
Close connection
///
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";
}
}
。。。。。
But one problem with this approach is the format for parsing letters. If it is an attachment, he also gives a direct binary, not easy to use.

So, you can use a ready-made tool: LumiSoft.Net.POP3.Client. This has been written to achieve, it is also very simple to use.
This is a simple usage (two methods are used here, the first one is not recommended)
。。
using (pop3_client POP3 = new Pop3_client ())
{
Establishing a connection with the POP3 server
POP3. Connect (_popserver, _pop3port,false);
Verify 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 = mime.parse (bytes);
Handlemail (MIME);
Delete it at last
POP3. Deletemessage (POP3. Messages[i]. SequenceNumber);
}。
。。。
Get the mail that you want to get.
#region POP3
String customer = Mime. MainEntity.To.ToAddressListString (); Cargo company
String sender = Mime. MainEntity.From.ToAddressListString (); This is the customer who send
#endregion
String customer = mailboxestostring (envelope. To); Cargo company
String sender = Mailboxestostring (envelope. from); This is the customer who send
。。。
In addition, the other tool it provides is IMAP, which is more convenient to operate. The code is as follows:

Imap_client clnt = new Imap_client ();
Try
{
Clnt. Connect ("mail.xx.com", 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);
}

。。
Above all is how to receive mail.
It is easy to learn about how to send a message. There are two different ways to do this.
The first way is to use SMTP on the Web. The user name and password must be supplied in this manner. This is suitable for Web applications, the use of SMTP is also online, I generally use 163 of SMTP, basically no problem.
The second way is to use local SMTP. There is no need to provide a password, the user can also be non-existent (spam is not the result of this.) , but it is necessary to provide the SMTP port number.

The second method tests sometimes the error "Mailbox unavailable." The server response was:5.7.1 unable to relay for XXX, after checking the data (not found in Baidu, or Google information a little more), only to find that the problem is IIS in the configuration of the SMTP service is problematic.
This modification resolves: to the Open SMTP Property->access page reply restrictions/reply-only this below option, Add your own ip:127.0.0.1 (allow native, use loalhost, if it is allowed to other machines, 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;

///
Need Password,username, SmtpServer
///
///
///
///
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 certify
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
///
Need USERNAME,SMTP,SMTP Port
///
///
///
///
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
}

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.