Free Information Technology Magazines and eBooks

Thursday, May 07, 2009

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 ();


Aside from reading emails, SmtPOP.NET can also send e-mail to an SMTP server.
To download the SmtPOP.NET library click here



For more C# tips and tricks, subscribe now



25 comments:

Anonymous said...

Hello. I found your C# code on how to read pop3 mail in C# and I thank you. One thing, though : when you say you "save to disk" the attachments, WHERE are they saved ? I couldn't find them !

Thanks

JCD

Anonymous said...

why the Body is always NULL
thanks

Anonymous said...

How this works with ssl and gmail for example? There is no any field, which subscribe ssl possibility.

Anonymous said...

Hi you,
How do you know get mail received date in smtPop.Net?
Please show me!
Thanks a lot.

girish meena said...

hi i also want to know. what if i want to deal with email sent by gmail account. how will i read them.

Fryan Valdez said...

@girish meena - you can the same code to read GMail messages. Just make sure to enable POP on your GMail account and use pop.gmail.com as the POP3 server. Good luck!

girish meena said...

@Fryan - thanks. In my application user sends mail from their account, it can be yahoo,gmail or MSN account. and these mail will come at id test@domain.com. Now i have to read these mail, it is woking fine with yahoo or others but not working fine with gmail mails.
What i have to do in this case.

girish meena said...

@Fryan thanks. In my application user can send mails through any mail account like yahoo, gmail MSN etc to a particular mail id like test@mydomain.com. I have to read these mails and save attachements. it is working fine with yahoo and others who don't have SSL issue, but not reading gmail mails which are sent by users.
hat should i do in this case.

girish meena said...

Hi Fryan,

Still I am using smtpop client. And I have a problem which I come to know just today.

I should divide it in three points to make you understand better.

1 smtpop is working fine, if a user sends email from their company email id (Like girish@company.com) to my application id (test@mydomai.com). In this case I can access email subject, body and attachment parts.

2. smtpop is working strangely when user send email from their yahoo id to my application email id. In this case I am able to access mail subject and body part, if email does not contain attachment. If email contains attachment I am not able to access body part.

3. In gmail case I am able to get both subject and body part when email does not have attachment. But it has no cue about email which have attachment means subject, body and attachment itself.

If you have any idea about this please tell me.

jackie said...

POPReader reader = pop.GetMailReader (id.Id);
what does the id.Id do and how should i replace it ....
please help soon..

My mail id jack.pmc@gmail.com

Fryan Valdez said...

@jackie - the id is a POPMessageId variable that holds the id of the messages (if any). You don't have to replace it. All you need to change is on this line

pop.Open ("mymailserver", "110", "sampleuser", "password");

Anonymous said...

Hi Fryan,

Fisrt I want to say thank you for the code it helped alot. :)

I do have a question that I was hoping you could answer. Do you know if there is a way I can download attachments that are related to unread emails?

Hope you can help on this.
Thanks,
Mel

vman said...

used you code but it crashes on 'pop.GetMailList()'
error: 'Object reference not set to an instance of an object'

Cristi said...

I`m would like to display the emails body, but msg.Bosy is null...

how can I diplay the body of an email using smtpop.dll?

Anonymous said...

I ran this application to read my emails in gmail and changed the made only one change in Pop.Open method as:

pop.Open ("pop.gmail.com", "110", "myname", "mypassword");

But I get an error/exception which says: "SocketException was unhandled

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 74.125.96.109:10

""

Please help with your inputs.

Thanks in Advance,
Ruben.

Please help

Anonymous said...

hai Thank u for ur code.I tried it.But it shows some error while connecting to pop server(Object reference not set to an instance of an object.).i used pop.gmail.com as my pop server and 995 as port number.Can u help me to solve it.

Anonymous said...

Hi,
I try to use this code in my .net 3.5 framework webapplication running on IIS 7 and it gives me this..
"System.Security.SecurityException: Request for the permission of type 'System.Net.DnsPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
"
Could you please let meknow what could be the issue?

cnu said...

how can I get the using SmtPop dll,
Can u Pls Help Me

eswaran said...

hai Thank u for ur code.I tried it.But it shows some error while connecting to pop server(Object reference not set to an instance of an object.).i used pop.gmail.com as my pop server and 995 as port number.Can u help me to solve it.

Anonymous said...

Hi,

I am now trying for a few days to resolve an error.

I created a project to read from a pop3 emailbox and get the attachments from all messages, save them to a local folder.
I used the smtpop.dll freeware library.
I worked with the code on this site: http://www.fryan0911.com/2009/05/how-to-read-pop3-email-using-c.html

This is working fine in debug mode. All attachments get pulled from the emails and saved to folder.
But... when i build the project and try to run the project, from the /release folder or any other pc, then i get the error:Configuration system failed to initialize
I placed the smtpop.dll in the same folder as the .exe
i referenced and used the .dll as described on the website.

What am i doing wrong, why do i get the error after building and not while debugging ?

Anonymous said...

I want to read my company mails.I just gave my server name "mail.domain.co.in", username "name@domain.co.in" and password. After I open connection , the message return "null"

Anonymous said...

The "pop.GetMailReader(id.Id)" does not seem to work. What am I doing wrong?

Anonymous said...

Quiero agregar algunas líneas espero sirva:

if (attach.Filename != "")
{

Byte[] b;
Console.WriteLine(attach.ContentTransferEncoding);
if (attach.ContentTransferEncoding.Equals(" quoted-printable\r\n"))
{

//foreach (EncodingInfo ei in Encoding.GetEncodings())
//{
// Encoding e = ei.GetEncoding();

// Console.Write("{0,-6} {1,-25} ", ei.CodePage, ei.Name);
// Console.Write("{0,-6} ", e.WindowsCodePage);

//}

string cadena = DecodeQuotedPrintables(attach.Body);
b = Encoding.ASCII.GetBytes(cadena);
}
else if (attach.ContentTransferEncoding.Equals(" 7bit\r\n"))
{
b = Encoding.ASCII.GetBytes(attach.Body );
}
else
{
// read data from attachment
b = Convert.FromBase64String(attach.Body);
}

Anonymous said...

Hello, I want to share some lines.
=================================
if (attach.Filename != "")
{

Byte[] b;
Console.WriteLine(attach.ContentTransferEncoding);
if (attach.ContentTransferEncoding.Equals(" quoted-printable\r\n"))
{

//foreach (EncodingInfo ei in Encoding.GetEncodings())
//{
// Encoding e = ei.GetEncoding();

// Console.Write("{0,-6} {1,-25} ", ei.CodePage, ei.Name);
// Console.Write("{0,-6} ", e.WindowsCodePage);

//}

string cadena = DecodeQuotedPrintables(attach.Body);
b = Encoding.ASCII.GetBytes(cadena);
}
else if (attach.ContentTransferEncoding.Equals(" 7bit\r\n"))
{
b = Encoding.ASCII.GetBytes(attach.Body );
}
else
{
// read data from attachment
b = Convert.FromBase64String(attach.Body);
}

Anonymous said...

Here the fragment to decode
============================

private static string DecodeQuotedPrintables(string input)
{
var occurences = new Regex(@"=[0-9A-Z]{2}", RegexOptions.Multiline);
var matches = occurences.Matches(input);
foreach (Match match in matches)
{
char hexChar = (char)Convert.ToInt32(match.Groups[0].Value.Substring(1), 16);
input = input.Replace(match.Groups[0].Value, hexChar.ToString());
}
return input.Replace("=\r\n", "");
}