Pages

Thursday, December 22, 2011

How to Read POP3 email using C#

Aside from sending email notification, sometimes we require our application to read POP3 emails. Today I will show you how to read POP3 mails using SmtPop.Net in C#. SmtPop.Net is an open source class library to receive and send e-mail messages through SMTP and POP3 server.


First you need to reference smtpop.dll on you .NET project. Then include SmtPop on the Using directives as follows:

using SmtPop;


Now here is a sample code to read POP3 emails:

// connect to pop3 server
POP3Client pop = new POP3Client ();
pop.ReceiveTimeout = 3 * 60000; // Set the timeout to 3 minutes
pop.Open ("mymailserver", "110", "sampleuser", "password");

// retrieve messages list from pop server
POPMessageId[] messages = pop.GetMailList ();

if (messages != null)
{
// run through available messages in POP3 server
foreach (POPMessageId id in messages)
{
POPReader reader = pop.GetMailReader (id.Id);
MimeMessage msg = new MimeMessage ();

// read the message
msg.Read (reader);
if (msg.Attachments != null)
{
// retrieve attachements
foreach (MimeAttachment attach in msg.Attachments)
{
if (attach.Filename != "")
{
// read data from attachment
Byte[] b = Convert.FromBase64String (attach.Body);
// save attachment to disk
System.IO.MemoryStream mem = new System.IO.MemoryStream (b, false);
FileStream outStream = File.OpenWrite(attach.Filename);
mem.WriteTo(outStream);
mem.Close();
outStream.Flush();
outStream.Close();
}
}
}
//delete message
pop.Dele (id.Id);
}
}
//close the connection to POP3 server
pop.Quit ();

No comments: