EAGetMail Developers Center > Using EAGetMail in Visual Basic.NET to retrieve email from POP3/IMAP4 server
This page has moved. Click Here! to redirect to our new page.
Introduction
EAGetMail is a POP3 & IMAP4 component which supports all operations of POP3/IMAP4/MIME protocol. This tutorial covers everything of receiving email and parsing email with EAGetMail in VB.NET.
Installation
You should download the EAGetMail Installer and install it on your machine at first.
A simple VB.NET project
First of all, let's create a VB.NET console project named "receiveemail" at first, then add the reference of EAGetMail in your project (Please refer to next section).
Add Reference of EAGetMail to Visual Stuido.NET Project
To use EAGetMail POP3 & IMAP Component in your project, the first step is "Add reference of EAGetMail to your project". Please create/open your project with Visual Studio.NET, then choose menu->"Project"->"Add Reference"->".NET"->"Browse...", and choose the EAGetMail{version}.dll from your disk, click "Open"->"OK", the reference of EAGetMail will be added to your project, and you can start to use EAGetMail POP3 & IMAP Component in your project.
Because EAGetMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.
Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0 and .Net Compact Framework 2.0, 3.5.
| File | .NET Framework Version |
| EAGetMail.dll |
Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version. |
| EAGetMail20.dll |
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version. |
| EAGetMail35.dll |
Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version. |
| EAGetMail40.dll |
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version. |
| EAGetMailCF20.dll |
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version. |
| EAGetMailCF35.dll |
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version. |
Retrieve email from POP3 server
The following code demonstrates how to receive email from a POP3 mail account. This sample downloads emails from POP3 server and delete the email after the email is retrieved.
Add the following code like this:
'[VB.NET Example - Receive email from POP3 server]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
Dim oServer As New MailServer("pop3.emailarchitect.net", _
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'if your POP3 server requires SSL connection,
'please add the following codes:
'oServer.SSLConnection = True
'oServer.Port = 995
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from POP3 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted from POP3 server.
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from POP3 server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
If you set everything right, you can get emails in the mail folder. If the codes threw exception, then please have a look at the following section.
Where can I get my POP3 server address, user and password?
Because each email account provider has different server address, so you should query your POP3 server address from your email account provider. User name is your email address or your email address without domain part. It depends on your email provider setting.
When you execute above example code, if you get error about "Networking connection" or "No such host", it is likely that your POP3 server address is not correct. If you get an error like "Invalid user or password", it is likely that you did not set the correct user or password.
Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your POP3 server address, user in your email client. For example, you can choose menu -> "Tools" - > - "Accounts" - > "Your email account" - > "Properties" - > "Servers" in Outlook express or Windows Mail to get your POP3 server, user. Using EAGetMail to receive email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.
Retrieve email from IMAP4 server in VB.NET
If your server supports IMAP4 protocol, you can also receive email by IMAP4 protocol. Please have a look at the following code.
'[VB.NET Example - Receive email from IMAP4 server]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
Dim oServer As New MailServer("imap4.emailarchitect.net", _
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4)
Dim oClient As New MailClient("TryIt")
'Set IMAP4 server port
oServer.Port = 143
'if your IMAP4 server requires SSL connection,
'please add the following codes:
'oServer.SSLConnection = True
'oServer.Port = 993
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from IMAP4 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted from IMAP server.
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from IMAP server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Retrieve email over SSL connection
SSL connection encrypts data between the POP3 component and POP3 server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail.
The following samples demonstrate how to receive email over SSL connection from Gmail, Yahoo and Hotmail account.
Receive email from Gmail account with SSL connection
'[VB.NET Example - Receive email from Gmail]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Gmail POP3 server is "pop.gmail.com"
'Gmail user authentication should use your
'Gmail email address as the user name.
'For example: your email is "gmailid@gmail.com",
'then the user should be "gmailid@gmail.com"
Dim oServer As New MailServer("pop.gmail.com", _
"gmailid@gmail.com", "yourpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'Set SSL connection
oServer.SSLConnection = True
oServer.Port = 995
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from POP3 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted in Gmail Account
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from Gmail POP3 server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Retrieve email from Yahoo account with SSL connection
'[VB.NET Example - Receive email from Yahoo]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Yahoo POP3 server is "pop.mail.yahoo.com"
'Yahoo user authentication should use your
'Yahoo email address as the user name.
'For example: your email is "yahooid@yahoo.com",
'then the user should be "yahooid@yahoo.com"
Dim oServer As New MailServer("pop.mail.yahoo.com", _
"yahooid@yahoo.com", "yourpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'Set SSL connection
oServer.SSLConnection = True
oServer.Port = 995
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from POP3 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted in Yahoo Account
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from Yahoo POP3 server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Retrieve email from Hotmail account with SSL connection
'[VB.NET Example - Receive email from Hotmail]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Hotmail POP3 server is "pop3.live.com"
'Hotmail user authentication should use your
'Hotmail email address as the user name.
'For example: your email is "hotmailid@hotmail.com",
'then the user should be "hotmailid@hotmail.com"
Dim oServer As New MailServer("pop3.live.com", _
"hotmailid@hotmail.com", "yourpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'Set SSL connection
oServer.SSLConnection = True
oServer.Port = 995
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from POP3 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted in Hotmail Account
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from Hotmail POP3 server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Retrieve email with event handler
After Connect method, GetMail method or other methods are invoked, if you want to know the progress of the email receiving, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email receiving.
'[VB.NET Example - Receive email from with event handler]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Private Sub OnConnected(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Connected")
End Sub
Private Sub OnQuit(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Quit")
End Sub
Private Sub OnReceivingDataStream(ByVal sender As Object, ByVal info As MailInfo, _
ByVal received As Integer, ByVal total As Integer, ByRef cancel As Boolean)
Console.WriteLine(String.Format("Receiving {0}, {1}/{2}...", info.Index, _
received, total))
End Sub
Private Sub OnIdle(ByVal sender As Object, ByRef cancel As Boolean)
End Sub
Private Sub OnAuthorized(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Authorized")
End Sub
Private Sub OnSecuring(ByVal sender As Object, ByRef cancel As Boolean)
Console.WriteLine("Securing ...")
End Sub
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
Dim oServer As New MailServer("pop3.emailarchitect.net", _
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'if your POP3 server requires SSL connection,
'please add the following codes:
'oServer.SSLConnection = True
'oServer.Port = 995
'Catching the following events is not necessary,
'just make the application more user friendly.
'If you use the object in asp.net/windows service or non-gui application,
'You need not to catch the following events.
'To learn more detail, please refer to the code in EAGetMail EventHandler
AddHandler oClient.OnAuthorized, AddressOf OnAuthorized
AddHandler oClient.OnConnected, AddressOf OnConnected
AddHandler oClient.OnIdle, AddressOf OnIdle
AddHandler oClient.OnSecuring, AddressOf OnSecuring
AddHandler oClient.OnReceivingDataStream, AddressOf OnReceivingDataStream
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from POP3 server
Dim oMail As Mail = oClient.GetMail(info)
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'generate an email file name based on date time.
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailbox, sdate, d.Millisecond.ToString("d3"), i)
'save email to local disk
oMail.SaveAs(fileName, True)
'mark email as deleted from POP3 server.
oClient.Delete(info)
Next
'quit and pure emails marked as deleted from POP3 server.
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
Using UIDL function to mark the email has been downloaded
If you want to leave a copy of email on the server, you should not call Delete method. However, there is a problem, how can you know if the email has already been downloaded? If there is a way to identify the downloaded email, you can avoid downloading the duplicated email from your POP3/IMAP4 server.
IMAP4 Solution
Every email has a unique identifier (UIDL) on IMAP4 server. It is a 32bit integer and it is always unique in your email account life time. So we can use the integer as file name to identify if the email has been downloaded.
Please see the following example code:
'[VB.NET Example - Receive email from IMAP4 server - Leave a copy of message on server]
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
Dim oServer As New MailServer("imap4.emailarchitect.net", _
"test@emailarchitect.net", "testpassword", ServerProtocol.Imap4)
Dim oClient As New MailClient("TryIt")
'Set IMAP4 server port
oServer.Port = 143
'if your IMAP4 server requires SSL connection,
'please add the following codes:
'oServer.SSLConnection = True
'oServer.Port = 993
Try
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
For i As Integer = 0 To infos.Length - 1
Dim info As MailInfo = infos(i)
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", _
info.Index, info.Size, info.UIDL)
'receive email from IMAP4 server
Dim oMail As Mail = oClient.GetMail(info)
'using IMAP UIDL as the file name.
Dim fileName As String = String.Format("{0}\{1}.eml", _
mailbox, info.UIDL )
If File.Exists( fileName ) Then
'This email has been downloaded, do not download it again.
Continue For
End If
Console.WriteLine("From: {0}", oMail.From.ToString())
Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)
'save email to local disk
oMail.SaveAs(fileName, True)
'do not delete email from IMAP4 server.
Next
'quit
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
End Module
POP3/IMAP4 Solution
There is a little bit different in POP3 server. The UIDL is only unique in the email life time. That means if the email was deleted from the server, other email can use the old unique identifier. Another problem is: UIDL in POP3 server can be any number or characters, so we cannot use UIDL as the file name, because UIDL may contain invalid characters for file name.
To solve this problem, we have to store the UIDL to a txt file and synchronize it with server every time.
Please have a look at the following example code. It works with both POP3/IMAP4 servers.
'[VB.NET Example - Using UIDL to mark email as read]
Imports System.Collections
Imports System.Text
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Public Class MyMailClient
Private m_arUidl As ArrayList = New ArrayList
Private m_uidlfile As String = "uidl.txt"
Private m_curpath As String = ""
#Region "UIDL Functions"
' uidl is the identifier of every email on POP3/IMAP4 server, to avoid
' retrieve the same email from server more than once, we record the
' email uidl retrieved every time if you delete the email from server
' every time and not to leave a copy of email on the server, then please
' remove all the function about uidl.
Private Function _FindUIDL(ByVal infos() As MailInfo, ByVal uidl As String) As Boolean
Dim count As Integer = infos.Length
For i As Integer = 0 To count - 1
If String.Compare(infos(i).UIDL, uidl, False) = 0 Then
_FindUIDL = True
Exit Function
End If
Next
_FindUIDL = False
End Function
'remove the local uidl which is not existed on the server.
Private Sub _SyncUIDL(ByVal oServer As MailServer, ByVal infos() As MailInfo)
Dim s As String = String.Format("{0}#{1} ", oServer.Server, oServer.User)
Dim bcontinue As Boolean = False
Dim n As Integer = 0
Do
bcontinue = False
Dim count As Integer = m_arUidl.Count
For i As Integer = n To count - 1
Dim x As String = m_arUidl(i)
If String.Compare(s, 0, x, 0, s.Length, True) = 0 Then
Dim pos As Integer = x.LastIndexOf(" ")
If pos <> -1 Then
Dim uidl As String = x.Substring(pos + 1)
If (Not _FindUIDL(infos, uidl)) Then
'this uidl doesn't exist on server,
'we should remove it from local uidl list.
bcontinue = True
n = i
m_arUidl.RemoveAt(i)
Exit For
End If
End If
End If
Next
Loop While (bcontinue)
End Sub
Private Function _FindExistedUIDL(ByVal oServer As MailServer, _
ByVal uidl As String) As Boolean
Dim s As String = String.Format("{0}#{1} {2}", _
oServer.Server.ToLower(), oServer.User.ToLower(), uidl)
Dim count As Integer = m_arUidl.Count
For i As Integer = 0 To count - 1
Dim x As String = m_arUidl(i)
If String.Compare(s, x, False) = 0 Then
_FindExistedUIDL = True
Exit Function
End If
Next
_FindExistedUIDL = False
End Function
Private Sub _AddUIDL(ByVal oServer As MailServer, ByVal uidl As String)
Dim s As String = String.Format("{0}#{1} {2}", _
oServer.Server.ToLower(), oServer.User.ToLower(), uidl)
m_arUidl.Add(s)
End Sub
Private Sub _UpdateUIDL()
Dim s As New StringBuilder
Dim count As Integer = m_arUidl.Count
For i As Integer = 0 To count - 1
s.Append(m_arUidl(i))
s.Append(vbCrLf)
Next
Dim file As String = String.Format("{0}\{1}", m_curpath, m_uidlfile)
Dim fs As FileStream = Nothing
Try
fs = New FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)
Dim data() As Byte = System.Text.Encoding.Default.GetBytes(s.ToString())
fs.Write(data, 0, data.Length)
fs.Close()
Catch ep As Exception
If Not (fs Is Nothing) Then
fs.Close()
End If
Throw ep
End Try
End Sub
Private Sub _LoadUIDL()
m_arUidl.Clear()
Dim filename As String = String.Format("{0}\{1}", m_curpath, m_uidlfile)
Dim read As StreamReader = Nothing
Try
read = File.OpenText(filename)
Do While (True)
Dim line As String = read.ReadLine().Trim(vbCrLf & " " & vbTab.ToCharArray())
m_arUidl.Add(line)
Loop
Catch ep As Exception
End Try
If Not (read Is Nothing) Then
read.Close()
End If
End Sub
#End Region
Public Sub ReceiveEmail(ByVal oServer As MailServer, ByVal bLeaveCopy As Boolean)
Dim oClient As New MailClient("TryIt")
m_curpath = Directory.GetCurrentDirectory()
Try
' uidl is the identifier of every email on POP3/IMAP4 server, to
' avoid retrieve the same email from server more than once,
' we record the email uidl retrieved every time if you delete the
' email from server every time and not to leave a copy of email on
' the server, then please remove all the function about uidl.
_LoadUIDL()
Dim mailFolder As String = [String].Format("{0}\inbox", m_curpath)
If Not Directory.Exists(mailFolder) Then
Directory.CreateDirectory(mailFolder)
End If
Console.WriteLine("Connecting server ... ")
oClient.Connect(oServer)
Dim infos As MailInfo() = oClient.GetMailInfos()
Console.WriteLine("Total {0} email(s)", infos.Length)
_SyncUIDL(oServer, infos)
Dim count As Integer = infos.Length
For i As Integer = 0 To count - 1
Dim info As MailInfo = infos(i)
If _FindExistedUIDL(oServer, info.UIDL) Then
'this email has existed on local disk.
Continue For
End If
Console.WriteLine("Retrieving {0}/{1}...", info.Index, count)
Dim oMail As Mail = oClient.GetMail(info)
Dim d As System.DateTime = System.DateTime.Now
Dim cur As New System.Globalization.CultureInfo("en-US")
Dim sdate As String = d.ToString("yyyyMMddHHmmss", cur)
Dim fileName As String = [String].Format("{0}\{1}{2}{3}.eml", _
mailFolder, sdate, d.Millisecond.ToString("d3"), i)
oMail.SaveAs(fileName, True)
If bLeaveCopy Then
'add the email uidl to uidl file to avoid we retrieve it next time.
_AddUIDL(oServer, info.UIDL)
End If
Next
If Not bLeaveCopy Then
Console.WriteLine("Deleting ...")
For i As Integer = 0 To count - 1
oClient.Delete(infos(i))
Next
End If
Console.WriteLine("Completed")
oClient.Quit()
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
'update the uidl list to a text file and then we can load it next time.
_UpdateUIDL()
End Sub
End Class
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
Dim oServer As New MailServer("pop3.emailarchitect.net", _
"test@emailarchitect.net", "testpassword", ServerProtocol.Pop3)
Dim oClient As New MailClient("TryIt")
'if your POP3 server requires SSL connection,
'please add the following codes:
'oServer.SSLConnection = True
'oServer.Port = 995
Dim MyClient As New MyMailClient
MyClient.ReceiveEmail(oServer, True)
End Sub
End Module
Parse email
After you received the emails to the local folder, we can use the following code to parse the email now. The following code demonstrates how to parse from, to, cc, subject, body text, attachments of all emails file received by previous sample.
'[VB.NET Example - Parse Email]
Imports System.Collections
Imports System.Text
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Private Sub ParseEmail(ByVal emlFile As String)
Dim oMail As New Mail("TryIt")
oMail.Load(emlFile, False)
'Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString())
'Parse Mail To/Recipient
Dim addrs As MailAddress() = oMail.[To]
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail CC
addrs = oMail.Cc
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject)
'Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody)
'Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody)
'Parse Attachments
Dim atts As Attachment() = oMail.Attachments
For i As Integer = 0 To atts.Length - 1
Console.WriteLine("Attachment: {0}", atts(i).Name)
Next
End Sub
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Get all *.eml files in specified folder and parse it one by one.
Dim files As String() = Directory.GetFiles(mailbox, "*.eml")
For i As Integer = 0 To files.Length - 1
ParseEmail(files(i))
Next
End Sub
End Module
TextBody and HtmlBody
Not every email has both text/plain body text and html body text. However, Mail object provides both TextBody and HtmlBody properties smartly. If the email has only text/plain body, then Mail object converts the text/plain body to html body automatically; if the email has only html body, then Mail object converts the html body to text/plain body automatically.
Verify digital signature and decrypt email in VB.NET
Digital signature prevents email content is faked or changed in transport level. Encrypting email protects email content from exposure to inappropriate recipients. Both digital signature and email encrypting depend on digital certificate.
How to sign email content?
Digital signature is always signed by sender certificate. The certificate used to sign email content MUST have the public/private key pair. First of all, the user MUST get a digital certificate for personal email protection from third-party certificate authorities such as www.verisign.com. After the certificate is installed on the machine, it can be viewed by "Control Panel"->"Internet Options"->"Content"->"Certificates"->"Personal". When you view the certificate, please note there is a line "You have a private key that corresponds to this certificate" in the certificate view, that means you are able to use this certificate to sign email content. If this line doesn't appear, that means you are unable to sign the email content by this certificate. To sign email content, please refer to EASendMail SMTP Component.
How to encrypt email?
Encrypting email doesn't require sender certificate but the certificate with public key for every recipient. For example, from@adminsystem.com sends an email to rcpt@adminsystem.com with digital signature. The digital signature contains the public key certificate for from@adminsystem.com, then rcpt@adminsystem.com can send an encrypted email with this certificate back to from@adminsystem.com. Only from@adminsystem can read this email, because this email MUST be decrypted by private key of from@adminsystem.com. Therefore, you MUST receive an digital signed email from other people (Most email clients such as outlook, outlook express will add the certificate to the Other People Storage automatically once an digital signed email is received) before you can send encrypted email to this people. To encrypt email, please refer to EASendMail SMTP Component.
Verify signed email and decrypt the encrypted email.
EAGetMail Mail class provides an easy way to verify the email digital signature and get the signer certificate. The signer certificate only contains the public key, that means you can add this certificate to your user certificate storage so that you can use this certificate to encrypt email and send the encrypted email back to the sender, only the sender can decrypt the email.
Please have a look at the following sample codes:
'[VB.NET Example - Verify digital signature and decrypt email]
Imports System.Collections
Imports System.Text
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Private Sub ParseEmail(ByVal emlFile As String)
Dim oMail As New Mail("TryIt")
oMail.Load(emlFile, False)
If oMail.IsEncrypted Then
Try
'this email is encrypted, we decrypt it by user default certificate.
' you can also use specified certificate like this
' Dim oCert As New Certificate()
' oCert.Load("c:\test.pfx", "pfxpassword", _
' Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
' oMail = oMail.Decrypt( oCert )
oMail = oMail.Decrypt(Nothing)
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End If
If oMail.IsSigned Then
Try
'this email is digital signed.
Dim cert As EAGetMail.Certificate = oMail.VerifySignature()
'you can add the certificate to your certificate storage like this
'cert.AddToStore( _
' Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
' "addressbook" )
' then you can use send the encrypted email back to this sender.
Console.WriteLine("This email contains a valid digital signature.")
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End If
'Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString())
'Parse Mail To/Recipient
Dim addrs As MailAddress() = oMail.[To]
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail CC
addrs = oMail.Cc
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject)
'Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody)
'Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody)
'Parse Attachments
Dim atts As Attachment() = oMail.Attachments
For i As Integer = 0 To atts.Length - 1
Console.WriteLine("Attachment: {0}", atts(i).Name)
Next
End Sub
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Get all *.eml files in specified folder and parse it one by one.
Dim files As String() = Directory.GetFiles(mailbox, "*.eml")
For i As Integer = 0 To files.Length - 1
ParseEmail(files(i))
Next
End Sub
End Module
Parse winmail.dat (TNEF) in VB.NET
When an Outlook user composes and sends a message using either Rich Text Format or HTML Format, Outlook automagically generates a file, winmail.dat, and attaches it to the end of the email. The winmail.dat contains the rich text body and original attachments. To parse winmail.dat (TNEF) file, we should use ParseTNEF method.
'[VB.NET Example - Parse winmail.dat (TNEF Parser)]
Imports System.Collections
Imports System.Text
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Private Sub ParseEmail(ByVal emlFile As String)
Dim oMail As New Mail("TryIt")
oMail.Load(emlFile, False)
If oMail.IsEncrypted Then
Try
'this email is encrypted, we decrypt it by user default certificate.
' you can also use specified certificate like this
' Dim oCert As New Certificate()
' oCert.Load("c:\test.pfx", "pfxpassword", _
' Certificate.CertificateKeyLocation.CRYPT_USER_KEYSET)
' oMail = oMail.Decrypt( oCert )
oMail = oMail.Decrypt(Nothing)
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End If
If oMail.IsSigned Then
Try
'this email is digital signed.
Dim cert As EAGetMail.Certificate = oMail.VerifySignature()
'you can add the certificate to your certificate storage like this
'cert.AddToStore( _
' Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
' "addressbook" )
' then you can use send the encrypted email back to this sender.
Console.WriteLine("This email contains a valid digital signature.")
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End If
'Parse Mail From/Sender
Console.WriteLine("From: {0}", oMail.From.ToString())
'Parse Mail To/Recipient
Dim addrs As MailAddress() = oMail.[To]
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail CC
addrs = oMail.Cc
For i As Integer = 0 To addrs.Length - 1
Console.WriteLine("To: {0}", addrs(i).ToString())
Next
'Parse Mail Subject
Console.WriteLine("Subject: {0}", oMail.Subject)
'Parse Mail Text/Plain body
Console.WriteLine("TextBody: {0}", oMail.TextBody)
'Parse Mail Html Body
Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody)
'Parse Attachments
Dim atts As Attachment() = oMail.Attachments
For i As Integer = 0 To atts.Length - 1
Dim att As Attachment = atts(i)
'this attachment is in OUTLOOK RTF format(TNEF), decode it here.
If [String].Compare(att.Name, "winmail.dat") = 0 Then
Dim tatts As Attachment() = Nothing
Try
tatts = Mail.ParseTNEF(att.Content, True)
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
Dim y As Integer = tatts.Length
For x As Integer = 0 To y - 1
Dim tatt As Attachment = tatts(x)
Console.WriteLine("winmail.dat: {0}", tatt.Name)
Next
Continue For
End If
Console.WriteLine("Attachment: {0}", att.Name)
Next
End Sub
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Get all *.eml files in specified folder and parse it one by one.
Dim files As String() = Directory.GetFiles(mailbox, "*.eml")
For i As Integer = 0 To files.Length - 1
ParseEmail(files(i))
Next
End Sub
End Module
Parse email to HTML page and display it in Web browser
Finally, I want to introduce a simple way to convert email file to HTML page. After the email was converted to HTML page, you can browse it with web browser. You can get everything in the HTML page such as From, To, Cc, Subject, Date, Attachments.
'[VB.NET Example - Convert Email to HTML]
Imports System.Collections
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace
Module Module1
Private Sub ConvertMailToHtml(ByVal fileName As String)
Try
Dim pos As Integer = fileName.LastIndexOf(".")
Dim mainName As String = fileName.Substring(0, pos)
Dim htmlName As String = mainName & ".htm"
Dim tempFolder As String = mainName
If Not File.Exists(htmlName) Then
'we haven't generate the html for this email, generate it now.
_GenerateHtmlForEmail(htmlName, fileName, tempFolder)
End If
Console.WriteLine("Please open {0} to browse your email", htmlName)
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End Sub
Private Function _FormatHtmlTag(ByVal src As String) As String
src = src.Replace(">", ">")
src = src.Replace("<", "<")
Return src
End Function
'we generate a html + attachment folder for every email, once the html is create,
' next time we don't need to parse the email again.
Private Sub _GenerateHtmlForEmail(ByVal htmlName As String, _
ByVal emlFile As String, ByVal tempFolder As String)
Dim oMail As New Mail("TryIt")
oMail.Load(emlFile, False)
If oMail.IsEncrypted Then
Try
'this email is encrypted, we decrypt it by user default certificate.
oMail = oMail.Decrypt(Nothing)
Catch ep As Exception
Console.WriteLine(ep.Message)
oMail.Load(emlFile, False)
End Try
End If
If oMail.IsSigned Then
Try
'this email is digital signed.
Dim cert As EAGetMail.Certificate = oMail.VerifySignature()
Console.WriteLine("This email contains a valid digital signature.")
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
End If
'Parse html body
Dim html As String = oMail.HtmlBody
Dim hdr As New StringBuilder()
'Parse sender
hdr.Append("<font face=""Courier New,Arial"" size=2>")
hdr.Append("<b>From:</b> " & _FormatHtmlTag(oMail.From.ToString()) & "<br>")
'Parse to
Dim addrs As MailAddress() = oMail.[To]
Dim count As Integer = addrs.Length
If count > 0 Then
hdr.Append("<b>To:</b> ")
For i As Integer = 0 To count - 1
hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
If i < count - 1 Then
hdr.Append(";")
End If
Next
hdr.Append("<br>")
End If
'Parse cc
addrs = oMail.Cc
count = addrs.Length
If count > 0 Then
hdr.Append("<b>Cc:</b> ")
For i As Integer = 0 To count - 1
hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
If i < count - 1 Then
hdr.Append(";")
End If
Next
hdr.Append("<br>")
End If
hdr.Append([String].Format("<b>Subject:</b>{0}<br>" & vbCr & vbLf, _
_FormatHtmlTag(oMail.Subject)))
'Parse attachments and save to local folder
Dim atts As Attachment() = oMail.Attachments
count = atts.Length
If count > 0 Then
If Not Directory.Exists(tempFolder) Then
Directory.CreateDirectory(tempFolder)
End If
hdr.Append("<b>Attachments:</b>")
For i As Integer = 0 To count - 1
Dim att As Attachment = atts(i)
'this attachment is in OUTLOOK RTF format, decode it here.
If String.Compare(att.Name, "winmail.dat") = 0 Then
Dim tatts As Attachment() = Nothing
Try
tatts = Mail.ParseTNEF(att.Content, True)
Catch ep As Exception
Console.WriteLine(ep.Message)
End Try
Dim y As Integer = tatts.Length
For x As Integer = 0 To y - 1
Dim tatt As Attachment = tatts(x)
Dim tattname As String = String.Format("{0}\{1}", _
tempFolder, tatt.Name)
tatt.SaveAs(tattname, True)
hdr.Append( _
String.Format("<a href=""{0}"" target=""_blank"">{1}</a> ", _
tattname, tatt.Name))
Next
Continue For
End If
Dim attname As String = String.Format("{0}\{1}", tempFolder, att.Name)
att.SaveAs(attname, True)
hdr.Append(String.Format("<a href=""{0}"" target=""_blank"">{1}</a> ", _
attname, att.Name))
If att.ContentID.Length > 0 Then
'show embedded images.
html = html.Replace("cid:" + att.ContentID, attname)
ElseIf [String].Compare(att.ContentType, 0, "image/", 0, _
"image/".Length, True) = 0 Then
'show attached images.
html = html & String.Format("<hr><img src=""{0}"">", attname)
End If
Next
End If
Dim reg As New Regex("(<meta[^>]*charset[ " & vbTab & "]*=[ " _
& vbTab & """]*)([^<> " & vbCr & vbLf & """]*)", _
RegexOptions.Multiline Or RegexOptions.IgnoreCase)
html = reg.Replace(html, "$1utf-8")
If Not reg.IsMatch(html) Then
hdr.Insert(0, _
"<meta HTTP-EQUIV=""Content-Type"" Content=""text-html; charset=utf-8"">")
End If
'write html to file
html = hdr.ToString() & "<hr>" & html
Dim fs As New FileStream(htmlName, FileMode.Create, FileAccess.Write, FileShare.None)
Dim data As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(html)
fs.Write(data, 0, data.Length)
fs.Close()
oMail.Clear()
End Sub
Sub Main()
'create a folder named "inbox" under current directory
' to save the email retrieved.
Dim curpath As String = Directory.GetCurrentDirectory()
Dim mailbox As String = [String].Format("{0}\inbox", curpath)
'if the folder is not existed, create it.
If Not Directory.Exists(mailbox) Then
Directory.CreateDirectory(mailbox)
End If
'Get all *.eml files in specified folder and parse it one by one.
Dim files As String() = Directory.GetFiles(mailbox, "*.eml")
For i As Integer = 0 To files.Length - 1
ConvertMailToHtml(files(i))
Next
End Sub
End Module
Total Sample Projects
After you downloaded the EAGetMail POP3 Component Installer and install it on your machine, there are many samples in the installation path.
| pop3_imap4_simple.vb6 | Receives and parses email from POP3 & IMAP4 with Visual Basic 6.0. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (VB6, ActiveX/COM) |
| pop3_imap4_simple.vb | Receives and parses email from POP3 & IMAP4 with Visual Basic.NET. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption.(VB.NET, .NET) |
| pop3_imap4_simple.csharp | Receives and parses email from POP3 & IMAP4 with CSharp.NET. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (C#, .NET) |
| pop3_imap4_simple.vc | Receives and parses email from POP3 & IMAP4 with Managed C++. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption.(Managed C++, .NET) |
| pop3_imap4_simple.vcNative | Receives and parses email from POP3 & IMAP4 with Native Visual C++. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (Visual C++, ActiveX/COM) |
| imap4_full.vb6 | Full functionality of IMAP4 including folder management, mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (VB6, ActiveX/COM) |
| imap4_full.vb | Full functionality of IMAP4 including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (V.NET, .NET) |
| imap4_full.csharp | Full functionality of IMAP4 including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verify and email decryption. (C#, .NET) |
| pocketpc.mobile.cs | Receives and parses email from POP3 & IMAP4 with CSharp.NET on Windows Mobile Platform.(C#, .NET) |
| pocketpc.mobile.vb | Receives and parses email from POP3 & IMAP4 with VB.NET on Windows Mobile Platform.(VB, .NET) |
| ParseEmail.js/ParseEmail.vbs | Parses email file by JScript/VBScript.(Jscript, VBScript, ActiveX/COM) |
| PreviewEmail.js/PreviewEmail.vbs | Download email header from POP3/IMAP4 server by JScript/VBScript.(Jscript, VBScript, ActiveX/COM) |
| asp | Receives and parses email from POP3 & IMAP4 with ASP.(ASP, VBScript, ActiveX/COM) |
| asp_queue | Receives email from POP3 & IMAP4 with EAGetMail Service.(ASP, VBScript, ActiveX/COM) |
| asp_net | Receives and parses email from POP3 & IMAP4 with ASP.NET.(ASP.NET, C#, .NET) |
| asp_net_queue | Receives email from POP3 & IMAP4 with EAGetMail Service.(ASP.NET, C#, .NET) |
Free Email Support
Not enough? Please contact our technical support team.
Support@EmailArchitect.NET
VIP@EmailArchitect.NET(Registered User)
Remarks
We usually reply emails in 24hours. The reason for getting no response is likely
that your smtp server bounced our reply. In this case, please try to use another
email address to contact us. Your Hotmail or Yahoo email account is recommended.
|