VB6/ASP - Retrieve email using Microsoft OAuth 2.0 + EWS/Graph API/IMAP4/POP3 protocol from Office 365 in background service

You can retrieve email using traditional user/password authentication from Office 365 account by EWS/IMAP4/POP3 Protocol.

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

Installation

Before you can use the following sample 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

Add reference in VBA (EXCEL/Access/Outlook)

Open VBA IDE by press Alt+F11, Please select menu -> Tools -> References -> and select EASendMailObj ActiveX Object, click OK, the reference will be added to current VBA project, and you can start to use it to retrieve email and parse email in your VBA 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

Office 365 OAuth 2.0 client credentials grant

Normal OAuth requires user input user/password for authentication. Obviously, it is not suitable for background service. In this case, you can use the OAuth 2.0 client credentials grant, sometimes called two-legged OAuth, to access web-hosted resources by using the identity of an application. It only works for Office365 user, it doesn’t work for personal Hotmail account.

Create your application in Azure Portal

To use Microsoft/Office365/Live OAuth (Modern Authentication) in your application, you must create an application in Azure Portal.

Important

You can use any Microsoft user to create the application, it doesn’t require application owner is administrator in your Office365 domain. But your Office365 administrator must authorize the application to access user mailbox.

  • Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
  • If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the Azure AD tenant that you want.
  • In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations -> New registration.
azure portal new app registration

Single tenant and multitenant in account type

When the register an application page appears, enter a meaningful application name and select the account type.

Select which accounts you would like your application to support.

  • If your application only supports the users in your directory or organization, please select Single tenant type;
  • If your application needs to support all users in Office 365 and Microsoft personal account (hotmail.com, outlook.com), please select Multitenant type, and you must verify publisher.

Because we just need to support Offic365 user in our organization, so select Accounts in this organizational directory only (single tenant).

Do not select supporting Microsoft personal account, because there is no way to access Microsoft personal account in background service.

Important

If you don’t verify publisher for multitenant application, your application will not request access token successfully.

API permissions

  • Click API Permission -> Microsoft Graph -> Delegated Permission -> User.Read.
  • Click API Permission -> Microsoft Graph -> Application Permission -> Mail.Send, Mail.ReadWrite.
  • Click API Permission -> Add a permission -> APIs in my organization uses -> Office 365 Exchange Online -> Application Permission -> Other permission -> full_access_as_app, IMAP.AccessAsApp and POP.AccessAsApp
azure APIs in my organization uses

Here is permissions list:

azure application api permission list

If your current user is not a user in a verified domain or Office 365, you will not find Office 365 Exchange Online in API list, then you have to add this API permission manually.

  • Select Manifest in the left-hand navigation under Manage.
  • Locate the requiredResourceAccess property in the manifest, and add the following inside the square brackets ([]):
 {
  "resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
  "resourceAccess": [
                              {
                                      "id": "cb842b43-da6e-4506-86fe-bb12199c656d",
                                      "type": "Role"
                              },
                              {
                                      "id": "5e5addcd-3e8d-4e90-baf5-964efab2b20a",
                                      "type": "Role"
                              },
      {
                                      "id": "dc890d15-9560-4a4c-9b7f-a736ec74ec40",
                                      "type": "Role"
                              }
  ]
}
  • Select Save.
  • Select API permissions under Manage. Confirm that the full_access_as_app, IMAP.AccessAsApp and POP.AccessAsApp permission is listed.

Client Id and client secrets

Now we need to create a client secret for the application, click Certificates and secrets -> client secrets and add a new client secret.

azure application api permission

After client secret is created, store the client secret value to somewhere.

Important

Please store client secret value by yourself, because it is hidden when you view it at next time.

Branding and verify publisher

Now we click Branding, you can edit your company logo, URL and application name. If your application supports multitenant (access user in all Office 365 and Microsoft personal account), you must complete the publisher verification.

If the application only accesses the accounts in your organization, you can skip publisher verification.

It is not difficult, you can have a look at publisher verification. After publisher verification is completed, your branding is like this:

azure application Authentication Overview

Important

You must complete the publisher verification for multitenant application, otherwise, your application will not request access token correctly.

Client id and tenant

Now you can click Overview to find your client id and tenant.

azure application client id and tenant

Limit user access to an application

User access to applications can still be limited, even when tenant-wide admin consent has been granted. Configure the application’s properties to require user assignment to limit user access to the application. For more information, see Methods for assigning users and groups.

For a broader overview, including how to handle other complex scenarios, see Use Azure AD for application access management.

Enable TLS Strong Encryption Algorithms in .NET 2.0 and .NET 4.0

Because HttpWebRequest is used to get access token from web service. If you’re using legacy .NET framework (.NET 2.0 - .NET 3.5 and .NET 4.0 - 4.6.1), you need to enable Strong Encryption Algorithms to request access token:

Put the following content to a file named NetStrongEncrypt.reg, right-click this file -> Merge -> Yes. You can also download it from https://www.emailarchitect.net/webapp/download/NetStrongEncrypt.zip.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

Access token expiration

You don’t have to request access token every time. By default, access token expiration time is 3600 seconds, you can use the access token repeatedly before it is expired.

Important

You should create your client id and client secret, do not use the client id from example codes in production environment, it is used for test purpose. If you got "This app isn't verified" information, please click "Advanced" -> Go to ... for test.

VB6/ASP - Retrieve email using Microsoft OAuth 2.0 + Graph API in background service - example

Option Explicit

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

Const MailServerAuthLogin = 0
Const MailServerAuthCRAM5 = 1
Const MailServerAuthNTLM = 2
Const MailServerAuthXOAUTH2 = 3

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

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096

Private Function GenerateRequestData()

    Const client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f"
    Const client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."
    Const scope = "https://graph.microsoft.com/.default"

    GenerateRequestData = "client_id=" & client_id & "&client_secret=" & client_secret & "&scope=" & scope & "&grant_type=client_credentials"

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")

    ' If your application is not created by Office365 administrator,
    ' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
    ' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
    Const tenant_id = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"

    Dim tokenUri
    tokenUri = "https://login.microsoftonline.com/" & tenant_id & "/oauth2/v2.0/token"

    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData

    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop

    Dim Status
    Status = httpRequest.Status

    If Status < 200 Or Status >= 300 Then
        Debug.Print "Failed to get access token from server."
        Debug.Print httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText

    Dim oauthParser As New EAGetMailObjLib.OAuthResponseParser
    oauthParser.Load result

    Dim accessToken
    accessToken = oauthParser.accessToken

    If accessToken = "" Then
        Debug.Print "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    Debug.Print "Failed to request access token." & Err.Description

End Function

Public Sub RetrieveEmail()

    Dim accessToken As String
    accessToken = RequestAccessToken(GenerateRequestData())

    If accessToken = "" Then
        Exit Sub
    End If

    Dim Office365User As String
    Office365User = "user@mydomain.onmicrosoft.com"


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 Graph API Server address
    oServer.Server = "graph.microsoft.com"
    ' Use OAUTH 2.0
    oServer.AuthType = MailServerAuthXOAUTH2
    oServer.user = Office365User
    ' Use access token as password
    oServer.Password = accessToken
    ' Use Graph API Protocol
    oServer.Protocol = MailServerMsGraph

    ' Enable SSL/TLS connection
    oServer.SSLConnection = True


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

    Debug.Print "Connecting " & oServer.Server & "..."
    oClient.Connect oServer
    Debug.Print "Connected"

    ' Get new email only, if you want to get all emails, please remove this line
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

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

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

        Debug.Print "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

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

        Debug.Print "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 read to prevent retrieving this email again.
        oClient.MarkAsRead info, True

        ' If you want to delete current email, please use Delete method instead of MarkAsRead
        ' oClient.Delete info
    Next

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

ErrorHandle:
    Debug.Print Err.Description

End Sub

VB6/ASP - Retrieve email using Microsoft OAuth 2.0 + EWS in background service - example

Option Explicit

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

Const MailServerAuthLogin = 0
Const MailServerAuthCRAM5 = 1
Const MailServerAuthNTLM = 2
Const MailServerAuthXOAUTH2 = 3

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

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096

Private Function GenerateRequestData()

    Const client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f"
    Const client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."
    Const scope = "https://outlook.office365.com/.default"

    GenerateRequestData = "client_id=" & client_id & "&client_secret=" & client_secret & "&scope=" & scope & "&grant_type=client_credentials"

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")

    ' If your application is not created by Office365 administrator,
    ' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
    ' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
    Const tenant_id = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"

    Dim tokenUri
    tokenUri = "https://login.microsoftonline.com/" & tenant_id & "/oauth2/v2.0/token"

    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData

    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop

    Dim Status
    Status = httpRequest.Status

    If Status < 200 Or Status >= 300 Then
        Debug.Print "Failed to get access token from server."
        Debug.Print httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText

    Dim oauthParser As New EAGetMailObjLib.OAuthResponseParser
    oauthParser.Load result

    Dim accessToken
    accessToken = oauthParser.accessToken

    If accessToken = "" Then
        Debug.Print "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    Debug.Print "Failed to request access token." & Err.Description

End Function

Public Sub RetrieveEmail()

    Dim accessToken As String
    accessToken = RequestAccessToken(GenerateRequestData())

    If accessToken = "" Then
        Exit Sub
    End If

    Dim Office365User As String
    Office365User = "user@mydomain.onmicrosoft.com"


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 Server address
    oServer.Server = "outlook.office365.com"
    ' Use OAUTH 2.0
    oServer.AuthType = MailServerAuthXOAUTH2
    oServer.user = Office365User
    ' Use access token as password
    oServer.Password = accessToken
    ' Use EWS Protocol
    oServer.Protocol = MailServerEWS

    ' Enable SSL/TLS connection
    oServer.SSLConnection = True


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

    Debug.Print "Connecting " & oServer.Server & "..."
    oClient.Connect oServer
    Debug.Print "Connected"

    ' Get new email only, if you want to get all emails, please remove this line
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

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

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

        Debug.Print "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

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

        Debug.Print "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 read to prevent retrieving this email again.
        oClient.MarkAsRead info, True

        ' If you want to delete current email, please use Delete method instead of MarkAsRead
        ' oClient.Delete info
    Next

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

ErrorHandle:
    Debug.Print Err.Description

End Sub

Register POP/IMAP service principals in Exchange

If you want to use POP/IMAP protocol, once your Azure AD application is consented to by a tenant admin, the tenant admin must register your AAD application’s service principal in Exchange via Exchange Online PowerShell. This is enabled by the New-ServicePrincipal cmdlet.

New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]

You should replace <APPLICATION_ID> by Application ID, <OBJECT_ID> by Object ID, <ORGANIZATION_ID> by Directory ID. If you have only one Active Directory, you can ignore the -Organization parameter.

You can find your APPLICATION_ID and OBJECT_ID in the Enterprise applications blade in the Azure Active Directory view in Azure Portal.

azure application client id and object id in enterprise application
New-ServicePrincipal -AppId "8f54719b-4070-41ae-91ad-f48e3c793c5f" -ServiceId "520715de-8170-48b5-acad-a1295650649e"

After you created the service principal, you can query it by:

Get-ServicePrincipal

The tenant admin can now add the specific mailboxes in the tenant that will be allowed to be access by your application. This is done with the Add-MailboxPermission cmdlet.

Add-MailboxPermission -Identity "ivan.smith@contoso.com" -User "520715de-8170-48b5-acad-a1295650649e" -AccessRights FullAccess

Now you can use the following codes to access the mailbox by IMAP or POP protocol.

VB6/ASP - Retrieve email using Microsoft OAuth 2.0 + IMAP4 in background service - example

Option Explicit

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

Const MailServerAuthLogin = 0
Const MailServerAuthCRAM5 = 1
Const MailServerAuthNTLM = 2
Const MailServerAuthXOAUTH2 = 3

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

Const CRYPT_MACHINE_KEYSET = 32
Const CRYPT_USER_KEYSET = 4096

Private Function GenerateRequestData()

    Const client_id = "8f54719b-4070-41ae-91ad-f48e3c793c5f"
    Const client_secret = "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."
    Const scope = "https://outlook.office365.com/.default"

    GenerateRequestData = "client_id=" & client_id & "&client_secret=" & client_secret & "&scope=" & scope & "&grant_type=client_credentials"

End Function

Private Function RequestAccessToken(requestData)
    RequestAccessToken = ""

    If requestData = "" Then
        Exit Function
    End If

On Error GoTo ErrorHandle

    Dim httpRequest
    Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")

    ' If your application is not created by Office365 administrator,
    ' please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
    ' Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
    Const tenant_id = "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"

    Dim tokenUri
    tokenUri = "https://login.microsoftonline.com/" & tenant_id & "/oauth2/v2.0/token"

    httpRequest.setOption 2, 13056
    httpRequest.Open "POST", tokenUri, True
    httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    httpRequest.Send requestData

    Do While httpRequest.ReadyState <> 4
        DoEvents
        httpRequest.waitForResponse (1)
    Loop

    Dim Status
    Status = httpRequest.Status

    If Status < 200 Or Status >= 300 Then
        Debug.Print "Failed to get access token from server."
        Debug.Print httpRequest.responseText
        Exit Function
    End If

    Dim result
    result = httpRequest.responseText

    Dim oauthParser As New EAGetMailObjLib.OAuthResponseParser
    oauthParser.Load result

    Dim accessToken
    accessToken = oauthParser.accessToken

    If accessToken = "" Then
        Debug.Print "Failed to parse access token from server response."
        Exit Function
    End If

    RequestAccessToken = accessToken
    Exit Function

ErrorHandle:
    Debug.Print "Failed to request access token." & Err.Description

End Function

Public Sub RetrieveEmail()

    Dim accessToken As String
    accessToken = RequestAccessToken(GenerateRequestData())

    If accessToken = "" Then
        Exit Sub
    End If

    Dim Office365User As String
    Office365User = "user@mydomain.onmicrosoft.com"


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 Server address
    oServer.Server = "outlook.office365.com"
    ' Use OAUTH 2.0
    oServer.AuthType = MailServerAuthXOAUTH2
    oServer.user = Office365User
    ' Use access token as password
    oServer.Password = accessToken
    ' Use IMAP Protocol
    oServer.Protocol = MailServerImap4

    ' Enable SSL/TLS connection
    oServer.SSLConnection = True

    ' Set IMAP SSL Port
    oServer.Port = 993

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

    Debug.Print "Connecting " & oServer.Server & "..."
    oClient.Connect oServer
    Debug.Print "Connected"

    ' Get new email only, if you want to get all emails, please remove this line
    oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfos_NewOnly

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

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

        Debug.Print "Index: " & info.Index & "; Size: " & info.Size & _
        "; UIDL: " & info.UIDL

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

        Debug.Print "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 read to prevent retrieving this email again.
        oClient.MarkAsRead info, True

        ' If you want to delete current email, please use Delete method instead of MarkAsRead
        ' oClient.Delete info
    Next

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

ErrorHandle:
    Debug.Print Err.Description

End Sub

TLS 1.2 protocol

TLS is the successor of SSL, more and more SMTP 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, 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

Appendix

Comments

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