Retrieve Email and Parse Email in VB 6.0 - Tutorial

This tutorial introduces how to retrieve email and parse email in VB 6.0 using POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates retrieving email over SSL/TLS connection, verifying email digital signature, decrypting encrypted email (S/MIME), parsing email attachment, parsing non-delivery report (NDR) and managing mail folder.

Retrieve email in a simple VB 6.0 project

To better demonstrate how to retrieve email and parse email, let’s create a VB 6.0 Standard EXE project at first, then add a CommandButton on the Form, double-click this button. It is like this

VB 6.0 standard project

Installation

EAGetMail is a POP3 and IMAP4 component which supports all operations of POP3/IMAP4/MIME/Exchange Web Service/WebDAV/SSL/S/MIME protocol. Before you can use the following example codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Add Reference

To use EAGetMail POP3 & IMAP4 ActiveX Object in your project, the first step is Add reference of EAGetMail to your project. Please go to menu -> Project -> References -> and select EAGetMailObj ActiveX Object, click OK, the reference will be added to your project, and you can start to use it to retrieve email and parse email in your project.

add reference in VB6

[VB 6.0 Example - Retrieve email from POP3 server]

Now add the following codes to the project. The following codes demonstrate how to retrieve email from a POP3 mail account. It downloads emails from POP3 server and deletes the email after the email is retrieved.

In order to run it correctly, please change email server, user, password, folder, file name values.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 995

    ' If your POP3 doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 110

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from POP3 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

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.

c#/vb.net/vb/delphi/vc++ console email sample

Troubleshooting

When you retrieve email in above simple project, if it returned an error, please have a look at the following tips:

“No Such Host” Error

This error means DNS server cannot resolve POP3 server, you should check if you input correct server address. If your server address is correct, you should check if your DNS server setting is correct.

Common “Socket/Networking Connection” Error

This error means there is a problem with networking connection to POP3 server. You can use Windows built-in Telnet command to detect the networking connection.

Using Telnet to detect networking connection to POP3 server

Note

Notice: in Windows 2008/Windows 8 or later version, Telnet Client is not installed by default, you should enable this command in Control Panel -> Programs and Features -> Turn Windows feature on or off -> have Telnet Client checked.

Under DOS command prompt, input telnet [serveraddress] [port]

telnet mail.emailarchitect.net 110

If the networking connection to your POP3 server is good, it should return a message like +OK .... If it returns Could not open connection to ..., that means the networking connection to POP3 server is bad, or outbound 110 port is blocked by anti-virus software, firewall or ISP. Please have a look at the following screenshot:

detect POP3 connection using telnet

POP3 110, 995 port, IMAP4 143, 993 port and SSL

  • 110 port is the default POP3 server port to receive email. 995 port is the common POP3 SSL port used to receive email over implicit SSL connection.
  • 143 port is the default IMAP4 server port, 993 port is the common port for IMAP4 SSL.

If you use telnet to test 995/993 port, it doesn’t return the +OK..., because it requires SSL hand shake. If the connection is ok, telnet returns a flash cursor.

Now SSL is commonly used, many email servers require SSL connection such as Gmail, Outlook, Office 365 and Yahoo. In this case you should set MailServer.SSLConnection to true and change MailServer.Port to 995 (POP3) or 993 (IMAP4).

“-ERR user authentication” Error

This error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.

Other error returned by POP3 server

If POP3 server returns an error, it usually returns description about this error. You can use the following codes to generate a log file to learn all POP3 session between client and server.

[VB 6.0 - Using log file to detect POP3 server response - Example]

oClient.LogFileName = "d:\pop3.txt"

TLS 1.2

TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

32bit/x64 ActiveX DLL

Seperate builds of run-time dll for 32 and x64 platform

File Platform
Installation Path\Lib\native\x86\EAGetMailObj.dll 32 bit
Installation Path\Lib\native\x64\EAGetMailObj.dll 64 bit

Distribution

  • Standard EXE

    For VB6, C++, Delphi or other standard exe application, you can distribute EAGetMailObj.dll with your application to target machine without COM-registration and installer. To learn more detail, please have a look at Registration-free COM with Manifest File.

  • Script

    For ASP, VBScript, VBA, MS SQL Stored Procedure, you need to install EAGetMail on target machine by EAGetMail installer, both 32bit/x64 DLL are installed and registered.

Next Section

In this section, I introduced retrieving email in VB 6.0 with POP3 protocol. At next section I will introduce how to retrieve email from IMAP4 server.

Retrieve Email from IMAP4 server in VB 6.0

In previous section, I introduced retrieving email from POP3 server in VB 6.0. In this section, I will introduce the IMAP4 server.

Introduction

IMAP4 protocol is different with POP3 protocol. First of all, IMAP4 supports retrieving email from different mail folder and folder management. Secondly, IMAP4 supports mail flags management. Therefore, we can do more things with IMAP4 server. To better understand the IMAP4 protocol, please see the following examples.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email from IMAP4 inbox]

The following example codes demonstrate how to download email from IMAP4 server default mailbox. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap4.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 993

    ' If your IMAP doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 143

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from IMAP4 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Because IMAP4 protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.

[VB 6.0 Example - Retrieve email from “Deleted Items”]

The following example codes demonstrate how to retrieve emails from “Deleted Items” in an IMAP4 account. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Function FindFolder(ByVal FolderPath As String, ByRef folders As FolderCollection)
    Dim i As Long
    For i = 0 To folders.Count - 1
        Dim oFolder As Imap4Folder
        Set oFolder = folders.Item(i)
        If StrComp(oFolder.LocalPath, FolderPath, 1) = 0 Then
            Set FindFolder = oFolder
            Exit Function
        End If

        Set oFolder = FindFolder(FolderPath, oFolder.SubFolderList)
        If Not (oFolder Is Nothing) Then
            Set FindFolder = oFolder
            Exit Function
        End If
    Next

    Set FindFolder = Nothing
End Function

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap4.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 993

    ' If your IMAP doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 143

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' Lookup folder based name,
    Dim folder As Imap4Folder
    ' If you want search sub folder, use parentfolder\subfolder
    ' For example: INBOX\MySubFolder
    Set folder = FindFolder("Deleted Items", oClient.GetFolderList())
    If folder Is Nothing Then
        Err.Raise 2, "ImapFolder", "Folder was not found"
    End If

    ' Select this folder
    oClient.SelectFolder folder

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from IMAP4 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

TLS 1.2

TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Next Section

At next section I will introduce how to retrieve email from Exchange Server with Web Service protocol.

Retrieve Email from Exchange Server with Web Service (EWS) in VB 6.0

In previous section, I introduced how to retrieve email from IMAP4 server. In this section, I will introduce the Exchange Web Service (EWS) protocol (Exchange 2007-2019/Office365).

Introduction

Exchange Web Service (EWS) protocol is similar with IMAP4 protocol. First of all, it supports retrieving email from different mail folder and folder management. Secondly, Exchange Web Service supports mail read flag management. Therefore, we can do more things with Exchange server. To better understand the Exchange Web Service protocol, please see the following examples.

Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 or later version, POP3/IMAP4 service is disabled by default. If you don’t want to use POP3/IMAP4 to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010/2013/2016 or later version) or WebDAV (Exchange 2000/2003) protocol.

Office 365 also supports EWS protocol.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email from Exchange INBOX]

The following example codes demonstrate how to download email from Exchange 2007/2010/2013/2016 server default mailbox using EWS protocol. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    ' Please use domain\user as the user name
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "exch.emailarchitect.net"

    oServer.User = "emailarchitect.net\test"
    oServer.Password = "testpassword"

    oServer.Protocol = MailServerEWS

    ' By default, Exchange Web Service (EWS) requires SSL connection
    ' Please ignore Port property for EWS and WebDAV protocol
    oServer.SSLConnection = True

    On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Exchange server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Delete email from Exchange server.
        oClient.Delete info
    Next

    ' Quit from Exchange server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Because Exchange Web Service protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.

[VB 6.0 Example - Retrieve email from “Deleted Items”]

The following example codes demonstrate how to retrieve emails from “Deleted Items” in an Exchange account.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Function FindFolder(ByVal FolderPath As String, ByRef folders As FolderCollection)
    Dim i As Long
    For i = 0 To folders.Count - 1
        Dim oFolder As Imap4Folder
        Set oFolder = folders.Item(i)
        If StrComp(oFolder.LocalPath, FolderPath, 1) = 0 Then
            Set FindFolder = oFolder
            Exit Function
        End If

        Set oFolder = FindFolder(FolderPath, oFolder.SubFolderList)
        If Not (oFolder Is Nothing) Then
            Set FindFolder = oFolder
            Exit Function
        End If
    Next

    Set FindFolder = Nothing
End Function

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    ' Please use domain\user as the user name
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "exch.emailarchitect.net"

    oServer.User = "emailarchitect.net\test"
    oServer.Password = "testpassword"

    oServer.Protocol = MailServerEWS

    ' By default, Exchange Web Service (EWS) requires SSL connection
    ' Please ignore Port property for EWS and WebDAV protocol
    oServer.SSLConnection = True

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' Lookup folder based name,
    Dim folder As Imap4Folder
    ' If you want search sub folder, use parentfolder\subfolder
    ' For example: INBOX\MySubFolder
    Set folder = FindFolder("Deleted Items", oClient.GetFolderList())
    If folder Is Nothing Then
        Err.Raise 2, "ImapFolder", "Folder was not found"
    End If

    ' Select this folder
    oClient.SelectFolder folder

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Exchange server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Delete email from Exchange server.
        oClient.Delete info
    Next

    ' Quit from Exchange server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to retrieve email from Exchange Server with WebDAV protocol.

Retrieve Email from Exchange Server with WebDAV protocol in VB 6.0

In previous section, I introduced how to retrieve email from Exchange Server with Web Service (EWS) protocol in VB 6.0. In this section, I will introduce the WebDAV protocol (Exchange 2000/2003).

Introduction

Exchange WebDAV protocol is similar with IMAP4 protocol. First of all, it supports retrieving email from different mail folder and folder management. Secondly, Exchange WebDAV supports mail read flag management. Therefore, we can do more things with Exchange server. To better understand the WebDAV protocol, please see the following examples.

Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007 or later version, POP3/IMAP4 service is disabled by default. If you don’t want to use POP3/IMAP4 to download email from Exchange Server, you can use Exchange Web Service (Exchange 2007/2010 or later version) or WebDAV (Exchange 2000/2003) protocol.

For Exchange Server 2007 or later version, WebDAV service is also disabled by default, so please use Exchange Web Service (EWS) instead of WebDAV protocol.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email from Exchange Inbox]

The following example codes demonstrate how to use EAGetMail to download email from Exchange server default mailbox using WebDAV protocol. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    ' Please use domain\user as the user name
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "exch.emailarchitect.net"

    oServer.User = "emailarchitect.net\test"
    oServer.Password = "testpassword"

    oServer.Protocol = MailServerDAV

    ' If your Exchange WebDAV server requires SSL connection,
    ' Please add the following codes:
    ' oServer.SSLConnection = True

    On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Exchange server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Delete email from Exchange server.
        oClient.Delete info
    Next

    ' Quit from Exchange server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Because Exchange WebDAV protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”. POP3 protocol doesn’t support this feature.

[VB 6.0 Example - Retrieve email from “Deleted Items”]

The following example codes demonstrate how to retrieve emails from “Deleted Items” in an Exchange account.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Function FindFolder(ByVal FolderPath As String, ByRef folders As FolderCollection)
    Dim i As Long
    For i = 0 To folders.Count - 1
        Dim oFolder As Imap4Folder
        Set oFolder = folders.Item(i)
        If StrComp(oFolder.LocalPath, FolderPath, 1) = 0 Then
            Set FindFolder = oFolder
            Exit Function
        End If

        Set oFolder = FindFolder(FolderPath, oFolder.SubFolderList)
        If Not (oFolder Is Nothing) Then
            Set FindFolder = oFolder
            Exit Function
        End If
    Next

    Set FindFolder = Nothing
End Function

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    ' Please use domain\user as the user name
    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "exch.emailarchitect.net"

    oServer.User = "emailarchitect.net\test"
    oServer.Password = "testpassword"

    oServer.Protocol = MailServerDAV

    ' If your Exchange WebDAV server requires SSL connection,
    ' Please add the following codes:
    ' oServer.SSLConnection = True

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' Lookup folder based name,
    Dim folder As Imap4Folder
    ' If you want search sub folder, use parentfolder\subfolder
    ' For example: INBOX\MySubFolder
    Set folder = FindFolder("Deleted Items", oClient.GetFolderList())
    If folder Is Nothing Then
        Err.Raise 2, "ImapFolder", "Folder was not found"
    End If

    ' Select this folder
    oClient.SelectFolder folder

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Exchange server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Delete email from Exchange server.
        oClient.Delete info
    Next

    ' Quit from Exchange server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to retrieve email over SSL connection.

Retrieve Email over SSL connection in VB 6.0

In previous section, I introduced how to retrieve email from Exchange Server with WebDAV protocol. In this section, I will introduce how to retrieve email over SSL connection in VB 6.0.

SSL and TLS

SSL connection encrypts data between the email component and POP3 server or IMAP4 server to protect user, password and email content in TCP/IP level. Now this technology is commonly used and many email servers are deployed with SSL such as Gmail, Yahoo and Hotmail.

There are two ways to deploy SSL on email server:

  • Implicit SSL

    Deploying SSL on another port (POP3: 995 port or IMAP4: 993 port) directly. This is most common way.

  • Explicit SSL (TLS)

    Using STARTTLS or STLS command to switch SSL channel on normal port (POP3: 110 port or IMAP4: 143 port);

TLS 1.2

TLS is the successor of SSL, EAGetMail supports SSL 3.0/TLS1.0 - 1.2 very well. In EAGetMail, ConnectTLS doesn’t mean TLS encryption, it means TLS command in POP3/IMAP protocol.

You don’t have to set any property to enable TLS 1.2 encryption. If your server requires TLS 1.2 encryption, TLS 1.2 encryption is used automatically with ConnectTLS, ConnectSSL or ConnectSSLAuto.

To enable TLS 1.2 on some legacy systems, you have to install required update/packages:

Enable TLS 1.2 on Windows XP/2003/2008/7/2008 R2

EAGetMail POP3 component supports both Implicit SSL and Explicit SSL.

For Exchange Web Service/WebDAV protocol, the SSL is based on HTTPS connection, so you just need to set SSLConnection property and simply ignore Port property. Notice: Exchange Web Service requires SSL connection by default.

[VB 6.0 Example - SSL/TLS]

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const ConnectSSLAuto = 0
Const ConnectSSL = 1
Const ConnectTLS = 2

' Retrieve email by normal TCP/IP without SSL connection
' POP3
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "pop3.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerPop3
oServer.Port = 110

' IMAP4
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "imap4.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerImap4
oServer.Port = 143

' Retrieve email over SSL connection with direct SSL.
' POP3 SSL
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "pop3.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerPop3
oServer.SSLConnection = True
oServer.Port = 995

' IMAP4 SSL
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "imap4.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerImap4
oServer.SSLConnection = True
oServer.Port = 993

' Retrieve email by SSL connection with STARTTLS or TLS command switching
' POP3 TLS
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "pop3.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerPop3
oServer.SSLConnection = True
oServer.Port = 110
oServer.SSLType = ConnectTLS

' IMAP4 STARTTLS
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "imap4.emailarchitect.net"
oServer.User = "test@emailarchitect.net"
oServer.Password = "testpassword"
oServer.Protocol = MailServerImap4
oServer.SSLConnection = True
oServer.Port = 143
oServer.SSLType = ConnectTLS

' Exchange WebDAV
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "exch.emailarchitect.net"
oServer.User = "emailarchitect.net\test"
oServer.Password = "testpassword"
oServer.Protocol = MailServerDAV

' Exchange Web Service SSL
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "exch.emailarchitect.net"
oServer.User = "emailarchitect.net\test"
oServer.Password = "testpassword"
oServer.Protocol = MailServerEWS
oServer.SSLConnection = True

' Exchange WebDAV SSL
Dim oServer As New EAGetMailObjLib.MailServer
oServer.Server = "exch.emailarchitect.net"
oServer.User = "emailarchitect.net\test"
oServer.Password = "testpassword"
oServer.Protocol = MailServerDAV
oServer.SSLConnection = True

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email from POP3 server over SSL on 995 port]

The following example codes demonstrate how to retrieve emails from POP3 server over SSL connection on 995 port. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 995 SSL Port
    oServer.Port = 995

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from POP3 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

[VB 6.0 Example - Retrieve email from IMAP4 server over SSL on 993 port]

The following example codes demonstrate how to retrieve emails from IMAP4 server over SSL connection on 993 port. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 IMAP4 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from IMAP4 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to download emails from Gmail account.

Download/Retrieve Email from Gmail account in VB 6.0

In previous section, I introduced how to retrieve email over SSL connection. In this section, I will introduce how to download email from your Gmail account in VB 6.0.

Introduction

Gmail POP3 server address is pop.gmail.com. It requires SSL connection on 995 port, and you should use your Gmail email address as the user name for user authentication.

Gmail IMAP4 server address is imap.gmail.com. It requires SSL connection on 993 port, and you should use your Gmail email address as the user name for user authentication. For example: your email is gmailid@gmail.com, and then the user name should be gmailid@gmail.com.

To retrieve email from Gmail account, you need to enable POP3 or IMAP4 access in your gmail account settings.

Because Gmail POP3 server doesn’t work like normal POP3 server, it hides old emails automatically even the email was not deleted, so we suggest that you use IMAP4 protocol.

Server Port SSL Protocol
pop.gmail.com 995 SSL required Pop3
imap.gmail.com 993 SSL required Imap4 (recommended)

Gmail App Password

To help keep your account secure, starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Therefore, you should sign in using App Passwords. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on. You need to use App Password instead of the user password for user authentication.

Another solution is Gmail OAUH, please see Gmail IMAP OAUTH section.

Last update: Google has disabled App password, you have to switch to Gmail IMAP OAUTH. If you don’t want to change your code, you can have a try with EA Oauth Service.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email from Gmail account]

The following example codes demonstrate how to download email from Gmail account using IMAP4 protocol.

Because Gmail POP3 server doesn’t work like normal POP3 server, it hides old emails automatically even the email was not deleted, so we suggest that you use IMAP4 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Gmail IMAP server address
    oServer.Server = "imap.gmail.com"
    oServer.User = "gmailid@gmail.com"

    ' Create app password in Google account
    ' https://support.google.com/accounts/answer/185833?hl=en
    oServer.Password = "your app password"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Gmail server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Gmail server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Gmail server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Gmail IMAP OAUTH

By default, you can generate an App Passwords, and use this app password instead of the user password for IMAP4 authentication.

However, Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.

[VB 6.0 Example - Retrieve Unread/New Email from Gmail Account]

Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Gmail like this

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const GetMailInfos_All = 1
Const GetMailInfos_NewOnly = 2
Const GetMailInfos_ReadOnly = 4
Const GetMailInfos_SeqRange = 8
Const GetMailInfos_UIDRange = 16
Const GetMailInfos_PR_ENTRYID = 32
Const GetMailInfos_DateRange = 64
Const GetMailInfos_OrderByDateTime = 128

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Gmail IMAP server address
    oServer.Server = "imap.gmail.com"
    oServer.User = "gmailid@gmail.com"

    ' Create app password in Google account
    ' https://support.google.com/accounts/answer/185833?hl=en
    oServer.Password = "your app password"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' retrieve unread/new email only
    oClient.GetMailInfosParam.Reset
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " unread emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Gmail server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' mark unread email as read, next time this email won't be retrieved again
        If Not info.Read Then
            oClient.MarkAsRead info, True
        End If

        ' if you don't want to leave a copy on server, please use
        ' oClient.Delete info
        ' instead of MarkAsRead
    Next

    ' Quit and expunge emails marked as deleted from Gmail server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

TLS 1.2

TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Next Section

At next section I will introduce how to download emails from Yahoo account.

Download/Retrieve Email from Yahoo account in VB 6.0

In previous section, I introduced how to download emails from Gmail account. In this section, I will introduce how to download emails from your Yahoo account in VB 6.0.

Introduction

Yahoo POP3 server address is pop.mail.yahoo.com. It requires SSL connection on 995 port; Yahoo IMAP4 server address is imap.mail.yahoo.com . It requires SSL connection on 993 port. You should use your Yahoo email address as the user name for user authentication. For example: your email is myid@yahoo.com, and then the user name should be myid@yahoo.com.

Server Port SSL Protocol
pop.mail.yahoo.com 995 SSL required Pop3
imap.mail.yahoo.com 993 SSL required Imap4

App Password

If you got authentication error, you need to enable Allowing less secure apps in your Yahoo account. Or you can generate an App Passwords and use this app password instead of the user password.

Although Yahoo supports OAUTH, but it doesn’t provide mail permission, so OAUTH is not a solution for Yahoo mail.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve emails from Yahoo account using POP3]

The following example codes demonstrate how to download emails from Yahoo account using POP3 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Yahoo POP3 server address is "pop.mail.yahoo.com"
    oServer.Server = "pop.mail.yahoo.com"
    oServer.User = "yahooid@yahoo.com"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 995 SSL Port
    oServer.Port = 995

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Yahoo POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Yahoo server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Yahoo POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

[VB 6.0 Example - Retrieve emails from Yahoo account using IMAP4]

The following example codes demonstrate how to download emails from Yahoo account using IMAP4 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Yahoo IMAP4 server address is "imap.mail.yahoo.com"
    oServer.Server = "imap.mail.yahoo.com"
    oServer.User = "yahooid@yahoo.com"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 IMAP4 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Yahoo IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Yahoo server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Yahoo IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

[VB 6.0 Example - Retrieve Unread/New Email from Yahoo Account]

Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Yahoo like this

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const MailServerMsGraph = 4

Const GetMailInfos_All = 1
Const GetMailInfos_NewOnly = 2
Const GetMailInfos_ReadOnly = 4
Const GetMailInfos_SeqRange = 8
Const GetMailInfos_UIDRange = 16
Const GetMailInfos_PR_ENTRYID = 32
Const GetMailInfos_DateRange = 64
Const GetMailInfos_OrderByDateTime = 128

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Yahoo IMAP4 server address is "imap.mail.yahoo.com"
    oServer.Server = "imap.mail.yahoo.com"
    oServer.User = "yahooid@yahoo.com"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' retrieve unread/new email only
    oClient.GetMailInfosParam.Reset
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " unread emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Yahoo IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' mark unread email as read, next time this email won't be retrieved again
        If Not info.Read Then
            oClient.MarkAsRead info, True
        End If

        ' if you don't want to leave a copy on server, please use
        ' oClient.Delete info
        ' instead of MarkAsRead
    Next

    ' Quit and expunge emails marked as deleted from Yahoo IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

TLS 1.2

TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Next Section

At next section I will introduce how to download emails from Hotmail/MSN Live/Office 365 account.

Download/Retrieve Email from Hotmail/Outlook/Live/Office 365 in VB 6.0

In previous section, I introduced how to download email from Yahoo account. In this section, I will introduce how to download email from Hotmail/MSN Live/Outlook.com/Office 365 account in VB 6.0.

Introduction

Hotmail/Outlook POP3 server address is outlook.office365.com. It requires SSL connection on 995 port; Hotmail/Outlook IMAP4 server address is outlook.office365.com. It requires SSL connection on 993 port;

You should use your Hotmail/Outlook email address as the user name for user authentication. For example: your email is liveid@hotmail.com, and then the user name should be liveid@hotmail.com.

Server Port SSL Protocol
outlook.office365.com 995 SSL required Pop3
outlook.office365.com 993 SSL required Imap4

App Password with Microsoft Account

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should create an App Passwords and use this App Password instead of the user password.

Another solution is using OAUH, please see Hotmail IMAP OAUTH section.

Last update: Microsoft has disabled App password, you have to switch to Hotmail IMAP OAUTH. If you don’t want to change your code, you can have a try with EA Oauth Service.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve emails from Hotmail/MSN Live/Outlook account using POP3]

The following example codes demonstrate how to download email from Hotmail/MSN Live/Outlook account using POP3 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Hotmail/MSN Live POP3 server address is "outlook.office365.com"
    oServer.Server = "outlook.office365.com"
    oServer.User = "hotmailid@hotmail.com"

    ' If you got authentication error, try to create an app password instead of your user password.
    ' https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
    oServer.Password = "your password or app password"
    oServer.Protocol = MailServerPop3

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 995 SSL Port
    oServer.Port = 995

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Hotmail/MSN Live POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Hotmail/MSN Live server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Hotmail/MSN Live POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

[VB 6.0 Example - Retrieve emails from Hotmail/MSN Live/Outlook account using IMAP4]

The following example codes demonstrate how to download email from Hotmail/MSN Live/Outlook account using IMAP4 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Hotmail/MSN Live IMAP4 server address is "outlook.office365.com"
    oServer.Server = "outlook.office365.com"
    oServer.User = "hotmailid@hotmail.com"

    ' If you got authentication error, try to create an app password instead of your user password.
    ' https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
    oServer.Password = "your password or app password"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 IMAP4 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Hotmail/MSN Live IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Hotmail/MSN Live server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Hotmail/MSN Live IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Hotmail IMAP OAUTH

Microsoft Live SMTP servers (Hotmail, Oultook personal account) have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.

Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.

Or you can generate App Passwords and use this app password instead of your user password.

Retrieve Email from Office 365

First of all, you should go to Office 365 Outlook -> Options -> See All Options -> Account -> My Account -> Settings for POP, IMAP, and SMTP access. You will get your Office 365 POP3/IMAP4 server address and port. The default POP3 server is outlook.office365.com on SSL 995 port; IMAP4 server is outlook.office365.com on SSL 993 port.

Important

Office 365 has started to disable user login in POP/IMAP protocol, you should use Office365 POP/IMAP/EWS OAUTH instead of traditional user/password login.

Server Port SSL Protocol
outlook.office365.com 995 SSL required Pop3
outlook.office365.com 993 SSL required Imap4

App Password and Office 365 OAUTH

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should create an App Passwords and use this App Password instead of the user password.

Office 365 has started to disable user login in POP/IMAP protocol, if basic authentication has been disabled in your tenant, you have to use Office365 POP/IMAP/EWS OAUTH.

Last update: Microsoft has disabled App password, you have to switch to Office365 POP/IMAP/EWS OAUTH. If you don’t want to change your code, you can have a try with EA Oauth Service.

[VB 6.0 Example - Retrieve emails from Office 365 account using IMAP4]

The following example codes demonstrate how to download email from Offic 365 account using IMAP4 protocol.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    ' Office 365 IMAP4 server address is "outlook.office365.com"
    oServer.Server = "outlook.office365.com"
    oServer.User = "user@domain"

    ' If you got authentication error, try to create an app password instead of your user password.
    ' https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
    oServer.Password = "your password or app password"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 IMAP4 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Office 365 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from Office 365 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from Office 365 IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

[VB 6.0 Example - Retrieve Unread/New Email from Hotmail/Outlook/Office 365]

Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from Hotmail/Outlook/Office 365 like this

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const GetMailInfos_All = 1
Const GetMailInfos_NewOnly = 2
Const GetMailInfos_ReadOnly = 4
Const GetMailInfos_SeqRange = 8
Const GetMailInfos_UIDRange = 16
Const GetMailInfos_PR_ENTRYID = 32
Const GetMailInfos_DateRange = 64
Const GetMailInfos_OrderByDateTime = 128

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer

    ' Hotmail/Outlook Live/Office365 IMAP4 server address is "outlook.office365.com"
    oServer.Server = "outlook.office365.com"
    oServer.User = "hotmailid@hotmail.com"

    ' If you got authentication error, try to create an app password instead of your user password.
    ' https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944
    oServer.Password = "your password or app password"
    oServer.Protocol = MailServerImap4

    ' Enable SSL Connection
    oServer.SSLConnection = True

    ' Set 993 SSL Port
    oServer.Port = 993

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' retrieve unread/new email only
    oClient.GetMailInfosParam.Reset
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " unread emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from Hotmail/MSN Live POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' mark unread email as read, next time this email won't be retrieved again
        If Not info.Read Then
            oClient.MarkAsRead info, True
        End If

        ' if you don't want to leave a copy on server, please use
        ' oClient.Delete info
        ' instead of MarkAsRead
    Next

    ' Quit and expunge emails marked as deleted from Hotmail/MSN Live POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Office365 POP/IMAP/EWS OAUTH

Microsoft Office365 servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application.

Microsoft will disable traditional user authentication in the future, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.

TLS 1.2

TLS is the successor of SSL, more and more Email servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Next Section

At next section I will introduce how to retrieve email with event handler.

Retrieve Email with Event Handler in VB 6.0

In previous section, I introduced how to retrieve email from Hotmail/MSN Live account. In this section, I will introduce how to retrieve email with event handler in VB 6.0.

Introduction

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.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email with event handler]

The following example codes demonstrate how to use EAGetMail POP3 component to retrieve email with event handler. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit
Private WithEvents oClient As EAGetMailObjLib.MailClient

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

' 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
Private Sub oClient_OnAuthorized(ByVal oSender As Object, Cancel As Boolean)
    Debug.Print "Authorized"
End Sub

Private Sub oClient_OnConnected(ByVal oSender As Object, Cancel As Boolean)
    Debug.Print "Connected"
End Sub

Private Sub oClient_OnIdle(ByVal oSender As Object, Cancel As Boolean)
    DoEvents
End Sub

Private Sub oClient_OnQuit(ByVal oSender As Object, Cancel As Boolean)
    Debug.Print "Quit"
End Sub

Private Sub oClient_OnReceivingDataStream(ByVal oSender As Object, _
ByVal oInfo As Object, ByVal Received As Long, ByVal Total As Long, Cancel As Boolean)
    Dim info As EAGetMailObjLib.MailInfo
    Set info = oInfo
    Debug.Print "Receiving " & info.Index & ", " & Received & "/" & Total & "..."
End Sub

Private Sub oClient_OnSecuring(ByVal oSender As Object, Cancel As Boolean)
    Debug.Print "Securing ..."
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 995

    ' If your POP3 doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 110

On Error GoTo ErrorHandle:

    If oClient Is Nothing Then
        Set oClient = New EAGetMailObjLib.MailClient
        oClient.LicenseCode = "TryIt"
    End If

    oClient.Connect oServer

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from POP3 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

        ' Mark email as deleted from POP3 server.
        oClient.Delete info
    Next

    ' Quit and expunge emails marked as deleted from POP3 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to use UIDL function to mark the email has been downloaded.

Using UIDL Function to Mark the Email has been downloaded/read in VB 6.0

In previous section, I introduced how to use event handler. In this section, I will introduce how to use UIDL function to mark the email has been downloaded in VB 6.0.

Introduction

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.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - 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. In order to run it correctly, please change email server, user, password, folder, file name values.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim currentPath As String
    Dim localInbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    currentPath = App.Path
    localInbox = currentPath & "\inbox"
    oTools.CreateFolder localInbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap4.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 993

    ' If your IMAP doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 143

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        Dim fileName As String

        ' Using IMAP UIDL as the file name.
        fileName = localInbox & "\" & info.UIDL & ".eml"
        If oTools.ExistFile(fileName) Then
            ' This email has been downloaded, do not receive it again.
        Else

            ' Receive email from POP3 server
            Dim oMail As EAGetMailObjLib.Mail
            Set oMail = oClient.GetMail(info)

            MsgBox "From: " & oMail.From.Address & _
                vbCrLf & "Subject: " & oMail.Subject

            ' Save email to local disk
            oMail.SaveAs fileName, True
        End If

        ' Do not delete email from IMAP4 server.
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

POP3/IMAP4/Exchange Web Service/WebDAV 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.

UIDL is also unique in Exchange Web Service/WebDAV, but the UIDL is string but not integer. UIDL in Exchange server may contain invalid characters for file name, so we cannot use UIDL as the file name either.

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/Exchange Web Service/WebDAV protocol.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private oTools As New EAGetMailObjLib.Tools

Private Sub Command1_Click()
    Dim currentPath As String
    Dim localInbox As String
    Dim isUidlLoaded As Boolean

    isUidlLoaded = False

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    currentPath = App.Path
    localInbox = currentPath & "\inbox"

    oTools.CreateFolder localInbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 995

    ' If your POP3 doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 110

On Error GoTo ErrorHandle:
    Dim leaveCopy As Boolean
    leaveCopy = True

    ' 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.
    ' If you want to re-download all emails, please delete uidl.txt from local inbox.
    Dim oUIDLManager As New EAGetMailObjLib.UIDLManager
    oUIDLManager.Load localInbox & "\uidl.txt"
    isUidlLoaded = True

    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()

    MsgBox infos.Count & " emails"

    ' Remove the local uidl that is not existed on the server,
    oUIDLManager.SyncUIDLEX oServer, infos
    ' Update result back to uidl file
    oUIDLManager.Update

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        Dim oUIDLItem As UIDLItem
        Set oUIDLItem = oUIDLManager.FindUIDL(oServer, info.UIDL)

        ' If this email has not been retrieved before, then get it
        If oUIDLItem Is Nothing Then

            Dim fileName As String
            fileName = oTools.GenFileName(i) & ".eml"

            Dim fullFileName As String
            fullFileName = localInbox & "\" & fileName

            Dim oMail As EAGetMailObjLib.Mail
            Set oMail = oClient.GetMail(info)
            oMail.SaveAs fullFileName, True

            If leaveCopy Then
                ' Add the email uidl to uidl file to avoid we retrieve it next time.
                oUIDLManager.AddUIDL oServer, info.UIDL, fileName
            Else
                oClient.Delete info

                ' Remove UIDL from local uidl file.
                oUIDLManager.RemoveUIDL oServer, info.UIDL
            End If
        End If
    Next

    ' Quit
    oClient.Quit

    ' Update the uidl list to a text file and then we can load it next time.
    oUIDLManager.Update
    Exit Sub

ErrorHandle:

    MsgBox Err.Description
    If isUidlLoaded Then
        ' Update the uidl list to a text file and then we can load it next time.
        oUIDLManager.Update
    End If
End Sub

UIDLManager Object

With EAGetMail 4.0, it provides a new class named “UIDLManager”. This object provides an easy way to maintain UIDL between your server and your local client. How does it work? It stores UIDL collection to a local disk file and you can use this object to add, remove and search UIDL with this local file. Then you don’t have to handle UIDL in your code. Please click here to learn more detail.

Mark Email as Read on IMAP4/Exchange Server

With IMAP4/Exchange Web Service/WebDAV protocol, you can also mark the email as read on the server, but POP3 doesn’t support this feature. Please refer to MarkAsRead method to learn more detail.

[VB 6.0 Example - Retrieve Unread/New Email in IMAP4/EWS/WebDAV]

Because IMAP/EWS/WebDAV support read mail flag, with this feature, we can also retrieve unread/new email only from IMAP4/EWS/WebDAV like this

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Const GetMailInfos_All = 1
Const GetMailInfos_NewOnly = 2
Const GetMailInfos_ReadOnly = 4
Const GetMailInfos_SeqRange = 8
Const GetMailInfos_UIDRange = 16
Const GetMailInfos_PR_ENTRYID = 32
Const GetMailInfos_DateRange = 64
Const GetMailInfos_OrderByDateTime = 128

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 993

    ' If your IMAP doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 143

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    ' retrieve unread/new email only
    oClient.GetMailInfosParam.Reset
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

    Dim infos As EAGetMailObjLib.MailInfoCollection
    Set infos = oClient.GetMailInfoList()
    MsgBox infos.Count & " unread emails"

    Dim i As Long
    For i = 0 To infos.Count - 1
        Dim info As EAGetMailObjLib.MailInfo
        Set info = infos.Item(i)

        MsgBox "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

        ' Receive email from IMAP4 server
        Dim oMail As EAGetMailObjLib.Mail
        Set oMail = oClient.GetMail(info)

        MsgBox "From: " & oMail.From.Address & _
            vbCrLf & "Subject: " & oMail.Subject

        Dim fileName As String
        ' Generate a random file name by current local datetime,
        ' You can use your method to generate the filename if you do not like it
        fileName = mailbox & "\" & oTools.GenFileName(i) & ".eml"

        ' Save email to local disk
        oMail.SaveAs fileName, True

         ' mark unread email as read, next time this email won't be retrieved again
        If Not info.Read Then
            oClient.MarkAsRead info, True
        End If

        ' if you don't want to leave a copy on server, please use
        ' oClient.Delete info
        ' instead of MarkAsRead
    Next

    ' Quit and expunge emails marked as deleted from IMAP4 server.
    oClient.Quit
    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to download email in background.

Download Email with Background Service in VB 6.0

In previous section, I introduced how to use UIDL function to mark the email has been downloaded. In this section, I will introduce how to download email with background service in VB 6.0.

Introduction

In an ASP/ASP.NET email application, if email download takes longer than the timeout value (in seconds) that the current asp page is allowed to run, user will get an error “ASP Timeout”. This often happens when user has a large quantity of emails to download or user downloads emails via a slow connection. By default the timeout is set to 90 seconds, it is easy to exceed this limit.

Obviously, a solution to ASP timeout is to set ASPScriptTimeout a larger value. You may click here for details. Technically the timeout problem can be solved in this way; however, some users may get frustrated and press the stop button on the browser toolbar as he waits too long.

EAGetMail POP3 Component introduces a more intelligent method to retrieve emails in background. You should download the EAGetMail Service installer and install it on your machine at first. Then you can use MailClient.GetMailsByQueue method to send the request to EAGetMail Service, the method returns to the user immediately and the EAGetMail Service performs task in background.

Important

To run the following example, you need to download EAGetMail and EAGetMail Service at first, and then install both on your machine.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Retrieve email with background service]

The following example codes demonstrate how to use EAGetMail POP3 component to retrieve email with background service. In order to run it correctly, please change email server, user, password, folder, file name values.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "pop3.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerPop3

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 995

    ' If your POP3 doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 110

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    ' Leave a copy of message on server.
    Dim leaveCopy As Boolean
    leaveCopy = True

    ' Download emails to this local folder
    Dim downloadFolder As String
    downloadFolder = mailbox

    ' Send request to EAGetMail Service, then EAGetMail Service retrieves email
    ' in background and this method returns immediately.
    oClient.GetMailsByQueue oServer, downloadFolder, leaveCopy

    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Scheduled to retrieve emails

EAGetMail Service provides another advanced feature which allow you set a POP3/IMAP4 account in the EAGetMail Service Manager. EAGetMail Service can download emails from this account in specified time interval. If you need to process the email in the mailbox on a regular basis, you just need to create your mail process application, you don’t need to write your email download task part.

Finally you just need to set your mail account in EAGetMail Service Manager and specify your application or COMMAND, EAGetMail service will download the emails and invoke your application automatically. Please refer to Mail Pull for more detail.

I also suggest that you have a look at Parse Non-Delivery Report (NDR) using EAGetMail Service. It demonstrates how to set a schedule to check a mailbox and insert non-delivery report to SQL database.

Next Section

At next section I will introduce how to parse email in VB 6.0.

Parse Email in VB 6.0

In previous section, I introduced how to download email with background service. In this section, I will introduce how to parse email in VB 6.0.

Introduction

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.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Parse email]

The following example codes demonstrate how to use EAGetMail POP3 component to parse email sender, to, cc, subject, body text and attachments.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Private Sub ParseEmail(ByVal emlFile As String)
    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"

On Error GoTo ErrorHandle
    oMail.LoadFile emlFile, False

    ' Parse email sender
    MsgBox "From: " & oMail.From.Address

    Dim addressList As EAGetMailObjLib.AddressCollection
    Dim i As Long
    Dim addr As EAGetMailObjLib.MailAddress

    ' Parse email to recipients
    Set addressList = oMail.ToList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "To: " & addr.Address
    Next

    ' Parse email cc
    Set addressList = oMail.CcList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "Cc: " & addr.Address
    Next

    ' Parse email subject
    MsgBox "Subject: " & oMail.Subject

    ' Parse email text body
    MsgBox "Text body: " & oMail.TextBody

    ' Parse email HTML body
    MsgBox "Html body: " & oMail.HtmlBody

    ' Parse attachments
    Dim atts As EAGetMailObjLib.AttachmentCollection
    Dim att As EAGetMailObjLib.Attachment

    Set atts = oMail.AttachmentList
    For i = 0 To atts.Count - 1
        Set att = atts.Item(i)
        MsgBox "Attachment: " & att.name
        ' Save attachment to local file.
        att.SaveAs App.Path & "\inbox\" & att.name, True
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and parse it one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ParseEmail files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

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.

Next Section

At next section I will introduce how to verify digital signature and decrypt email.

Verify Digital Signature and Decrypt Email in VB 6.0 - S/MIME

In previous section, I introduced how to parse email. In this section, I will introduce how to verify digital signature and decrypt email in VB 6.0.

Introduction

How to sign email?

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.

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.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Verify digital signature and decrypt email]

The following example codes demonstrate how to use EAGetMail POP3 component to verify digital signature and decrypt email.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096
Const CERT_SYSTEM_STORE_CURRENT_USER = 65536
Const CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072

Private Sub ParseEmail(ByVal emlFile As String)
    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"

On Error GoTo ErrorHandle
    oMail.LoadFile emlFile, False

    If oMail.IsEncrypted Then
        ' This email is encrypted, we decrypt it by user default certificate.
        ' You can also use specified certificate like this
        ' Dim oCert As New EAGetMailObjLib.Certificate
        ' oCert.LoadFromFile "c:\test.pfx", "pfxpassword", CRYPT_USER_KEYSET
        ' Set oMail = oMail.Decrypt(oCert)
        Set oMail = oMail.Decrypt(Nothing)
    End If

    If oMail.IsSigned Then
        ' This email is digital signed.
        Dim oCert As EAGetMailObjLib.Certificate
        Set oCert = oMail.VerifySignature
        MsgBox "This email contains a valid digital signature."
        ' You can add the certificate to your certificate storage like this
        ' oCert.AddToStore CERT_SYSTEM_STORE_CURRENT_USER, "addressbook"
        ' Then you can use send the encrypted email back to this sender.
    End If

    ' Parse email sender
    MsgBox "From: " & oMail.From.Address

    Dim addressList As EAGetMailObjLib.AddressCollection
    Dim i As Long
    Dim addr As EAGetMailObjLib.MailAddress

    ' Parse email to recipients
    Set addressList = oMail.ToList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "To: " & addr.Address
    Next

    ' Parse email cc
    Set addressList = oMail.CcList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "Cc: " & addr.Address
    Next

    ' Parse email subject
    MsgBox "Subject: " & oMail.Subject

    ' Parse email text body
    MsgBox "Text body: " & oMail.TextBody

    ' Parse email HTML body
    MsgBox "Html body: " & oMail.HtmlBody

    ' Parse attachments
    Dim atts As EAGetMailObjLib.AttachmentCollection
    Dim att As EAGetMailObjLib.Attachment

    Set atts = oMail.AttachmentList
    For i = 0 To atts.Count - 1
        Set att = atts.Item(i)
        MsgBox "Attachment: " & att.name
        ' Save attachment to local file.
        att.SaveAs App.Path & "\inbox\" & att.name, True
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and parse it one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ParseEmail files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to parse MAPI winmail.dat (TNEF/MAPI) attachment.

Parse winmail.dat (TNEF/MAPI) in VB 6.0

In previous section, I introduced how to verify digital signature and decrypt email. In this section, I will introduce how to parse winmail.dat (TNEF stream) in VB 6.0.

Introduction

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 stream) file, we should use ParseTNEF method.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Parse winmail.dat (TNEF stream)]

The following example codes demonstrate how to parse MAPI winmail.dat.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096
Const CERT_SYSTEM_STORE_CURRENT_USER = 65536
Const CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072

Private Sub ParseEmail(ByVal emlFile As String)
    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"

On Error GoTo ErrorHandle
    oMail.LoadFile emlFile, False

    If oMail.IsEncrypted Then
        ' This email is encrypted, we decrypt it by user default certificate.
        ' You can also use specified certificate like this
        ' Dim oCert As New EAGetMailObjLib.Certificate
        ' oCert.LoadFromFile "c:\test.pfx", "pfxpassword", CRYPT_USER_KEYSET
        ' Set oMail = oMail.Decrypt(oCert)
        Set oMail = oMail.Decrypt(Nothing)
    End If

    If oMail.IsSigned Then
        ' This email is digital signed.
        Dim oCert As EAGetMailObjLib.Certificate
        Set oCert = oMail.VerifySignature
        MsgBox "This email contains a valid digital signature."
        ' You can add the certificate to your certificate storage like this
        ' oCert.AddToStore CERT_SYSTEM_STORE_CURRENT_USER, "addressbook"
        ' Then you can use send the encrypted email back to this sender.
    End If

    ' Parse email sender
    MsgBox "From: " & oMail.From.Address

    Dim addressList As EAGetMailObjLib.AddressCollection
    Dim i As Long
    Dim addr As EAGetMailObjLib.MailAddress

    ' Parse email to recipients
    Set addressList = oMail.ToList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "To: " & addr.Address
    Next

    ' Parse email cc
    Set addressList = oMail.CcList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "Cc: " & addr.Address
    Next

    ' Parse email subject
    MsgBox "Subject: " & oMail.Subject

    ' Parse email text body
    MsgBox "Text body: " & oMail.TextBody

    ' Parse email HTML body
    MsgBox "Html body: " & oMail.HtmlBody


    ' Parse attachments
    Dim atts As EAGetMailObjLib.AttachmentCollection
    Dim att As EAGetMailObjLib.Attachment

    Set atts = oMail.AttachmentList
    For i = 0 To atts.Count - 1
        Set att = atts.Item(i)
        MsgBox "Attachment: " & att.name

        ' This attachment is in OUTLOOK RTF format(TNEF), decode it here.
        If LCase(att.name) = "winmail.dat" Then
            Dim tatts
            Dim x As Integer
            tatts = oMail.ParseTNEF(att.Content, True)
            For x = LBound(tatts) To UBound(tatts)
                Dim tatt As EAGetMailObjLib.Attachment
                Set tatt = tatts(x)
                MsgBox "winmail.dat: " & tatt.name
            Next
        End If
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and parse it one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ParseEmail files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Parse TNEF (winmail.dat) by DecodeTNEF method

In EAGetMail 4.5, a new method named DecodeTNEF is introduced. It is easier to parse TNEF attachment. Please have a look at the following example codes:

Option Explicit

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096
Const CERT_SYSTEM_STORE_CURRENT_USER = 65536
Const CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072

Private Sub ParseEmail(ByVal emlFile As String)
    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"

On Error GoTo ErrorHandle
    oMail.LoadFile emlFile, False

    If oMail.IsEncrypted Then
        ' This email is encrypted, we decrypt it by user default certificate.
        ' You can also use specified certificate like this
        ' Dim oCert As New EAGetMailObjLib.Certificate
        ' oCert.LoadFromFile "c:\test.pfx", "pfxpassword", CRYPT_USER_KEYSET
        ' Set oMail = oMail.Decrypt(oCert)
        Set oMail = oMail.Decrypt(Nothing)
    End If

    If oMail.IsSigned Then
        ' This email is digital signed.
        Dim oCert As EAGetMailObjLib.Certificate
        Set oCert = oMail.VerifySignature
        MsgBox "This email contains a valid digital signature."
        ' You can add the certificate to your certificate storage like this
        ' oCert.AddToStore CERT_SYSTEM_STORE_CURRENT_USER, "addressbook"
        ' Then you can use send the encrypted email back to this sender.
    End If

    ' Decode winmail.dat (TNEF) automatically'
    oMail.DecodeTNEF

    ' Parse email sender
    MsgBox "From: " & oMail.From.Address

    Dim addressList As EAGetMailObjLib.AddressCollection
    Dim i As Long
    Dim addr As EAGetMailObjLib.MailAddress

    ' Parse email to recipients
    Set addressList = oMail.ToList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "To: " & addr.Address
    Next

    ' Parse email cc
    Set addressList = oMail.CcList
    For i = 0 To addressList.Count - 1
        Set addr = addressList.Item(i)
        MsgBox "Cc: " & addr.Address
    Next

    ' Parse email subject
    MsgBox "Subject: " & oMail.Subject

    ' Parse email text body
    MsgBox "Text body: " & oMail.TextBody

    ' Parse email HTML body
    MsgBox "Html body: " & oMail.HtmlBody

    ' Parse attachments
    Dim atts As EAGetMailObjLib.AttachmentCollection
    Dim att As EAGetMailObjLib.Attachment

    Set atts = oMail.AttachmentList
    For i = 0 To atts.Count - 1
        Set att = atts.Item(i)
        MsgBox "Attachment: " & att.name
        ' Save attachment to local file.
        att.SaveAs App.Path & "\inbox\" & att.name, true
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and parse it one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ParseEmail files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Next Section

At next section I will introduce how to convert email to HTML page and display it in Web browser.

Parse Email Body, Attachment and Convert Email to HTML page in VB 6.0

In previous section, I introduced how to parse winmail.dat. In this section, I will introduce how to parse email body and attachment, then convert email to a HTML page and display it using Web browser in VB 6.0.

Introduction

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 and Embedded images.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Convert email to HTML]

The following example codes demonstrate how to use EAGetMail POP3 component to convert email to HTML page.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096
Const CERT_SYSTEM_STORE_CURRENT_USER = 65536
Const CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072

Private oTools As New EAGetMailObjLib.Tools

' 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)

On Error GoTo ErrorGenHtml

    Dim oTools As New EAGetMailObjLib.Tools
    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"

    oMail.LoadFile emlFile, False
    If Err.Number <> 0 Then
        MsgBox Err.Description
        Exit Sub
    End If

    On Error Resume Next
    If oMail.IsEncrypted Then
        Set oMail = oMail.Decrypt(Nothing)
        If Err.Number <> 0 Then
            MsgBox Err.Description
        End If
    End If

    If oMail.IsSigned Then
        oMail.VerifySignature
        If Err.Number <> 0 Then
            MsgBox Err.Description
        End If
    End If

On Error GoTo ErrorGenHtml

    ' Decode winmail.dat (TNEF) and RTF body automatically
    ' also convert RTF body to HTML automatically.
    oMail.DecodeTNEF

    Dim html As String
    html = oMail.HtmlBody

    Dim hdr As String
    hdr = hdr & "<font face=""Courier New,Arial"" size=2>"
    hdr = hdr & "<b>From:</b> " + FormatHtmlTag(oMail.From.name & "<" & _
    oMail.From.Address & ">") + "<br>"

    Dim i, addrs
    Set addrs = oMail.ToList

    If (addrs.Count > 0) Then
        hdr = hdr & "<b>To:</b> "
        For i = 0 To addrs.Count - 1
            hdr = hdr & FormatHtmlTag(addrs.Item(i).name & "<" & addrs.Item(i).Address & ">")
            hdr = hdr & ";"
        Next
        hdr = hdr & "<br>"
    End If

    Set addrs = oMail.CcList

    If (addrs.Count > 0) Then
        hdr = hdr & "<b>Cc:</b> "
        For i = 0 To addrs.Count - 1
            hdr = hdr & FormatHtmlTag(addrs.Item(i).name & "<" & addrs.Item(i).Address & ">")
            hdr = hdr & ";"
        Next
        hdr = hdr & "<br>"
    End If

    hdr = hdr & "<b>Subject:</b>" & FormatHtmlTag(oMail.Subject) & "<br>" & vbCrLf

    Dim atts
    Set atts = oMail.AttachmentList
    If (atts.Count > 0) Then

        If Not oTools.ExistFile(tempFolder) Then
            oTools.CreateFolder (tempFolder)
        End If

        hdr = hdr & "<b>Attachments:</b>"
        For i = 0 To atts.Count - 1
            Dim att As Attachment
            Set att = atts.Item(i)

            Dim attname
            attname = tempFolder & "\" & att.name
            att.SaveAs attname, True

            hdr = hdr & "<a href=""" & attname & """ target=""_blank"">" & att.name & "</a> "
            If Len(att.ContentID) > 0 Then
                'show embedded image.
                html = Replace(html, "cid:" + att.ContentID, attname)
            ElseIf InStr(1, att.ContentType, "image/", vbTextCompare) = 1 Then
                'show attached image.
                html = html & "<hr><img src=""" & attname & """>"
            End If
        Next
    End If

    hdr = "<meta HTTP-EQUIV=""Content-Type"" Content=""text-html; charset=utf-8"">" & hdr
    html = hdr & "<hr>" & html
    oTools.WriteTextFile htmlName, html, 65001

    MsgBox emlFile & " has been converted to html successfully!"
    Exit Sub

ErrorGenHtml:
    MsgBox "Failed to generate html file for the email; " & Err.Description

End Sub

Private Function FormatHtmlTag(ByVal src As String) As String
    src = Replace(src, ">", "&gt;")
    src = Replace(src, "<", "&lt;")
    FormatHtmlTag = src
End Function

Private Sub ConvertMailToHtml(ByVal fileName As String)
    Dim pos
    pos = InStrRev(fileName, ".")
    Dim mainName
    Dim htmlName
    mainName = Mid(fileName, 1, pos - 1)
    htmlName = mainName & ".htm"

    Dim tempFolder As String
    tempFolder = mainName
    If Not (oTools.ExistFile(htmlName)) Then
        ' We haven't generate the html for this email, generate it now.
        GenerateHtmlForEmail htmlName, fileName, tempFolder
    End If

End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and convert it to HTML one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ConvertMailToHtml files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

In EAGetMail installer, there are many samples demonstrate how to use Web browser control to display the email, I suggest that you download it and have a try

pop3, imap4 samples

Next Section

At next section I will introduce how to parse Non-delivery report.

Parse Non-Delivery Report (NDR) in VB 6.0

In previous section, I introduced how to convert email to HTML page. In this section, I will introduce how to parse Non-delivery report (NDR) in VB 6.0.

Read Receipt

Some e-mail applications, such as Microsoft Office Outlook, employ a read-receipt tracking mechanism. A sender selects the receipt request option prior to sending the message. Upon opening the email, each recipient has the option of notifying the sender that the message was opened and read.

However, there is no guarantee that you will get a read-receipt. Some possible reason are that very few e-mail applications or services support read receipts, or simply because users disable the functionality. Those do support read-receipt aren’t necessarily compatible with or capable of recognizing requests from a different e-mail service or application

Delivery Receipt and FailureReport

It is also called a DSN (delivery service notification), which is a request to the recipient&#8217;s email server to send you a notification about the delivery of an email you’ve just sent. The notification takes the form of an email, and will tell you if your delivery succeeded (Delivery Receipt), failed, got delayed (Failure Report).

Parse Report

For many email campaign applications, the very important task is detecting if the email is received by recipient or not. Parsing the delivery report is the common way to get the email status. EAGetMail .NET class provides a built-in function (GetReport) to parse the report. The following sample demonstrates how to parse the delivery-report.

If ReporType is DeliveryReceipt or ReadReceipt, the report probably has only OriginalSender, OriginalRecipient and OriginalMessageID information in the report, it depends on the mail server that generated the report.

Note

Remarks: All of examples in this section are based on first section: A simple VB 6.0 project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[VB 6.0 Example - Parse delivery report]

The following example codes demonstrate how to parse delivery report.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Private Sub ParseReport(ByVal emlFile As String)

    Const FailureReport = 0
    Const DeliveryReceipt = 1
    Const ReadReceipt = 2
    Const Receipt_Deleted = 3
    Const DelayedReport = 4

    Dim oMail As New EAGetMailObjLib.Mail
    oMail.LicenseCode = "TryIt"
    oMail.LoadFile emlFile, False

    If Not oMail.IsReport Then
        MsgBox "this is not a report"
        Exit Sub
    End If

    Dim oReport As EAGetMailObjLib.MailReport
    Set oReport = oMail.GetReport()
    ' Get report type
    Select Case oReport.ReportType
    Case DeliveryReceipt
        MsgBox "This is a deliver receipt"
    Case ReadReceipt
        MsgBox "This is a read receipt"
    Case Receipt_Deleted
        MsgBox "This is a unread receipt, this email was deleted without read!"
    Case DelayedReport
        MsgBox "This is a delayed report, this email will be tried later by server automatically!"
    Case Else
        MsgBox "This is a failure report"
    End Select

    ' Get original message information
    MsgBox oReport.OriginalSender
    MsgBox oReport.OriginalRecipient
    MsgBox oReport.OriginalMessageID

    If oReport.ReportType = FailureReport Or oReport.ReportType = DelayedReport Then
        MsgBox oReport.ErrCode
        MsgBox oReport.ErrDescription
        MsgBox oReport.OriginalSubject
        MsgBox oReport.ReportMTA

        Dim oHeaders As EAGetMailObjLib.HeaderCollection
        Set oHeaders = oReport.OriginalHeaders
        Dim i, nCount As Integer
        nCount = oHeaders.Count
        For i = 0 To nCount - 1
            Dim oHeader As EAGetMailObjLib.HeaderItem
            Set oHeader = oHeaders.Item(i)
            MsgBox oHeader.HeaderKey & ": " & oHeader.HeaderValue
        Next
    End If

End Sub

Private Sub Command1_Click()
    Dim curpath As String
    Dim mailbox As String
    Dim oTools As New EAGetMailObjLib.Tools

    ' Create a folder named "inbox" under current directory
    ' to save the email retrieved.
    curpath = App.Path
    mailbox = curpath & "\inbox"
    oTools.CreateFolder mailbox

    Dim files
    Dim i As Long

    ' Get all *.eml files in specified folder and parse it one by one.
    files = oTools.GetFiles(mailbox & "\*.eml")
    For i = LBound(files) To UBound(files)
        ParseReport files(i)
    Next

    Exit Sub
ErrorHandle:
    MsgBox Err.Description
End Sub

Parse Non-Delivery Report (NDR) using EAGetMail Service

To retrieve and parse Failure Report (NDR), you should monitor your sender mailbox. Here I will introduce how to use EAGetMail Service to monitor a mailbox and retrieve non-delivery report and insert it to SQL server on a regular basis.

Install EAGetMail Service

To use EAGetMail Service, you need to download EAGetMail Service and install it on your machine at first.

Create SQL table to store report

Then create a table in your SQL database like this:

CREATE TABLE [dbo].[Failure_Report](
    [reportid] [int] IDENTITY(1,1) NOT NULL,
    [address] [nvarchar](255) NOT NULL,
    [error_code] [nchar](10) NOT NULL,
    [error_desc] [nchar](255) NOT NULL,
    [error_datetime] [datetime] NOT NULL
) ON [PRIMARY]

GO

Create vbscript to process report

Create a vbscript named “parse_reports.vbs” like this:

Const FailureReport = 0 'Specifies that the email is a failure delivery report.
Const DeliveryReceipt = 1 'Specifies that the email is a delivery success report(delivery receipt).
Const ReadReceipt = 2 'Specifies that the email is a read receipt.
Const Receipt_Deleted = 3 'Specifies that the email is an unread receipt.

Dim args, info
Set args = WScript.Arguments

Dim oConn

If args.Length < 1 Then
    info =  "Usage: Parse_Reports.vbs [email folder path]" & Chr(13) & Chr(10)
    info = info & "eg: Parse_Reports.vbs ""c:\my folder""" & Chr(13) & Chr(10)
    WScript.Echo info
    WScript.Quit
End If

Dim oTools, files
Set oTools = CreateObject("EAGetMailObj.Tools")
' get all .eml files from specified folder
files = oTools.GetFiles( args(0) & "\*.eml" )

Dim count, i
count = UBound(files) - LBound(files) + 1
WScript.Echo( "Total " & count & " email(s)." )

Set oConn = CreateObject("ADODB.Connection")
Dim connStr

' For more connection string
' MS SQL Server 2000
'"Driver={SQL Server};Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2005
'"Driver={SQL Server Native Client};Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2005 Native Provider
'"Provider=SQLNCLI;Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2008
'"Driver={SQL Server Native Client 10.0};Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2008 Native Provider
'"Provider=SQLNCLI10;Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2012
'"Driver={SQL Server Native Client 11.0};Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' MS SQL Server 2012 Native Provider
'"Provider=SQLNCLI11;Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"

' change it to your sql server address, database, user and password
' The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
' e.g.: Server=serveraddress\instancename;
' open database connection

connStr = "Driver={SQL Server Native Client 11.0};Server=localhost; Database=myDB;Uid=myUser;Pwd=myPassword;"
WScript.Echo( "Connecting database ..." )

' Connect database
oConn.Open connStr

Dim nReport
nReport = 0

For i = 0 To count - 1
WScript.Echo( "Process " & i + 1 & ":" & files(i) & " ..." )
If ParseEmail( files(i)) Then
        ' Delete the local report file
    oTools.RemoveFile files(i)
End If
WScript.Echo( "" )
Next
oConn.Close
WScript.Echo("Close Data Connection")
WScript.Echo( "Total " & nReport & " failure report(s)")
WScript.Echo( "End" )

Function ParseEmail( fileName )
    Dim oMail
    Set oMail = CreateObject("EAGetMailObj.Mail")
    oMail.LicenseCode = "TryIt"
    oMail.LoadFile fileName, True

    If Not oMail.IsReport Then
        WScript.Echo( "Not a report or receipt!" )
        ParseEmail = False
        Exit Function
    End If


    Dim oReport
    Set oReport = oMail.GetReport()

    'We only process failure report
    If oReport.ReportType <> FailureReport Then
        WScript.Echo( "Not a failure report!" )
        ParseEmail = False
        Exit Function
    End If

    Dim address, errorCode, errorDesc
    address = oReport.OriginalRecipient
    errorCode = oReport.ErrCode
    errorDesc = oReport.ErrDescription

    WScript.Echo( "OriginalRecipient: " & address )
    WScript.Echo( "ErrorCode: " & errorCode )
    WScript.Echo( "ErrorDesc: " & errorDesc )

    If Len(errorDesc) > 250 Then
        errorDesc = Mid( errorDesc, 1, 250 )
    End If

    ' Insert result to database
    Dim sql
    sql = "INSERT INTO [dbo].[Failure_Report]" & _
        " ([address] " & _
        " ,[error_code] " & _
        " ,[error_desc] " & _
        " ,[error_datetime]) " & _
    " VALUES " & _
        " (?, ?, ? , GETDATE())"

    Dim oCommand
    Set oCommand = CreateObject("ADODB.Command")
    oCommand.CommandText = sql
    oCommand.CommandType = 1 'adCmdText
    oCommand.Prepared = true
    oCommand.ActiveConnection = oConn

    Dim oParameter
    Set oParameter = oCommand.CreateParameter( "address",  8, 1, , address )
    oCommand.Parameters.Append oParameter

    Set oParameter = oCommand.CreateParameter( "error_code", 8, 1, , errorCode )
    oCommand.Parameters.Append oParameter

    Set oParameter = oCommand.CreateParameter( "error_desc", 8, 1, , errorDesc )
    oCommand.Parameters.Append oParameter

    oCommand.Execute

    nReport = nReport + 1
    ParseEmail = True

End Function

Set a schedule to check email

Finally, open EAGetMail Service Manager -> Mail Pull Configuration -> New:

  • Input your sender mailbox account information.
  • Create a folder named “inbox” on your machine, this folder is used to store .EML file.
  • Input the folder full path to “Save email file(s) to specified local folder:”;
  • Input vbscript full path [SPACE] folder full path to: “Run specified application after download is finished”.

For example: If your vbscript full path is d:\parse_reports.vbs and your folder is d:\inbox, then input: "d:\parse_reports.vbs" "d:\inbox"

With above setting, EAGetMail Service checks mailbox every 15 minutes and once there is non-delivery report, it will invoke parse_reports.exe to process non-delivery report and insert it to database like this:

Important

If you have “Leave a copy of message on mail server” unchecked, EAGetMail Service will delete all emails in your mailbox after the emails were retrieved to local folder. If your mailbox is only used to retrieve non-delivery report, then I recommend you have “Leave a copy of message on mail server” unchecked to get better performance.

Debug your application

You can run your application directly under DOS prompt without EAGetMail Service. If there is any error, you can debug and fix it.

cscript "d:\parse_reports.vbs" "d:\inbox"

EAGetMail Service is a common solution to process email on a regular basis, you can use above solution to download and process normal emails as well. You just need to change/extend the codes in parse_reports.exe

Common SQL Driver Download

If SQL Server is installed on a remote server, and you don’t have SQL driver installed on local machine, then you need to download and install corresponding driver on local machine.

Next Section

At next section I will introduce how to manage folders with IMAP4/Exchange Web Service (EWS)/WebDAV protocol.

Create Folder and Manage Folder using IMAP4/Exchange Web Service (EWS)/WebDAV in VB 6.0

In previous section, I introduced how to parse non-delivery report (NDR) in VB 6.0. In this section, I will introduce how to create folders and manage folders with IMAP4/Exchange Web Service (EWS)/WebDAV protocol in VB 6.0.

Create Folder and Delete Folder

Because IMAP4/Exchange Web Service (EWS)/WebDAV protocol supports folder access, so we can retrieve email from other mailbox rather than default “INBOX”, I have introduced it in other sections. In this section, I will introduce how to use EAGetMail to create folder and delete folder with IMAP4/Exchange Web Service/WebDAV protocol. Notice: POP3 protocol doesn’t support this feature.

[VB 6.0 Example - Create Folder and Delete Folder]

The following example codes demonstrate how to create folder and delete folder.

Note

To get the full sample projects, please refer to Samples section.

Option Explicit

Const MailServerPop3 = 0
Const MailServerImap4 = 1
Const MailServerEWS = 2
Const MailServerDAV = 3
Const MailServerMsGraph = 4

Private Sub Command1_Click()

    ' To create folder with Exchange Web Service, please change
    ' MailServerImap4 to MailServerEWS to MailServer.Protocol

    ' To create folder email with Exchange WebDAV, please change
    ' MailServerImap4 to MailServerDAV to MailServer.Protocol

    ' Exchange Server supports POP3/IMAP4 protocol as well, but in Exchange 2007
    ' or later version, POP3/IMAP4 service is disabled by default. If you don't want to use POP3/IMAP4
    ' to download email from Exchange Server, you can use Exchange Web Service(Exchange 2007/2010 or
    ' later version) or WebDAV(Exchange 2000/2003) protocol.

    Dim oServer As New EAGetMailObjLib.MailServer
    oServer.Server = "imap4.emailarchitect.net"
    oServer.User = "test@emailarchitect.net"
    oServer.Password = "testpassword"
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection, most modern email servers require SSL/TLS by default
    oServer.SSLConnection = True
    oServer.Port = 993

    ' If your IMAP doesn't deploy SSL connection
    ' Please use
    ' oServer.SSLConnection = False
    ' oServer.Port = 143

On Error GoTo ErrorHandle:
    Dim oClient As New EAGetMailObjLib.MailClient
    oClient.LicenseCode = "TryIt"

    oClient.Connect oServer
    MsgBox "Connected"

    Dim oFolder As EAGetMailObjLib.Imap4Folder
    Set oFolder = oClient.CreateFolder(Nothing, "Test Folder")

    Dim folders
    Set folders = oClient.GetFolderList()

    Dim i
    For i = 0 To folders.Count - 1
        Dim fd As EAGetMailObjLib.Imap4Folder
        Set fd = folders.Item(i)
        MsgBox "folder: " & fd.FullPath
    Next

    oClient.DeleteFolder oFolder

    oClient.Logout

    Exit Sub

ErrorHandle:
    MsgBox Err.Description
End Sub

Retrieve/Copy/Move/Upload Email to Folder

To retrieve emails from a specified folder, please use SelectFolder method; To move email from a folder to another folder, please use Move method; To copy email from a folder to another folder, please use Copy method; To upload an email file from local disk to server folder, please use Append method.

Note

Please refer to ImapFull project for more detail.

Access Exchange Shared Mailbox

A MS Exchange shared mailbox is a mailbox that multiple users can use to read and send email messages. To access shared mailbox, please use MailServer.Alias property.

Access Exchange 2007/2010/2013/2016/2019 Public Mailbox

Since Exchange 2007 or later version (2010/203), IMAP4 protocol does not expose public folders to mail client. If you want to access public folders on MS Exchange 2007/2010/2013/2016/2019 or later version, please use MailClient.QueryEWSPublicFolders method.

Next Section

Total sample projects in EAGetMail Mail Component installation package.

VB 6.0 - POP3, IMAP4, SSL, Parse Email, S/MIME, Parse Delivery Report - Sample Projects

After you downloaded the EAGetMail POP3 Component Installer and install it on your machine, there are many samples in the installation path.

All the samples locate at EAGetMail Installation Folder. Most of sample projects demonstrate SSL/TLS Connection, UIDLManager, S/MIME, Tnef (winmail.dat) Parsing, Retrieve/Parse Email and Gmail/Office365/Hotmail OAUTH/XOAUTH2.

.NET Framework Sample Projects

ASP.NET Form

C#\Simple Retrieve email and parse email from ASP.NET Form with POP3/IMAP4/Exchange Web Service/WebDAV/Graph API/Gmail Rest API protocol.
C#\QueueService Download email from EAGetMail Background Service with POP3/IMAP4/Exchange Web Service/WebDAV protocol.

.NET Desktop (Windows Form)

C#, VB\Simple Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV/Graph API/Gmail Rest API protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV/Graph API/Gmail Rest API) and Gmail/Office365/Hotmail OAUTH.
C#, VB\SimpleWebView2 Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to display email in WebView2.
C#, VB\ParseReport Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV/Graph API/Gmail Rest API protocol.
C#, VB\ImapFull Full functionality of IMAP4/EWS/WebDAV/Graph API/Gmail Rest API including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption.
C#, VB\ImapFullWebView2 Full functionality of IMAP4/EWS/WebDAV/Graph API/Gmail Rest API including folder management, email moving and mail flags. This sample also demonstrates how to display email in WebView2.

Windows CE/PocketPC

C#, VB\pocketpc.mobile Retrieve email and parse email from .NET Compact Framework with POP3/IMAP4/EWS/WebDAV protocol.

ActiveX Object Sample Projects

ASP Classic

VBScript\Simple Retrieve email and parse email from ASP Form with POP3/IMAP4/Exchange Web Service/WebDAV protocol.
VBScript\QueueService Download email from EAGetMail Background Service with POP3/IMAP4/Exchange Web Service/WebDAV protocol.

Delphi

Simple Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH.
ParseReport Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol.
ImapFull Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption.

Script

VBScript, JScript\ParseEmail Parse email file by JScript/VBScript.
VBScript, JScript\PreviewEmail Download email header with POP3/IMAP4/EWS/WebDAV server by JScript/VBScript.

VB6

Simple Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH.
ParseReport Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol.
ImapFull Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption.

VC++

Simple Retrieve email and parse email with POP3/IMAP4/EWS/WebDAV protocol. It also demonstrates how to retrieve emails within specified date range (IMAP/EWS/WebDAV) and Gmail/Office365/Hotmail OAUTH.
ParseReport Retrieve and parse delivery report (NDR) with POP3/IMAP4/EWS/WebDAV protocol.
ImapFull Full functionality of IMAP4/EWS/WebDAV including folder management, email moving and mail flags. This sample also demonstrates parsing winmail.dat, digital signature verification and email decryption.

Free Email Support

Not enough? Please contact our technical support team.

Support@EmailArchitect.NET

Remarks

We usually reply emails within 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 Gmail, Hotmail/Offic 365 email account is recommended.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.