A POP3 Client in C# .NET - Code Project

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

8,139,817 members and growing!

(38,758 online)

Rupak Gupta

112

Sign out

Home

Articles

Quick Answers

Discussions

Learning Zones

Features

Help!

The Lounge

Search

General Programming Internet / Network Email

A POP3 Client in C# .NET


By Desmond McCarter | 10 Feb 2004
.NET1.0 Win2K C # Dev Intermediate

Licence First Posted Views Downloads Bookmarked

C POL 10 Feb 2004 614,006 9,407 278 times

See Also
More like this More by this author

A POP3 client in C# .NET for reading and processing emails (including attachments).
Article Browse Code Stats Revisions
4.81 (147 votes) 354

Sponsored Links
MX-Frame Business Application Framework www.mxframe.net Search for ASP.NET Add search engine functionality to your ASP.NET web site. Features... keyoti.com

Download source files - 12.6 Kb Download demo project - 15.8 Kb

Introduction
I was asked some time ago to develop software which involved extracting bodies and subject lines from emails. "Humm ...", I thought, "connect to mail server on 110, send POP3 commands, receive data, sorted!". Indeed, at my first attempt it was a piece of cake: reading emails - no problem. Colleagues working at my company were evangelizing about what we could do: "Yeah mate, we can automatically process emails, no sweat". Clients would then ask more questions: "can we send it in rich text or HTML?". "Yeah, sure we can!!". "What about processing them automatically?". "Hey - you're talking to the email kings!!". "What about processing multiple attachments, WAV's MP3's JPEG's?". "Ermmm ... can I get back to you on that ...". Wasn't as easy as I'd thought ... The reason why I found it quite difficult to code initially was mainly due to how MIME is written and how extremely ugly it can look at first glance. Here's a sample, which contains two multipart blocks (I'll explain this later):
C ollapse | C opy C ode

Received: by Mailserver id 01C3EFF7.990BBDF0@TEST; Tue, 11 Feb 2003 17:02:00 -0000 Message-ID: 2CB86919E23ED51191840060080C3DAE02320B76@MAILSERVER From: Desmond McCarter To: testemail Subject: FW: my subject Date: Tue, 11 May 2003 17:01:59 -0000 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----_=_NextPart_000_01C3EFF7.990BD65A"
C ollapse | C opy C ode

This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_000_01C3EFF7.990BD65A Content-Type: text/plain; charset="iso-8859-1"

-----Original Message----From: Lisa Cleary [mailto:lisa@cleary.com] Sent: 11 May 2003 16:17 To: 'Desmond McCarter' Subject: RE: Test ------_=_NextPart_000_01C3EFF7.990BD65A Content-Type: application/vnd.ms-excel; name="test.xls" Content-Transfer-Encoding: base64
C ollapse | C opy C ode

See Also...
C reating animations with Dundas C hart for ASP.NET Smarter Data Labels with Dundas C hart SmartLabels Understanding C hart Areas with Dundas C hart for .NET Making Sense of Geographic Data with Dundas Map and AJAX DestroyWindow in VBScript SmartLink C reate data-driven applications with the Hera Application Framework Towards the self-documenting database: extended properties Digital Signatures and PDF Documents Reading and Writing Images From a Windows Mobile Database using UltraLite 10 (C #) WMP Power Hour APP

0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAAEAAAAwQEAAAAAAAAA EAAA/v///wAAAAD+////AAAAAL0BAAC+AQAAvwEAAMABAAD///////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////8J CBAAAAYFAP4czQfJQAAABgEAAOEAAgCwBMEAAgAAAOIAAABcAHAADQAAV0ggU21pdGggTmV3cyAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEIAAgCwBGEBAgAAAMABAAA9AQQA AQD8AJwAAgAOABkAAgAAABIAAgAAABMAAgAAAK8BAgAAALwBAgAAAD0AEgAXB6b/WC+gIzgAAQAA AAEAWAJAAAIAAACNAAIAAAAiAAIAAAAOAAIAAQC3AQIAAADaAAIAAAAxABoAyAAAAP9/kAEAAAAA .

The Daily Insider

MIME (Multipurpose Internet Mail Extensions): A quick and dirty guide


Data that is transferred over the Internet is sent as a collection of bytes (i.e. a collection of 8 bits). This information includes text files, CSVs or even JPEGs or movies. "Hey" you might say "you can't send binary data as a collection of bytes!". Yes you can, with a suitable encoding scheme: using the base 64 algorithm for example (check out the System.Convert.ToBase64String method in your .NET framework). This information (we're talking in email context) also includes the subject, body and forwarded items. For the client (sending the email) and the server (reading the email) should understand each other and, in order to do that, they must conform (send and receive data) in MIME format. In the snipped MIME example (above), you can see and easily understand the basic fields: "From:" - who sent the email, "To:" - who is receiving the email, "Subject:" - the subject of the email and "Date:" - the date/time the email was sent. The "Content-Type:" determines what type of content the email contains. In a simple text email (i.e. with no attachments) this is normally "text/plain". You can see however (I hope you can anyway) that this email actually contains an attachment: test.xls. Emails that contain attachments have a MIME content type of "multipart/mixed". This means that the email contains data sectioned into multiple parts: the body and attachments (or in this case "attachment") etc. The boundary (boundary="- -- _=_NextPart_000_01C3EFF7.990BD65A") identifies where these parts start and stop. T he body in my example (and in most emails) is the first part of this multipart email. The start of the body identified at the first boundary declaration:
C ollapse | C opy C ode

------_=_NextPart_000_01C3EFF7.990BD65A Content-Type: text/plain; charset="iso-8859-1"

-----Original Message----From: Lisa Cleary [mailto:lisa@cleary.com] Sent: 11 May 2003 16:17 To: 'Desmond McCarter' Subject: RE: Test

You can also see from the above MIME text that this part also contains its content type, i.e. the format of the body: text/plain. All parts of a multipart email have their header definitions first, then an empty line, then the actual body. The next part of this multipart email is the attachment:
C ollapse | C opy C ode

------_=_NextPart_000_01C3EFF7.990BD65A Content-Type: application/vnd.ms-excel; name="test.xls" Content-Transfer-Encoding: base64 0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAAEAAAAwQEAAAAAAAAA EAAA/v///wAAAAD+////AAAAAL0BAAC+AQAAvwEAAMABAAD///////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////8J CBAAAAYFAP4czQfJQAAABgEAAOEAAgCwBMEAAgAAAOIAAABcAHAADQAAV0ggU21pdGggTmV3cyAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEIAAgCwBGEBAgAAAMABAAA9AQQA AQD8AJwAAgAOABkAAgAAABIAAgAAABMAAgAAAK8BAgAAALwBAgAAAD0AEgAXB6b/WC+gIzgAAQAA AAEAWAJAAAIAAACNAAIAAAAiAAIAAAAOAAIAAQC3AQIAAADaAAIAAAAxABoAyAAAAP9/kAEAAAAA .

Note again, the second and final "multipart part" (i.e. the attachment) start off with the boundary declaration. Also note that the content type is defined, as well as the name and encoding scheme used to convert the attachment, enabling it to be sent over the internet in byte format. You need to take note that had this email had another attachment, then the second attachment (the third "multipart part") would start off with the same boundary declaration and so on.

MIME is in fact object oriented


The first mistake I made when building a POP3 library was to develop it in a language that was unsuitable: C. It took too long to write and did indeed get very dirty. It took about 3 weeks to develop and test my library, whereas in C# it took a day and a half!! The reason for this is that MIME, you can say, is an object oriented format: each part of a multipart email (even the body of a simple text/plain mail + main headers etc.) can be thought of as being objects. This is one of the main reasons why I wrote it in C# (could have used Java or even J2EE but ...).

Code
The code I have written starts off with a class called Pop3Client. This class is used to instantiate connection to a POP3 server:
C ollapse | C opy C ode

Pop3Client email = new Pop3Client("user", "password", "mail.server.com");

You then open the Inbox as follows:


C ollapse | C opy C ode

email.OpenInbox();

To go to the first email, then you call the NextEmail() method, which returns true if there is a "next email" or false if no such email exists. T here is also a IsMultipart singleton, which you can use to check and see whether the email has multiple parts (i.e. attachments). Here's an example of how the code might look:
C ollapse | C opy C ode

try { Pop3Client email = new Pop3Client("user", "password", "mail.server.com"); email.OpenInbox(); while( email.NextEmail()) { if(email.IsMultipart) { IEnumerator enumerator = email.MultipartEnumerator; while(enumerator.MoveNext()) { Pop3Component multipart = (Pop3Component) enumerator.Current; if( multipart.IsBody ) { Console.WriteLine("Multipart body:"+ multipart.Body); } else { Console.WriteLine("Attachment name="+ multipart.Name); // ... etc } } } } email.CloseConnection(); } catch(Pop3LoginException) { Console.WriteLine("You seem to have a problem logging in!"); }

I have also implemented other functionalities within this class library which includes saving attachments (currently done automatically) in their original format, a getter for the filename, extension etc. Have a look and see what you think: I definitely found it fun to write and explore!!

License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author


Desmond McCarter
Web Developer United Kingdom Member

Des is a Technical Architect working for a private telecoms based company in the United Kingdom. He has been involved in programming for over 14 years and has worked on many platforms including UNIX, Linux and Windows. Language specialities are C, C++, C#.NET, Java & J2EE and shell scripting (especially on UNIX/Linux). Also enjoys writing and optimising SQL scripts. Des is engaged to a lovely girl called Lisa!

Article Top

Rate this:

Poor

Excellent Vote

Comments and Discussions


FAQ Profile popups New Message Noise level Medium Layout Normal Refresh olgofur rishabhtoshniwal kaempf84 cool_cupid_jny Mark Laird Rizwan Bashir Rajat_Chanana sampsonlau Sandeep Mewara Member 3753463 hoi gokujames raj4057 PrajeeshTest PrajeeshTest benbawden John LAWDeed David Cresswell biswajitcb Paulo Roussenq gulam_last chris175 testerbddd chris175 Ravi J Patel Last Update: 23:52 4 Oct '11 Suggestion Question Bug Answer Joke Per page 25 Search Update First Prev Next 9:16 23 Aug '11 4:16 25 Jul '11 15:33 25 Jul '11 7:37 1 Jul '11 19:35 24 Jun '11 2:20 21 Apr '11 11:06 16 Apr '11 22:35 3 Apr '11 3:12 26 Mar '11 20:39 28 Dec '10 22:45 20 Oct '10 5:27 14 Oct '10 14:55 27 Sep '10 0:39 16 Sep '10 9:07 15 Sep '10 12:55 13 Sep '10 8:59 16 Mar '11 12:54 11 Aug '10 9:22 29 Jul '10 15:54 6 May '10 3:24 3 May '10 14:41 16 Apr '10 17:39 13 May '10 9:21 16 Apr '10 8:09 7 Apr '10 1 2 3 4 5 6 7 8 9 10 11 Next Rant Admin

How to download attachments from defined letters byteCount getting 0 Re: byteC ount getting 0 Read Unread Mail My vote of 5 Extra characters like =3D or = at the end of line getting error while using this code in asp.net My vote of 5 My vote of 5 How to save attachement using POP3 Client in C# .NET? How to filter POP3 Email from Junk Mail ? My vote of 5 Need Help if (!header.Substring(0, 3).Equals("+OK")) My vote of 5 Filename and Name - trying to save attachments Re: Filename and Name - trying to save attachments Access to "Date" or any other unique reference My vote of 5 Method email.NextEmail() doesn't work attachment is not saving if mail is comming from gmail Updated Code Re: Updated C ode This code needs updating... Very helpfull Last Visit: 23:10 4 Oct '11 General News

Use C trl+Left/Right to switch messages, C trl+Up/Down to switch threads, C trl+Shift+Left/Right to switch pages.
P e rmalink | A dv ertis e | P rivac y | M obile | Web0 3 | 2 .5 .1 1 1 0 0 4 .1 L ayout: fix ed | fluid A rtic le C opyright 2 0 0 4 by D es mond M c C arter E verything els e C opyright C odeP rojec t, 1 9 9 9 - 2 0 1 1 T erms of U s e

You might also like