POP3 Email
Published: 23 Aug 2004
Unedited - Community Contributed
Wouldn’t it be useful to be able to check your mail from a web browser? Here we look at how to write such a utility using the TcpClient class. Start from simply logging on to more complex issues like reading and deleting messages.
by Damian Manifold
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 62925/ 104


POP3 Email
by Damian Manifold

.NET comes with some new and interesting toys, but the one thing that is missing is the ability to receive POP3 Mail. Here we will build a class to take care of this oversight.
Logging On & Logging Off

Logging On & Logging Off
by Damian Manifold

Here is the code to connect to the server and communicate with it; also it allows you to perform the 2 most basic mail functions which are Logging On and Logging Off.

Source Code
PopMail.aspx The Form to enter the Account Details
PopMail.aspx.vb The Code to do all the work

You will notice that when responses are checked to be okay we only check for the +OK, other information maybe returned after but this is not part of the Standard and should be ignored.

PopMail.aspx the mail example in action

Getting MailBox & Message Size

Getting MailBox & Message Size
by Damian Manifold

Once you have logged in, the next easiest thing to do is to retrieve statistics about the mailbox and messages.

Below you will find the POP3 class code with 3 new properties MailBoxSize , MessageCount, and a new class MailMessage. Although at the moment it only holds the ID and size, we fill go on to add more properties as we retrieve them from the server.

Source Code
PopMail.aspx The Form to enter the Account Details
PopMail.aspx.vb The Code to do all the work

You can see in the code that the MailBoxSize and MessageCount properties have been written to set the value the first time they are called, this has been done to reduce unnecessary trafic.Your mailbox will locked once you have logged in and not released until you log out, so remember the quicker you perform your task the better. If you wish to experiment remember that if your code bombs out whilst you are logged into your mailbox it will remain locked until it times out in about 5 to 10 minutes.

So now you have the ability to add a "You've got mail!" component to you homepage, or better identify oversized emails in your mailbox.

PopMail.aspx the mail example in action

Retrieve Message and Headers

Retrieve Message and Headers
by Damian Manifold

Now we shall look into retrieving the mail message from the server, and then go on to extract the header information.

Source Code
PopMail.aspx The Form to enter the Account Details
PopMail.aspx.vb The Code to do all the work

You can see that we have now modified the MailMessage Class.

  161   public class MailMessage
  162   Inherits System.Web.Mail.MailMessage
Code Sample1 Generated using CodeView

The class now inherits from the SMTP MailMessage class. This means that it now can hold all the information of the email without us having to re-invent the wheel; it also makes it easy to pass the mail back out using the SMTP Mail class.

Now that we are going to be retrieving the entire message we can expect to receive a lot more data. The Getdata function has been enhanced to be able to read more than just a short reply.

  185  private function getData() as string
  186      Dim bData(t.ReceiveBufferSize) as byte
  187      getData = ""
  188      Do
  189          'get the data
  190          s.Read(bData, 0, bData.Length)
  191          getData += System.Text.Encoding.ASCII.GetString(bData)
  192          'clear byte array for next pass
  193          bData.Clear(bData, 0, bData.Length)
  194          'wait for the dataavailble flag to get set
  195          System.Threading.Thread.Sleep(250)
  196          'if there is more data repeat
  197      Loop while s.DataAvailable
  198  End function
Code sample2 Generated using CodeView

The message stream is read in a loop until there is no more data. There is a small delay to allow the DataAvailable flag to be set, 250 milliseconds seems more adequate, unless you have anti-virus software that scans emails, in which you may need to increase this.

There 2 new public functions in the class, getHeader and getMail. getHeader uses the TOP pop3 command to retrieve just the header component of the mail message. Where as getMail users the RETR pop3 command to retrieve the entire message and then seperates it into its Header and Body parts. Both functions use the private setHeader function to extract the header information into the MailMessage.

The setHeader function extracts the standard header information and a few of the more useful ones such as Message-ID. The mail Header and does contain a lot more information, as to whether is useful is up to you.

The example below shows the getMail function in action. You can see getHeader function in action in the next part where we go on to delete messages.

PopMail.aspx the getMail in action

Deleting Messages

Deleting Messages
by Damian Manifold

Deleting messages is a simple but important task; here you will see the GetHeader function being used to create a list of Messages to be marked for deletion by the delete function.

Source Code
PopMail.aspx The Form to enter the Account Details
PopMail.aspx.vb The Code to do all the work

The delete function uses the DELE pop3 command to delete a mail by using the message number, this may be a problem. In a web situation once the list has been produced there could be some time till a selection is made. If this is the case the message cannot be guaranteed to be in the same position, as there is the possibility that the MailBox may have be accessed by another client.

This being the case, the example uses the Message-ID header value to uniquely identify the message. It does mean however that we have to search for the corresponding message number. This is easily done in the loop that is used to produce the list, if a match is found the corresponding message is deleted and the list item struck out to indicate this.

  41  'check wether the mail has been marked for deletion
  42  if Request.Form.Item(ma(cnt).Headers("Message-ID")) <> "" Then
  43      'if it has, delete it a indicate its deletion.
  44      if p.delete(ma(cnt)) Then
  45          r.Font.Strikeout = true
  46      End if
  47  End if
Code Sample1 Generated using CodeView

PopMail.aspx the getHeader and delete functions in action

Articles and Links

Read POP3 Email with ASP.NET By Chris Garrett

http://www.faqs.org/rfcs/rfc1460.html Post Office Protocol - Version 3

User Comments

Title: Mr.   
Name: Richard White
Date: 2011-07-31 6:21:25 PM
I am using yahoo e-mail to organize a large reunion. I have 1 group, 3 folders pluse my contacts and all of my sent e-mails to the reunion members. I am not at all happy with Yahoo and it is giving me a lot of trouble. How do I get all of this into a Gmail or an at&t account?
Title: SP   
Name: SP
Date: 2010-08-26 1:23:06 PM
Utilize seu computador para ligar para qualquer fixo ou celular em todo Brasil.

Economize até 80% em ligações telefônicas

* Tarifa unica por minuto para todo Brasil
* Tarifa unica em qualquer horário
* Ligue para qualquer fixo ou celular
* Sem assinatura
* Sem mensalidade
* R$ 0,22 Local/DDD
* R$ 0,69 Celular Brasil

Baixe o softfone gratuitamente no site www.systemvoice.com.br, faça o cadastro em abra sua conta voip e receba, senha e login.

Teste gratuito de 10 minutos em ligaçoes.
Title: sp   
Name: sp
Date: 2010-07-31 9:08:05 PM
Quer melhorar seu site ?
Quer realizar uma campanha digital na Internet ?
A AG360 atua no segmento a mais de 13 anos.
Temos mais de 2000 sites desenvolvidos em nosso portfólio e mais de 250 lojas virtuais com sucesso na WEB.
Experiência e Seriedade.
Solicite nossa equipe comercial.
Agradecemos sua atenção !!
Title: DF   
Name: DF
Date: 2010-02-11 11:29:10 AM
Agora Brasilia possui o GUIA mais completo e robusto da Região!!! Você não pode deixar de conhecer.

ACESSE AGORA: www.acessabrasilia.com

- Assista Tv ao Vivo 24hs
- Lista Telefônica regional
- Guia de Acompanhantes
- Guia Médico
- Guia Odontológico
- Guia Nextel
- WebCan's ao Vivo pelo mundo
- Assista Filmes 24hs totalmente grátis
- Zoológico 24hs ao Vivo
- Escute conversa entre pilotos de Aviões ao vivo
- Classificados
- 2ª Via de contas
- Imagens Via satélite
- Previsão do tempo
- Trabalhos Escolares prontos

Tudo isso e muito mais 100% grátis.

O que Vc sempre quiz em um só lugar.


ACESSE JÁ: www.acessabrasilia.com

Title: SP.   
Name: SP.
Date: 2010-02-04 2:23:26 PM
OLICAB - Comércio de equipamentos p/ lojas Ltda.,
localizada à Rua Ricardo Dalton, 287 - km 25 Via Anhanguera - São Paulo/SP.
Atuando na Área de Instalações Comerciais desde 1994, vem oferecendo aos Supermercadistas e Lojistas, ampla linha de Equipamentos e Acessórios para todos os segmentos de lojas.
- Gôndolas ( Prateleiras ) para Hipermercados e Supermercados, Pet-Shop, Perfumarias, Farmácias, Bombonieri, Lj.de Convenências, Lj. de Presentes,
Papelarias, Material de Construção, etç.
- Racks de Depósitos p/ Hiper e Supermercados,
- Acessórios como Réguas, Ganchos, Cestos e Porta Etiquetas p/Prateleiras em diversas cores.
Fazemos Reformas dos Equips de sua Loja, como (Pés de Gôndolas, Prateleiras, Consoles, Cestos, Podiun p/ Ponta de Gôndolas), etç.
Reposição e Pintura de Gôndolas e Terminais. Oferecemos Serviços Especializados de Pintura Eletrostática (epóxi).
Temos grande variedade de Produtos à pronta-entrega e facilitamos o pagamento.
Entre em contato conosco e confira, através dos nossos - Tels. (011) 3916-6152 / 3916-6013
- Falar c/ Sra. Vera p/ Cel.9195-9536 ou
c/ Sr. Oliveira - Cel. 7133 - 6298
- Site: www.olicab.com.br
- Email: olicab@ig.com.br
Title: Web developer   
Name: Tanveer Ahmad
Date: 2009-12-29 3:37:28 AM

Its fabulous and great.its working 100% .. Really you do good work thanks a lot .
Title: Deepak   
Name: Saxena
Date: 2009-05-30 5:21:03 AM
i want to use you downloads
Title: problem with body mail   
Name: super
Date: 2009-04-12 6:53:44 AM
This article is helpful. But, I have a big problem with the display of contain's (body) mail. This code displays more informations, letters and numbers without any meaning .
I think that the contain is not formated. Can one help me ?

Title: Prob. In Running   
Name: Cutama
Date: 2009-04-06 7:58:21 AM
DPM assemblies are not necessary, I've removed the reference to DPM assemblies but hte code still runs fine.

However, when I run the code using break points everythign is fine. However, when I deploy the code it pops up errors at c.text=server.htmlencode(m(cnt)..... some tines it is at To and soem times it is at the body.

Pls. Help.
Title: How can I get Assembly?   
Name: Neetu
Date: 2009-03-20 12:51:16 AM
Hello There,,

Plz , Can u tell me
how i can download the DPM assembly.
<%@ Register TagPrefix="cc1" namespace="DPM" Assembly="DPM" %>?
waiting for your reply
Title: How to Get only Plain Text   
Name: Nilesh
Date: 2008-12-23 2:11:33 AM
Please give me the code how to Get only plain Text.
Title: How to get all the Emails Read/Unread)   
Name: ravi gupta
Date: 2008-12-16 6:29:39 AM
Please give me the code how to Get all emails regardless of Read/unread.

Title: Time Outs   
Name: DVD
Date: 2008-12-15 7:00:16 PM
This is really helpful code but I'm experiencing really slow performance when I'm accessing even just the headers of a POP3 box with 200+ messages in it (a total of 9mb of mail)and timeouts if I try to access the bodies. Even your demo pages on here time out. When I use a webmail interface to access this mailbox it is much faster. Could you please help identify the source of this problem? Thanks.
Title: Will Not Run On Live Server   
Name: John
Date: 2008-10-15 5:12:20 PM

This code works great when running from a test machine and connecting to pop3 on our live server.

But once it gets installed on live server, the page times out.

Any ideas? Do I have to rename the pop3 server as it is local?
Title: -ERR Unacceptable command   
Name: Simon
Date: 2008-10-14 10:52:26 AM

Firstly, thanks for the code, it;s going to really help us.

Getting a problem with the getMail funstion though.

The line: msg = SendCmd("retr " + m.ID.ToString + " 0")

effectively this is writing (for 1st message):
SendCmd(retr 1)

However it is returning:
-ERR Unacceptable command

Any ideas?

Thanks in advance.
Title: plz help me   
Name: raghavenrdra
Date: 2008-09-27 6:57:09 AM
how i can download the DPM assembly.
<%@ Register TagPrefix="cc1" namespace="DPM" Assembly="DPM" %>
Title: how to send mails in pop3   
Name: Raghavendra
Date: 2008-09-27 2:31:33 AM
hi there.
i read ur artical but i need C#.net code and is there any configure on my system means settings.plz help me.
Title: Outstanding   
Name: Mike
Date: 2008-08-26 3:40:50 PM
Outstanding code - THANKS!
Title: email logout   
Name: The 2 Tops
Date: 2008-08-08 7:10:16 AM
I logged onto another computer and accessed my e-mail via my Virgin media account. That computer now has my e-mail address and password, in addition to their own, and that user cannot remove my details. Is it possible for one of us to rectify this?
Title: Unread Messages   
Name: DamianM
Date: 2008-05-05 5:13:10 AM
POP3 makes no distinction as to whether a message is read or unread. This has to be done in the client.
Title: pop3   
Name: sekhar
Date: 2008-05-05 5:06:59 AM

how to read unread messages from pop3 server
Title: Create New Mail id   
Name: Swati
Date: 2008-05-02 2:43:20 AM
Can anyone let me noe how can I make a new mail id in POP 3 server. The thing I want is whenever a new employee joins our organization the new mail id is automatically created on mail server. Plz advice.
Title: telnet   
Name: DamianM
Date: 2008-04-24 9:44:27 AM
If you cannot connect via telnet, either the url or the port number is wrong. These are the only variable i can think of.
Title: popcommand with telnet   
Name: fathima
Date: 2008-04-24 7:50:50 AM
i have tried to connect pop mail thro telnet.. it doesnt connect.. how can i find where the problem is..
Title: GMail   
Name: DamianM
Date: 2008-04-23 4:43:05 AM
The only reason I can think of it not working isthat some of the responses might be different to when this was first written.
Try to connect to the pop mail via telnet and see what responses you get.
Title: NetworkStream problem   
Name: Fathima
Date: 2008-04-23 2:42:19 AM

We use "pop.gmail.com" as server and portnumber as 995.

private s as System.Net.Sockets.NetworkStream
private t as new System.Net.Sockets.TcpClient()
private Cnct as Boolean = false

public Sub new(ByVal Server as string)
t.Connect(Server, 995)
s = t.GetStream()
if Left(getData(), 3) = "+OK" Then
Cnct = true
End if
End Try
End Sub

From this, we could not get stream data. kindly help to solve this problem.

Thanks in advance
Title: .   
Name: DamianM
Date: 2008-04-22 4:10:54 AM
The DPM assemblies are not part of the pop3, they are part of the display. They can be ignored.
Title: pop3 email   
Name: fathima
Date: 2008-04-22 1:30:15 AM
what about this DPM assembly.. where can i find these..
with regards,
Title: POP 3 Email   
Name: Murali
Date: 2008-02-27 1:55:47 AM
Your codes are very grate but i need the sample source project for my reference. if you can possible please send it to me. my email id is mkmurali.mca@gmail.com. i am expecting to your reply.

Thank you.
Title: Retrieve Message and Headers   
Name: ibraheem Ammrieh
Date: 2008-01-16 9:18:11 AM
this code is very grate but it doesn't work on local. you can test this piont. there is a problem in securiy or something else
Title: plz help me   
Name: prashant
Date: 2007-12-22 10:10:53 AM
my email id is adc_jain2005@yahoo.co.in

even can you tell me how to read pop3 mailbox which are SSL enabled
Title: plz help me   
Name: prashant
Date: 2007-12-22 10:09:41 AM
object reference not set to the instance of the object
in the line
can you pls tell me how to solve this error or can you send me the project in which your coding is working perfectly
Title: plz help me   
Name: prashant jain
Date: 2007-12-22 10:08:16 AM
thank you for replying me
in this coding when i run on the demo you have given then it runs fine without any problem but when i copy paste the coding in my project i run fiine if i debug but if i run without debugging then it gives folllowing error
Title: Attachments   
Name: Damianm
Date: 2007-12-21 6:34:12 AM
In the world of pop3 there is really no such think as attachments its all just text, attachments are stored in the email encoded in some form, usually mime. Reading an attachment is just a matter of reading the text from the email them decoding it.
Decoding it depends on how it was decoded as is technically very different from the scope of this article.
Title: pls help in reading attachment   
Name: prashant jain
Date: 2007-12-21 1:21:36 AM
its fine
but on reading attachment its gives error
can you please tell me how to read attachment
please mail me on adc_jain2005@yahoo.co.in
Title: Entire Source Code   
Name: Don Sharp
Date: 2007-12-02 6:12:04 PM
Is it possible to get the entire source code for this project?

Title: Error While trying to view the code   
Name: Balaji
Date: 2007-08-12 11:27:39 PM
While trying to view the popmail.aspx.vb, it throws error. Can you please correct the error and help me in getting the content of that page.

With Regards
Title: Unread Email   
Name: DamianM
Date: 2007-07-23 5:21:32 AM
There is no way using pop3 to determine whether an email is read or unread. This is done by the email client, such as outlook, they keep track of this and it is not a function of POP3.
Title: Help me please !!!   
Name: Edmond
Date: 2007-07-21 9:49:41 AM
HI ~
I'm currently doing my project about mail notification tool on the system tray.
My project should be able to check if some new mail is available now from the pop3 webmail server(yahoo mail, hotmail and Gmail). And I will coding in Visual Basic 2005.
But now,I still having some problems. Could you please help me how to check the unread mail from pop3 webmail server.

Please help me. Thanks
Here my email address : ahyeap_4yw@hotmail.com

Best regards,
Title: Uread Mail   
Name: Mostafa
Date: 2006-09-14 7:12:42 AM
i need to read and save Uread Mail and Attachment
how can i do this
Title: How to get unread emails   
Name: Naveen
Date: 2006-08-09 3:31:15 AM
i want to get the all unread mail from the pop3 server. could you please help me how to check the unread mail from pop3 server. i am able to read all mails from POP3 but i am not able to Identify them read/unread.

Please help me

Title: POP3 EMails   
Name: Nirav Dolia
Date: 2006-08-01 9:48:28 AM
i want to get the all unread mail from the pop3 server. could you please help me how to check the unread mail from pop3 server. i am able to read all mails from POP3 but i am not able to Identify them read/unread.

Please help me

Nirav Dolia
Title: Error in code   
Name: Andy
Date: 2006-06-16 1:35:49 PM
I noticed a bug in the following method which was causing the mail body not to be displayed properly:

Public Function getMail(ByRef m As MailMessage) As Boolean
Dim msg As String
Dim hend As Integer

'make sure the buffer is big enough to hold the message.
'to be sure make it just a little bigger
't.ReceiveBufferSize = m.Size
msg = SendCmd("retr " + m.ID.ToString + " 0")

Changing the above line to :
msg = SendCmd("retr " + m.ID.ToString + vbCrLf)
resolved the problem.

Hope this saves someone time. Nice article although!
Title: Excellent Article   
Name: engineer3000
Date: 2006-06-03 4:10:14 AM
Hi Buddy,Excellent article. you did a greate job. Thanx a lot....
Title: POP Mail   
Name: Dinesh
Date: 2006-05-29 8:44:32 AM
its fantastic
Title: Source in C#?   
Name: Paul
Date: 2006-04-29 12:08:00 AM
Great article, exactly what I am looking for, But now I have to translate it to C# to work with my application. Do you by chance have the Source code in C#?
Title: Wonderful   
Name: Deric
Date: 2006-04-19 2:57:07 PM
This is great.

Title: Tiwari   
Name: Aashutosh
Date: 2006-04-11 12:26:19 AM
Fine article but better to make it in c#.
Title: pop3   
Name: William Wallace
Date: 2005-08-31 5:54:45 AM
thanks a lot.... this article is excellent... a great help...
Title: POP3 EMail   
Name: Pankaj
Date: 2005-07-15 9:35:06 AM
I was looking for such a code and I really found it gr8. I really appreciate for putting this article on the web. It has taken me 2 days to find this article and I really find it very useful. Thanks for this article.
gr8 work
Title: Very Good   
Name: Abhijit Kulkarni
Date: 2004-10-06 5:20:26 AM
This is really good. Help me very much.

Title: Excellent   
Name: Bahadir ARSLAN
Date: 2004-08-27 2:20:16 AM
Excellent work!
Very easy and clear article...
Title: Progger   
Name: Rob
Date: 2004-07-12 4:32:06 AM
Excellent, i enjoyed the article and will use some of it and give credit where it is due.

Thanx again

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-07-02 5:05:11 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search