Friday 11 April 2008

Fetching and processing POP3 email in C#.NET

This is a problem that plagued the first three hours of my day, and was solved by the incredibly handy OpenPop.NET. I played with two other POP-related products including one entry on TheCodeProject.com, but with not much in the way of luck.

I was really impressed with OpenPop.NET because I was able to create a POP3 solution that:

  1. Connected to a POP server.
  2. Fetched some email.
  3. Checked the attachments for the ContentType of text/xml.
  4. If it was XML, I then processed and saved the XML to disk.

All of the above took a grand total of 60 minutes to complete, and all of this was without any documentation (I think it's a side-project of two developers who haven't gotten around to documenting it yet), which speaks volumes for the simplicity of its design and the properties and methods it exposes.

Source code is below just in case you get stuck. Obviously you'll need to introduce some error trapping.


That URL again - http://sourceforge.net/projects/hpop/!

7 comments:

Michael O'Neill said...

Nicely done.

Unknown said...

I am trying to use OpenPOP to do something very similar to what you are doing. The only difference is that I do not want to limit the file types to xml. I am unable to find documentation on OpenPOP. I am retrieving the emails and can print out the attachment filenames, I just can't figure out how to save the actual files. Any help will be greatly appreciated. Thanks.

Unknown said...

Nevermind. I just figured it out. Thanks anyway.

In case anyone else stumbles upon this you can replace the loop that is iterating through the attachments with:

for (int j = 0; j < m.AttachmentCount; j++)
{
if (!m.GetAttachment(j).NotAttachment)
{
attachmentBytes = m.GetAttachment(j).DecodedAsBytes();
if (attachmentBytes != null)
{
using (BinaryWriter binWriter = new BinaryWriter(File.Open("c:\\test\\" + m.GetAttachmentFileName(m.GetAttachment(j)), FileMode.Create)))
{
binWriter.Write(attachmentBytes);
}
}
}
}

Sagamore said...

Thanks !
Your comment regarding downloading any type of attachment saved me hours of development.

Unknown said...

Hi I am also trying fetching email from gmail using OpenPop. But the problem is it gives me wrong sequence of email. I need to fetch the latest emails but it gives me emails that are not sequential in terms of receiving date/time.

Could you help me?

Wet said...

I wanted to thank you for the time you saved me. I spent most of the day evaluating different POP3 components on Code Project and OpenPOP didn't even appear in my Google searches.

OpenPOP is an excellent (an updated) project for all of my POP3 needs!

Unknown said...

i am not getting the y < msg.AttachmentCount . help me please..