rebex

11
Login Contact About Rebex Contact Our customers News Jobs Back to tutorial list... Table of content Namespaces and assemblies POP3 basics - connecting, logging in and disconnecting Authenticating to a POP3 server Authentication using NTLM Obtaining info about the mailbox Sequence numbers and unique IDs Retrieving the message list Downloading message headers Downloading messages Deleting and undeleting messages Using events and logging communication # Namespaces and assemblies There are two assemblies which have to be reference in your project to be able to use all features of Mail for .NET described here. Rebex.Net.Pop3.dll is needed for any POP3 operations and contains the Pop3 class and others in Rebex.Net namespace. Rebex.Mail.dll contains classes that make it possible to read, create and write e-mail messages in MIME format and contains the MailMessage class in Rebex.Mail namespace and a number of classes that represent mail message headers in Rebex.Mime.Headers namespace. To gain access to all described functionality, reference the two assemblies from your project and import the following namespaces in your source files: C# using Rebex.Net; using Rebex.Mail; using Rebex.Mime.Headers; VB.NET Imports Rebex.Net Imports Rebex.Mail Imports Rebex.Mime.Headers back to top... # POP3 basics - connecting, logging in and disconnecting Typical POP3 session goes like this: Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx 2 de 12 28/03/2011 09:54 a.m.

Upload: richard-gonzalez

Post on 28-Mar-2015

105 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Rebex

Login

Contact

About RebexContactOur customersNewsJobs

Back to tutorial list...

Table of content

Namespaces and assembliesPOP3 basics - connecting, logging in and disconnectingAuthenticating to a POP3 serverAuthentication using NTLMObtaining info about the mailboxSequence numbers and unique IDsRetrieving the message listDownloading message headersDownloading messagesDeleting and undeleting messagesUsing events and logging communication

# Namespaces and assemblies

There are two assemblies which have to be reference in your project to be able to use all features of Mail for .NETdescribed here. Rebex.Net.Pop3.dll is needed for any POP3 operations and contains the Pop3 class and others inRebex.Net namespace. Rebex.Mail.dll contains classes that make it possible to read, create and write e-mailmessages in MIME format and contains the MailMessage class in Rebex.Mail namespace and a number of classesthat represent mail message headers in Rebex.Mime.Headers namespace.

To gain access to all described functionality, reference the two assemblies from your project and import the followingnamespaces in your source files:

C#

using Rebex.Net;using Rebex.Mail;using Rebex.Mime.Headers;

VB.NET

Imports Rebex.NetImports Rebex.MailImports Rebex.Mime.Headers

back to top...

# POP3 basics - connecting, logging in and disconnecting

Typical POP3 session goes like this:

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

2 de 12 28/03/2011 09:54 a.m.

Page 2: Rebex

Connect to the POP3 serverLogin - authenticate with user name and passwordWork with messages in your mailboxDisconnect

POP3 is basically a single-session and single-folder protocol. While you are connected and authenticated, you are notgoing to be informed when any new message arrives, and you only have access to messages that were available at thetime of authentication. Because of this, many POP3 servers only allow a single session for a single account at a time, sodon't forget to call Disconnect method when you are done with the mailbox, or you might experience problemsconnecting again until the previous session either expires or the Ftp object is claimed by .NET's garbage collector. Also,due to the nature of the POP3 protocol, you will need to connect periodically if you wish to check for new messages.

And now let's look at some sample code.

C#

using Rebex.Net;...

// create client and connect Pop3 client = new Pop3();client.Connect("pop3.example.org");

// authenticate client.Login("username", "password");

// work with messages //...

// disconnect client.Disconnect();

VB.NET

Imports Rebex.Net...

'create client and connect Dim client As New Pop3client.Connect("pop3.example.org")

'authenticate client.Login("username", "password")

'work with messages '...

'disconnect client.Disconnect()

back to top...

# Authenticating to a POP3 server

The POP3 protocol supports several authentication methods. Normally, you just have to supply your credentials to theLogin method. The component will automatically choose the best (most secure) authentication method available and logyou in.

Additionally, you can retrieve the list of supported authentication methods using the Pop3 object's

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

3 de 12 28/03/2011 09:54 a.m.

Page 3: Rebex

GetSupportedAuthenticationMethods method, and specify which one is to be used for login. (Or specifyPop3Authentication.Auto that will do this automatically.)

C#

using Rebex.Net;...

Pop3 client = new Pop3();client.Connect("pop3.example.org");

// authenticate - let the component choose the best method client.Login("username", "password");

// or choose one yourself // client.Login("username", "password", Pop3Authentication.Plain);

VB.NET

Imports Rebex.Net...

'create client and connect Dim client As New Pop3client.Connect("pop3.example.org")

'authenticate - let the component choose the best method client.Login("username", "password")

'or choose one yourself 'client.Login("username", "password", Pop3Authentication.Plain)

back to top...

# Authentication using NTLM

By default, the Login method won't try NTLM authentication, because it might not work correctly in some situations.However, if NTLM does work with your server, nothing stops you from using it. Just read the information on MicrosoftExchange in the FAQ first if you use that server.

C#

// create client and connect Pop3 client = new Pop3();client.Connect("pop3.example.org");

// authenticate using NTLM client.Login("domain\\username", "password", Pop3Authentication.Ntlm);

...

VB.NET

' create client and connect Dim client As New Pop3()client.Connect("pop3.example.org")

'authenticate using NTLM client.Login("domain\username", "password", SmtpAuthentication.Ntlm)

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

4 de 12 28/03/2011 09:54 a.m.

Page 4: Rebex

...

NTLM also makes it possible to authenticate as the user under whose context your application is running. This makes itpossible for the user to log in without the need to specify his or her password.

C#

// create client and connect Pop3 client = new Pop3();client.Connect("pop3.example.org");

// authenticate using NTLM client.Login(Pop3Authentication.Ntlm);

...

VB.NET

' create client and connect Dim client As New Pop3()client.Connect("pop3.example.org")

' authenticate using NTLM's single-sign-on feature client.Login(SmtpAuthentication.Ntlm)

...

back to top...

# Obtaining info about the mailbox

There are two pieces of information available - the number of messages in the mailbox can be obtained using theGetMessageCount method and the total size of them using the GetMailboxSize method.

C#

// create client, connect and log in Pop3 client = new Pop3();client.Connect("pop3.example.org");client.Login("username", "password");

Console.Write("Number of messages in the mailbox is: ");Console.Write(client.GetMessageCount());Console.WriteLine();

client.Disconnect();

VB.NET

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

Console.Write("Number of messages in the mailbox is: ")Console.Write(client.GetMessageCount())Console.WriteLine()

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

5 de 12 28/03/2011 09:54 a.m.

Page 5: Rebex

client.Disconnect()

back to top...

# Sequence numbers and unique IDs

The POP3 protocol uses two different IDs to identify messages.

ID type Description

intsequenceNumber

A number between 1..[number of messages in the POP3 mailbox]. This number doesnot change during POP3 session - even when one or more messages are deleted, theremaining messages retaing their sequence number. However, these numbers arespecific to a single session - when you disconnect and log in again later, the samesequence numbers will be assigned to different messages.

stringuniqueID

Unlike sequence number, the message unique ID is permanent and does not changebetween sessions. A message will retain its unique ID until it is deleted.

Most POP3 methods that deal with messages only accept sequenceNumber as a parameter for messageidentification. However, it is quite simple to map a given unique ID to a corresponding sequence number and vice-versa.Just retrieve the message list using use GetMessageList method, use its Find method to get info about the givenmessage and read its UniqueId or SequenceNumber properties to get the required ID.

C#

string localPath = "";

// some valid unique ID we already retrieved in past string uniqueId = "abcd13954986";

// create client, connect and log in Pop3 client = new Pop3();client.Connect("pop3.example.org");client.Login("username", "password");

// get message list Pop3MessageCollection messages = client.GetMessageList();Pop3MessageInfo info = messages.Find(uniqueId);if (info == null){ Console.WriteLine("Message not found, probably deleted?");}else { // read the sequence number int sequenceNumber = info.SequenceNumber;

// and use it to download the message client.GetMessage(sequenceNumber, localPath);}

client.Disconnect();

VB.NET

Dim localPath As String = ""

'some valid unique ID we already retrieved in past

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

6 de 12 28/03/2011 09:54 a.m.

Page 6: Rebex

Dim uniqueId As String = "abcd13954986"

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

'get message list Dim messages As Pop3MessageCollection = client.GetMessageList()Dim info As Pop3MessageInfo = messages.Find(uniqueId)If info Is Nothing Then Console.WriteLine("Message not found, probably deleted?")Else 'read the sequence number Dim sequenceNumber As Integer = info.SequenceNumber

'and use it to download the message client.GetMessage(sequenceNumber, localPath)End If

client.Disconnect()

back to top...

# Retrieving the message list

To get a list of messages in the mailbox, call the GetMessageList method. It accepts an optional parameter thatspecifies what information to retrieve from the server:

Parameter value Description

Pop3ListFields.SequenceNumber Message sequence number for current session.

Pop3ListFields.UniqueID Message unique ID that is permanent and does not changebetween sessions.

Pop3ListFields.Length Message data size in bytes.

Pop3ListFields.FastCombination of SequenceNumber, UniqueId and Length. Thisis the default for GetMessageList method if no fieldsargumentis specified.

Pop3ListFields.FullHeaders

Same as Fast, but also downloads the message headers of eachmessage as Date, From, To, Subject or Message ID fields. Thisvariant is the most verbose, but also the slowest. See the nextsection for more discussion about this.

These fields are bit flags, which means that combinations of SequenceNumber|Length and UniqueId|Length arealso possible - use bitwise or operator for this.

The following code shows how to download a message list and show a unique ID and From/Subject headers of eachmessage:

C#

// create client, connect and log in Pop3 client = new Pop3();client.Connect("pop3.example.org");client.Login("username", "password");

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

7 de 12 28/03/2011 09:54 a.m.

Page 7: Rebex

// get message list - full headers Pop3MessageCollection messages = client.GetMessageList(Pop3ListFields.FullHeaders);

// display info about each message Console.WriteLine("UID | From | To | Subject");foreach (Pop3MessageInfo message in messages){ Console.WriteLine ( "{0} | {1} | {2} | {3}", message.UniqueId, message.From, message.To, message.Subject );}

client.Disconnect();

VB.NET

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

'get message list - full headers Dim messages As New Pop3MessageCollectionmessages = client.GetMessageList(Pop3ListFields.FullHeaders)

'display info about each message Console.WriteLine("UID | From | To | Subject")Dim message As Pop3MessageInfoFor Each message In messages Console.WriteLine( _ "{0} | {1} | {2} | {3}", _ message.UniqueId, _ message.From, _ message.To, _ message.Subject)Next

client.Disconnect()

back to top...

# Downloading message headers

The simplest method for downloading all message headers is to call GetMessageList with parameterPop3ListFields.FullHeaders, as described in the Retrieving the message list tutorial. It retrieves headers for allmessages in the mailbox.

However, as mentioned earlier, this might take a very long time if there are too many messages in the mailbox or theconnection bandwidth is limited. If this is the case, it is advisable to only ask for the message list with the IDs and length(Pop3ListFields.Fast) and retrieve message headers of each message separately using the GetMessageInfomethod - and this can even be done later or only when needed.

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

8 de 12 28/03/2011 09:54 a.m.

Page 8: Rebex

C#

// create client, connect and log in Pop3 client = new Pop3();client.Connect("pop3.example.org");client.Login("username", "password");

int sequenceNumber = 1; // the first message

Pop3MessageInfo info = client.GetMessageInfo( sequenceNumber, Pop3ListFields.FullHeaders);

Console.Write("Date: " + info.Date);Console.Write("From: " + info.From);Console.Write("Subject: " + info.Subject);

client.Disconnect();

VB.NET

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

Dim sequenceNumber As Integer = 1 'the first message

Dim info As Pop3MessageInfo = client.GetMessageInfo( _ sequenceNumber, _ Pop3ListFields.FullHeaders)

Console.Write("Date: " & info.Date.ToString())Console.Write("From: " & info.From.ToString())Console.Write("Subject: " & info.Subject)

client.Disconnect()

back to top...

# Downloading messages

Finally, let's start downloading some messages! It is very simple - just call the GetMailMessage method and youretrieve an instance of the MailMessage class that contains the message corresponding to the supplied sequencenumber. You can read message headers, body and attachments from it, modify it, save it to disk or send it again usingour Smtp class. For more info about this, check out our MailMessage class tutorial.

Alternatively, if all you need is to download the message data and save it to disk or write it into a stream, and you don'tneed to access the message content in any way at the moment, just call the GetMessage method instead. This won'treturn an instance of MailMessage and just writes the message data into the supplied local path or stream.

C#

// create client, connect and log in Pop3 client = new Pop3();client.Connect("pop3.example.org");client.Login("username", "password");

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

9 de 12 28/03/2011 09:54 a.m.

Page 9: Rebex

// get message list Pop3MessageCollection list = client.GetMessageList();

if (list.Count == 0){ Console.WriteLine("There are no messages in the mailbox.");}else { // download the first message MailMessage message = client.GetMailMessage(list[0].SequenceNumber); //... }

client.Disconnect();

VB.NET

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

'get message list Dim list As Pop3MessageCollection = client.GetMessageList()

If list.Count = 0 Then Console.WriteLine("There are no messages in the mailbox.")Else 'download the first message Dim message As MailMessage = client.GetMailMessage(list(0).SequenceNumber) '... End If

client.Disconnect()

back to top...

# Deleting and undeleting messages

Deleting messages in POP3 is quite straightforward, but might seem a bit awkward at first. To delete a message, callthe Delete method with message sequence number as an argument.

The Delete method marks a message as deleted. These won't appear in subsequent message lists, but will actuallyonly be removed from the mailbox after a call to Disconnect method. You can "undelete" messages that were not yetremoved using one of the following methods:

Calling Undelete method. This recovers messages marked as deleted. It will appear in message lists again andwon't be removed when the session ends.Calling Disconnect(true). This will undelete all deleted messages and disconnect from the server. No deletedmessages will be removed, and the next time you connect to this mailbox, they will be there again. CallingDisconnect() without parameter will commit all changes and remove all messages marked as deleted.

C#

// create client, connect and log in Pop3 client = new Pop3();

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

10 de 12 28/03/2011 09:54 a.m.

Page 10: Rebex

client.Connect("pop3.example.org");client.Login("username", "password");

int sequenceNumber = 1;

// delete the first message client.Delete(sequenceNumber);

// undo the delete operation client.Undelete();

// and delete it again client.Delete(sequenceNumber);

// commit changes and disconnect client.Disconnect();

VB.NET

'create client, connect and log in Dim client As New Pop3client.Connect("pop3.example.org")client.Login("username", "password")

Dim sequenceNumber As Integer = 1

'delete the first message client.Delete(sequenceNumber)

'undo the delete operation client.Undelete()

'and delete it again client.Delete(sequenceNumber)

'commit changes and disconnect client.Disconnect()

back to top...

# Using events and logging communication

In case something goes wrong, it is very useful to have a log of commands sent to the server and responses receivedfrom it for diagnostics purposes. To make this possible, the Pop3 class declares the following events:

Event name Description

CommandSent Occurs when a command (e.g. CAPA or RETR) is sent to the server.

ResponseRead Occurs when response is received from the server.

StateChangedOccurs when the session state changes, such as from Disconnected to Ready, fromReady to Sending or from Sending to Reading.

TransferProgress Occurs when a block of message data is received from the server.

The CommandSent or ResponseRead events are particularly useful for the purpose of generating a communication logand the TransferProgress event can be used by a GUI application to display amount of transfered data or a progress

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

11 de 12 28/03/2011 09:54 a.m.

Page 11: Rebex

bar.

C#

Pop3 client = new Pop3();client.CommandSent += new Pop3CommandSentEventHandler(client_CommandSent);client.ResponseRead += new Pop3ResponseReadEventHandler(client_ResponseRead);client.Connect("pop3.example.org");

...

private void client_CommandSent(object sender, Pop3CommandSentEventArgs e){ Console.WriteLine("Command: {0}", e.Command);}

private void client_ResponseRead(object sender, Pop3ResponseReadEventArgs e){ Console.WriteLine("Response: {0}", e.Response);}

VB.NET

Dim client As New Pop3AddHandler client.CommandSent, AddressOf client_CommandSentAddHandler client.ResponseRead, AddressOf client_ResponseReadclient.Connect("pop3.example.org")

...

Public Sub client_CommandSent(ByVal sender As Object, ByVal e As _Pop3CommandSentEventArgs) Console.WriteLine("Command: {0}", e.Command)End Sub

Public Sub client_ResponseRead(ByVal sender As Object, ByVal e As _Pop3ResponseReadEventArgs) Console.WriteLine("Response: {0}", e.Response)End Sub

back to top...

Back to tutorial list...

Rebex.NET: POP3 Tutorial http://www.rebex.net/mail.net/tutorial-pop3.aspx

12 de 12 28/03/2011 09:54 a.m.