You can retrieve email using traditional user/password authentication from Office 365 account by EWS Protocol.
However Microsoft has disabled traditional user authentication in many tenants, switching to Microsoft OAuth (Modern Authentication) is strongly recommended now.
In this topic, I will introduce how to retrieve email using VC++ and Microsoft OAuth (Modern Authentication) in background service.
Sections:
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.
To better demonstrate how to retrieve email and parse email, let’s create a Visual C++ console project named “receiveemail” at first, and then add the reference of EAGetMail in your project.
To use EAGetMail POP3 & IMAP4 ActiveX Object in your project, the first step is “Add header files of EAGetMail to your project”.
Please go to C:\Program Files\EAGetMail\Include\tlh
or C:\Program Files (x86)\EAGetMail\Include\tlh
folder, find eagetmailobj.tlh
and eagetmailobj.tli
,
and then copy these files to your project folder. You can start to use it to retrieve email and parse email in your project.
Normal OAuth requires user to input user and password in browser for authentication. Obviously, it is not suitable for background service.
The solution is granting admin consent
to the azure application, then the application
can use the client secret value to request the access token directly.
This way doesn’t require user attending, it is suitable for background service.
This tutorial introduces how to register application for background service
in Azure Portal,
then assign the Graph API/EWS/SMTP/POP/IMAP API permission to the application and add the access right to the mailbox of specific user.
Sign in to the Azure Portal using the Microsoft account of the Office 365 administrator
.
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.
Search Microsoft Entra ID
(old name “Azure Active Directory”) and go to this service:
In the left-hand navigation pane, select the Microsoft Entra ID
service, and then select App registrations -> New registration.
Input a name to to register the application:
After the application is registered, you can click Overview
to find the client id
and tenant id
.
These are required parameters for requesting access token.
Now you need to assign API permission to the application by clicking API Permission
-> Add a permission
.
You don’t have to assign all the API permissions below to the application, just assign the API permission(s) you need.
Protocol | Permission | Scope | |
Graph API | Mail.Send, Mail.ReadWrite | https://graph.microsoft.com/.default | |
EWS | full_access_as_app | https://outlook.office365.com/.default | |
SMTP | SMTP.AccessAsApp | https://outlook.office365.com/.default | |
POP | POP.AccessAsApp | https://outlook.office365.com/.default | |
IMAP | IMAP.AccessAsApp | https://outlook.office365.com/.default |
Go to Microsoft APIs
->
Microsoft Graph
-> Application Permission
->
Go to APIs in my organization uses
->
Office 365 Exchange Online
-> Application Permission
->
To use the application to access the user mailbox in Office365 domain, you should grant admin consent by Office365 domain administrator.
In API Permission -> Click grant admin consent for ...
to grant admin consent to the application.
Now we need to create a client secret for the application,
click Certificates and secrets
-> client secrets
and add a new client secret.
After client secret is created, store the client secret value
to somewhere. It is another required parameter
for requesting access token.
Important
Please store client secret value
by yourself, because it is hidden when you view it at next time.
Now you can use the client id
, tenant id
and client secret value
to request access token.
But to use SMTP/POP/IMAP protocol, you need to Register SMTP/POP/IMAP service principals in Exchange as well.
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.
Now you can use the following example codes to retrieve email with Graph API or EWS protocol:
#include "stdafx.h" // pre-compile header
#include <stdio.h>
#include <tchar.h>
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\EAGetMailObj.tlh"
using namespace EAGetMailObjLib;
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\msxml3.tlh"
using namespace MSXML2;
const int MailServerPop3 = 0;
const int MailServerImap4 = 1;
const int MailServerEWS = 2;
const int MailServerDAV = 3;
const int MailServerMsGraph = 4;
const int MailServerAuthLogin = 0;
const int MailServerAuthCRAM5 = 1;
const int MailServerAuthNTLM = 2;
const int MailServerAuthXOAUTH2 = 3;
const int GetMailInfos_All = 1;
const int GetMailInfos_NewOnly = 2;
const int GetMailInfos_ReadOnly = 4;
const int GetMailInfos_SeqRange = 8;
const int GetMailInfos_UIDRange = 16;
const int GetMailInfos_PR_ENTRYID = 32;
const int GetMailInfos_DateRange = 64;
const int GetMailInfos_OrderByDateTime = 128;
DWORD _getCurrentPath(LPTSTR lpPath, DWORD nSize)
{
DWORD dwSize = ::GetModuleFileName(NULL, lpPath, nSize);
if (dwSize == 0 || dwSize == nSize)
{
return 0;
}
// Change file name to current full path
LPCTSTR psz = _tcsrchr(lpPath, _T('\\'));
if (psz != NULL)
{
lpPath[psz - lpPath] = _T('\0');
return _tcslen(lpPath);
}
return 0;
}
BOOL RequestAccessToken(const char* requestData, _bstr_t &accessToken)
{
try
{
IServerXMLHTTPRequestPtr httpRequest = NULL;
httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP));
if (httpRequest == NULL)
{
printf("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n");
return FALSE;
}
_bstr_t fullRequest = requestData;
const char* postData = (const char*)fullRequest;
LONG cdata = strlen(postData);
LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL);
for (LONG k = 0; k < (int)cdata; k++)
{
BYTE ch = (BYTE)postData[k];
::SafeArrayPutElement(psaHunk, &k, &ch);
}
_variant_t requestBuffer;
requestBuffer.vt = (VT_ARRAY | VT_UI1);
requestBuffer.parray = psaHunk;
// 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 char* tenant_id = "2ea4955d-830e-4aa7-8ab5-661a6b9aa84d";
_variant_t async(true);
_bstr_t tokenUri("https://login.microsoftonline.com/");
tokenUri += _bstr_t(tenant_id);
tokenUri += _bstr_t("/oauth2/v2.0/token");
httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056);
httpRequest->open(L"POST", tokenUri, async, vtMissing, vtMissing);
httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded");
httpRequest->send(requestBuffer);
while (httpRequest->readyState != 4) {
httpRequest->waitForResponse(1);
}
long status = httpRequest->status;
_bstr_t responseText = httpRequest->responseText;
if (status < 200 || status >= 300)
{
printf("Failed to get access token from server: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
IOAuthResponseParserPtr oauthParser = NULL;
oauthParser.CreateInstance(__uuidof(EAGetMailObjLib::OAuthResponseParser));
oauthParser->Load(responseText);
accessToken = oauthParser->AccessToken;
if (accessToken.length() == 0)
{
printf("Failed to parse access token from server response: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
return TRUE;
}
catch (_com_error &ep)
{
printf("Failed to get access token: %s", (const char*)ep.Description());
return FALSE;
}
}
_bstr_t GenerateRequestData()
{
// You should create your client id and client secret,
// do not use the following client id in production environment, it is used for test purpose only.
const char* client_id = "b22194da-44d6-4320-a067-e86a275d6fa4";
const char* client_secret = "VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.";
const char* scope = "https://graph.microsoft.com/.default";
_bstr_t buffer = "client_id=";
buffer += client_id;
buffer += "&client_secret=";
buffer += client_secret;
buffer += "&scope=";
buffer += scope;
buffer += "&grant_type=client_credentials";
return buffer;
}
void RetrieveEmail()
{
::CoInitialize(NULL);
_bstr_t accessToken;
// request access token from MS server without user interaction
if (!RequestAccessToken((const char*)GenerateRequestData(), accessToken))
{
return;
}
const char* Office365User = "user@mydomain.onmicrosoft.com";
try
{
TCHAR szPath[MAX_PATH + 1];
_getCurrentPath(szPath, MAX_PATH);
TCHAR szMailBox[MAX_PATH + 1];
wsprintf(szMailBox, _T("%s\\inbox"), szPath);
// Create a folder to store emails
::CreateDirectory(szMailBox, NULL);
IMailServerPtr oServer = NULL;
oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer));
// Office365 Graph API server address
oServer->Server = _bstr_t("graph.microsoft.com");
oServer->User = _bstr_t(Office365User);
// Use access token as password
oServer->Password = accessToken;
// Use OAUTH 2.0
oServer->AuthType = MailServerAuthXOAUTH2;
// Use Graph API Protocol
oServer->Protocol = MailServerMsGraph;
// Enable SSL Connection
oServer->SSLConnection = VARIANT_TRUE;
IMailClientPtr oClient = NULL;
oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient));
oClient->LicenseCode = _T("TryIt");
_tprintf(_T("Connecting %s ...\r\n"), (const TCHAR*)oServer->Server);
oClient->Connect(oServer);
// Get new email only, if you want to get all emails, please remove this line
oClient->GetMailInfosParam->GetMailInfosOptions = GetMailInfos_NewOnly;
IMailInfoCollectionPtr infos = oClient->GetMailInfoList();
_tprintf(_T("Total %d emails\r\n"), infos->Count);
for (long i = 0; i < infos->Count; i++)
{
IMailInfoPtr pInfo = infos->GetItem(i);
_tprintf(_T("Index: %d; Size: %d; UIDL: %s\r\n\r\n"),
pInfo->Index, pInfo->Size, (const TCHAR*)pInfo->UIDL);
TCHAR szFile[MAX_PATH + 1];
// Generate a random file name by current local datetime,
// You can use your method to generate the filename if you do not like it
SYSTEMTIME curtm;
::GetLocalTime(&curtm);
::wsprintf(szFile, _T("%s\\%04d%02d%02d%02d%02d%02d%03d%d.eml"),
szMailBox,
curtm.wYear,
curtm.wMonth,
curtm.wDay,
curtm.wHour,
curtm.wMinute,
curtm.wSecond,
curtm.wMilliseconds,
i);
// Receive email from POP3 server
IMailPtr oMail = oClient->GetMail(pInfo);
_tprintf(_T("From: %s\r\n"), (const TCHAR*)oMail->From->Address);
_tprintf(_T("Subject: %s\r\n"), (const TCHAR*)oMail->Subject);
// Save email to local disk
oMail->SaveAs(szFile, VARIANT_TRUE);
// Mark email as read to prevent retrieving this email again.
oClient->MarkAsRead(pInfo, VARIANT_TRUE);
// If you want to delete current email, please use Delete method instead of MarkAsRead
// oClient->Delete(pInfo);
}
// Delete method just mark the email as deleted,
// Quit method expunge the emails from server exactly.
oClient->Quit();
}
catch (_com_error &ep)
{
_tprintf(_T("Error: %s\r\n"), (const TCHAR*)ep.Description());
}
}
#include "stdafx.h" // pre-compile header
#include <stdio.h>
#include <tchar.h>
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\EAGetMailObj.tlh"
using namespace EAGetMailObjLib;
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\msxml3.tlh"
using namespace MSXML2;
const int MailServerPop3 = 0;
const int MailServerImap4 = 1;
const int MailServerEWS = 2;
const int MailServerDAV = 3;
const int MailServerMsGraph = 4;
const int MailServerAuthLogin = 0;
const int MailServerAuthCRAM5 = 1;
const int MailServerAuthNTLM = 2;
const int MailServerAuthXOAUTH2 = 3;
const int GetMailInfos_All = 1;
const int GetMailInfos_NewOnly = 2;
const int GetMailInfos_ReadOnly = 4;
const int GetMailInfos_SeqRange = 8;
const int GetMailInfos_UIDRange = 16;
const int GetMailInfos_PR_ENTRYID = 32;
const int GetMailInfos_DateRange = 64;
const int GetMailInfos_OrderByDateTime = 128;
DWORD _getCurrentPath(LPTSTR lpPath, DWORD nSize)
{
DWORD dwSize = ::GetModuleFileName(NULL, lpPath, nSize);
if (dwSize == 0 || dwSize == nSize)
{
return 0;
}
// Change file name to current full path
LPCTSTR psz = _tcsrchr(lpPath, _T('\\'));
if (psz != NULL)
{
lpPath[psz - lpPath] = _T('\0');
return _tcslen(lpPath);
}
return 0;
}
BOOL RequestAccessToken(const char* requestData, _bstr_t &accessToken)
{
try
{
IServerXMLHTTPRequestPtr httpRequest = NULL;
httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP));
if (httpRequest == NULL)
{
printf("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n");
return FALSE;
}
_bstr_t fullRequest = requestData;
const char* postData = (const char*)fullRequest;
LONG cdata = strlen(postData);
LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL);
for (LONG k = 0; k < (int)cdata; k++)
{
BYTE ch = (BYTE)postData[k];
::SafeArrayPutElement(psaHunk, &k, &ch);
}
_variant_t requestBuffer;
requestBuffer.vt = (VT_ARRAY | VT_UI1);
requestBuffer.parray = psaHunk;
// 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 char* tenant_id = "2ea4955d-830e-4aa7-8ab5-661a6b9aa84d";
_variant_t async(true);
_bstr_t tokenUri("https://login.microsoftonline.com/");
tokenUri += _bstr_t(tenant_id);
tokenUri += _bstr_t("/oauth2/v2.0/token");
httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056);
httpRequest->open(L"POST", tokenUri, async, vtMissing, vtMissing);
httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded");
httpRequest->send(requestBuffer);
while (httpRequest->readyState != 4) {
httpRequest->waitForResponse(1);
}
long status = httpRequest->status;
_bstr_t responseText = httpRequest->responseText;
if (status < 200 || status >= 300)
{
printf("Failed to get access token from server: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
IOAuthResponseParserPtr oauthParser = NULL;
oauthParser.CreateInstance(__uuidof(EAGetMailObjLib::OAuthResponseParser));
oauthParser->Load(responseText);
accessToken = oauthParser->AccessToken;
if (accessToken.length() == 0)
{
printf("Failed to parse access token from server response: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
return TRUE;
}
catch (_com_error &ep)
{
printf("Failed to get access token: %s", (const char*)ep.Description());
return FALSE;
}
}
_bstr_t GenerateRequestData()
{
// You should create your client id and client secret,
// do not use the following client id in production environment, it is used for test purpose only.
const char* client_id = "b22194da-44d6-4320-a067-e86a275d6fa4";
const char* client_secret = "VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.";
const char* scope = "https://outlook.office365.com/.default";
_bstr_t buffer = "client_id=";
buffer += client_id;
buffer += "&client_secret=";
buffer += client_secret;
buffer += "&scope=";
buffer += scope;
buffer += "&grant_type=client_credentials";
return buffer;
}
void RetrieveEmail()
{
::CoInitialize(NULL);
_bstr_t accessToken;
// request access token from MS server without user interaction
if (!RequestAccessToken((const char*)GenerateRequestData(), accessToken))
{
return;
}
const char* Office365User = "user@mydomain.onmicrosoft.com";
try
{
TCHAR szPath[MAX_PATH + 1];
_getCurrentPath(szPath, MAX_PATH);
TCHAR szMailBox[MAX_PATH + 1];
wsprintf(szMailBox, _T("%s\\inbox"), szPath);
// Create a folder to store emails
::CreateDirectory(szMailBox, NULL);
IMailServerPtr oServer = NULL;
oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer));
// Office365 server address
oServer->Server = _bstr_t("outlook.office365.com");
oServer->User = _bstr_t(Office365User);
// Use access token as password
oServer->Password = accessToken;
// Use OAUTH 2.0
oServer->AuthType = MailServerAuthXOAUTH2;
// Use EWS Protocol
oServer->Protocol = MailServerEWS;
// Enable SSL Connection
oServer->SSLConnection = VARIANT_TRUE;
IMailClientPtr oClient = NULL;
oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient));
oClient->LicenseCode = _T("TryIt");
_tprintf(_T("Connecting %s ...\r\n"), (const TCHAR*)oServer->Server);
oClient->Connect(oServer);
// Get new email only, if you want to get all emails, please remove this line
oClient->GetMailInfosParam->GetMailInfosOptions = GetMailInfos_NewOnly;
IMailInfoCollectionPtr infos = oClient->GetMailInfoList();
_tprintf(_T("Total %d emails\r\n"), infos->Count);
for (long i = 0; i < infos->Count; i++)
{
IMailInfoPtr pInfo = infos->GetItem(i);
_tprintf(_T("Index: %d; Size: %d; UIDL: %s\r\n\r\n"),
pInfo->Index, pInfo->Size, (const TCHAR*)pInfo->UIDL);
TCHAR szFile[MAX_PATH + 1];
// Generate a random file name by current local datetime,
// You can use your method to generate the filename if you do not like it
SYSTEMTIME curtm;
::GetLocalTime(&curtm);
::wsprintf(szFile, _T("%s\\%04d%02d%02d%02d%02d%02d%03d%d.eml"),
szMailBox,
curtm.wYear,
curtm.wMonth,
curtm.wDay,
curtm.wHour,
curtm.wMinute,
curtm.wSecond,
curtm.wMilliseconds,
i);
// Receive email from POP3 server
IMailPtr oMail = oClient->GetMail(pInfo);
_tprintf(_T("From: %s\r\n"), (const TCHAR*)oMail->From->Address);
_tprintf(_T("Subject: %s\r\n"), (const TCHAR*)oMail->Subject);
// Save email to local disk
oMail->SaveAs(szFile, VARIANT_TRUE);
// Mark email as read to prevent retrieving this email again.
oClient->MarkAsRead(pInfo, VARIANT_TRUE);
// If you want to delete current email, please use Delete method instead of MarkAsRead
// oClient->Delete(pInfo);
}
// Delete method just mark the email as deleted,
// Quit method expunge the emails from server exactly.
oClient->Quit();
}
catch (_com_error &ep)
{
_tprintf(_T("Error: %s\r\n"), (const TCHAR*)ep.Description());
}
}
Although the application is consented by the tenant admin, but to access SMTP/POP/IMAP service, the tenant administrator still need to register your application as service principal in Exchange via Exchange Online PowerShell. This is enabled by the New-ServicePrincipal cmdlet.
New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID>
You should find your APPLICATION_ID
and OBJECT_ID
before running above cmdlet.
Go to Overview
-> Managed application in local directory
:
After you click your application name in Managed application in l...
,
you can see Application ID
and Object ID
for New-ServicePrincipal cmdlet.
Now you need to open Exchange Online PowerShell to run the cmdlet. If you have not installed the module, you can use the Install-Module cmdlet to install the module from the PowerShell Gallery.
Install-Module -Name ExchangeOnlineManagement
After you’ve installed the module, open a PowerShell window and load the module by running the following command:
Import-Module ExchangeOnlineManagement
Connect-ExchangeOnline -UserPrincipalName "admin@yourdomain.onmicrosoft.com"
After Exchange Online PowerShell is connected successfully, run the following cmdlet to create a new service principal:
The ServiceId is the OBJECT_ID
and the AppId is APPLICATION_ID
found in Find APPLICATION_ID and OBJECT_ID
New-ServicePrincipal -AppId "b22194da-44d6-4320-a067-e86a275d6fa4" -ServiceId "71941e67-ef24-45e8-bd22-dfd53790bb77"
After you create the service principal, you can query it by:
Get-ServicePrincipal
You 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 <mailboxIdParameter> -User <SecurityPrincipalIdParameter|OBJECT_ID> -AccessRights <MailboxRights[]>
For example:
Add-MailboxPermission -Identity "grant-test@emailarchitect.net" -User "71941e67-ef24-45e8-bd22-dfd53790bb77" -AccessRights FullAccess
You can also query the permission by:
Get-MailboxPermission -Identity "grant-test@emailarchitect.net"
Now you can use IMAP or POP3 protocol to retrieve email by the following codes:
#include "stdafx.h" // pre-compile header
#include <stdio.h>
#include <tchar.h>
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\EAGetMailObj.tlh"
using namespace EAGetMailObjLib;
#include "C:\Program Files (x86)\EAGetMail\Include\tlh\msxml3.tlh"
using namespace MSXML2;
const int MailServerPop3 = 0;
const int MailServerImap4 = 1;
const int MailServerEWS = 2;
const int MailServerDAV = 3;
const int MailServerMsGraph = 4;
const int MailServerAuthLogin = 0;
const int MailServerAuthCRAM5 = 1;
const int MailServerAuthNTLM = 2;
const int MailServerAuthXOAUTH2 = 3;
const int GetMailInfos_All = 1;
const int GetMailInfos_NewOnly = 2;
const int GetMailInfos_ReadOnly = 4;
const int GetMailInfos_SeqRange = 8;
const int GetMailInfos_UIDRange = 16;
const int GetMailInfos_PR_ENTRYID = 32;
const int GetMailInfos_DateRange = 64;
const int GetMailInfos_OrderByDateTime = 128;
DWORD _getCurrentPath(LPTSTR lpPath, DWORD nSize)
{
DWORD dwSize = ::GetModuleFileName(NULL, lpPath, nSize);
if (dwSize == 0 || dwSize == nSize)
{
return 0;
}
// Change file name to current full path
LPCTSTR psz = _tcsrchr(lpPath, _T('\\'));
if (psz != NULL)
{
lpPath[psz - lpPath] = _T('\0');
return _tcslen(lpPath);
}
return 0;
}
BOOL RequestAccessToken(const char* requestData, _bstr_t &accessToken)
{
try
{
IServerXMLHTTPRequestPtr httpRequest = NULL;
httpRequest.CreateInstance(__uuidof(MSXML2::ServerXMLHTTP));
if (httpRequest == NULL)
{
printf("Failed to create XML HTTP Object, please make sure you install MSXML 3.0 on your machine.\r\n");
return FALSE;
}
_bstr_t fullRequest = requestData;
const char* postData = (const char*)fullRequest;
LONG cdata = strlen(postData);
LPSAFEARRAY psaHunk = ::SafeArrayCreateVectorEx(VT_UI1, 0, cdata, NULL);
for (LONG k = 0; k < (int)cdata; k++)
{
BYTE ch = (BYTE)postData[k];
::SafeArrayPutElement(psaHunk, &k, &ch);
}
_variant_t requestBuffer;
requestBuffer.vt = (VT_ARRAY | VT_UI1);
requestBuffer.parray = psaHunk;
// 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 char* tenant_id = "2ea4955d-830e-4aa7-8ab5-661a6b9aa84d";
_variant_t async(true);
_bstr_t tokenUri("https://login.microsoftonline.com/");
tokenUri += _bstr_t(tenant_id);
tokenUri += _bstr_t("/oauth2/v2.0/token");
httpRequest->setOption((MSXML2::SERVERXMLHTTP_OPTION)2, 13056);
httpRequest->open(L"POST", tokenUri, async, vtMissing, vtMissing);
httpRequest->setRequestHeader(L"Content-Type", L"application/x-www-form-urlencoded");
httpRequest->send(requestBuffer);
while (httpRequest->readyState != 4) {
httpRequest->waitForResponse(1);
}
long status = httpRequest->status;
_bstr_t responseText = httpRequest->responseText;
if (status < 200 || status >= 300)
{
printf("Failed to get access token from server: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
IOAuthResponseParserPtr oauthParser = NULL;
oauthParser.CreateInstance(__uuidof(EAGetMailObjLib::OAuthResponseParser));
oauthParser->Load(responseText);
accessToken = oauthParser->AccessToken;
if (accessToken.length() == 0)
{
printf("Failed to parse access token from server response: %d %s\r\n", status, (const char*)responseText);
return FALSE;
}
return TRUE;
}
catch (_com_error &ep)
{
printf("Failed to get access token: %s", (const char*)ep.Description());
return FALSE;
}
}
_bstr_t GenerateRequestData()
{
// You should create your client id and client secret,
// do not use the following client id in production environment, it is used for test purpose only.
const char* client_id = "b22194da-44d6-4320-a067-e86a275d6fa4";
const char* client_secret = "VTO8Q~eo0JCXc291jcM4wnhZ_GXyKMu.";
const char* scope = "https://outlook.office365.com/.default";
_bstr_t buffer = "client_id=";
buffer += client_id;
buffer += "&client_secret=";
buffer += client_secret;
buffer += "&scope=";
buffer += scope;
buffer += "&grant_type=client_credentials";
return buffer;
}
void RetrieveEmail()
{
::CoInitialize(NULL);
_bstr_t accessToken;
// request access token from MS server without user interaction
if (!RequestAccessToken((const char*)GenerateRequestData(), accessToken))
{
return;
}
const char* Office365User = "grant-test@emailarchitect.net";
try
{
TCHAR szPath[MAX_PATH + 1];
_getCurrentPath(szPath, MAX_PATH);
TCHAR szMailBox[MAX_PATH + 1];
wsprintf(szMailBox, _T("%s\\inbox"), szPath);
// Create a folder to store emails
::CreateDirectory(szMailBox, NULL);
IMailServerPtr oServer = NULL;
oServer.CreateInstance(__uuidof(EAGetMailObjLib::MailServer));
// Office365 server address
oServer->Server = _bstr_t("outlook.office365.com");
oServer->User = _bstr_t(Office365User);
// Use access token as password
oServer->Password = accessToken;
// Use OAUTH 2.0
oServer->AuthType = MailServerAuthXOAUTH2;
// Use IMAP4 Protocol
oServer->Protocol = MailServerImap4;
// Enable SSL Connection
oServer->SSLConnection = VARIANT_TRUE;
// Set IMAP4 SSL Port
oServer->Port = 993;
IMailClientPtr oClient = NULL;
oClient.CreateInstance(__uuidof(EAGetMailObjLib::MailClient));
oClient->LicenseCode = _T("TryIt");
_tprintf(_T("Connecting %s ...\r\n"), (const TCHAR*)oServer->Server);
oClient->Connect(oServer);
// Get new email only, if you want to get all emails, please remove this line
oClient->GetMailInfosParam->GetMailInfosOptions = GetMailInfos_NewOnly;
IMailInfoCollectionPtr infos = oClient->GetMailInfoList();
_tprintf(_T("Total %d emails\r\n"), infos->Count);
for (long i = 0; i < infos->Count; i++)
{
IMailInfoPtr pInfo = infos->GetItem(i);
_tprintf(_T("Index: %d; Size: %d; UIDL: %s\r\n\r\n"),
pInfo->Index, pInfo->Size, (const TCHAR*)pInfo->UIDL);
TCHAR szFile[MAX_PATH + 1];
// Generate a random file name by current local datetime,
// You can use your method to generate the filename if you do not like it
SYSTEMTIME curtm;
::GetLocalTime(&curtm);
::wsprintf(szFile, _T("%s\\%04d%02d%02d%02d%02d%02d%03d%d.eml"),
szMailBox,
curtm.wYear,
curtm.wMonth,
curtm.wDay,
curtm.wHour,
curtm.wMinute,
curtm.wSecond,
curtm.wMilliseconds,
i);
// Receive email from POP3 server
IMailPtr oMail = oClient->GetMail(pInfo);
_tprintf(_T("From: %s\r\n"), (const TCHAR*)oMail->From->Address);
_tprintf(_T("Subject: %s\r\n"), (const TCHAR*)oMail->Subject);
// Save email to local disk
oMail->SaveAs(szFile, VARIANT_TRUE);
// Mark email as read to prevent retrieving this email again.
oClient->MarkAsRead(pInfo, VARIANT_TRUE);
// If you want to delete current email, please use Delete method instead of MarkAsRead
// oClient->Delete(pInfo);
}
// Delete method just mark the email as deleted,
// Quit method expunge the emails from server exactly.
oClient->Quit();
}
catch (_com_error &ep)
{
_tprintf(_T("Error: %s\r\n"), (const TCHAR*)ep.Description());
}
}
You don’t have to request access token
every time. By default,
access token
expiration time is 3600 seconds, you can reuse the access token
repeatedly before it is expired.
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
If you are not the tenant administrator and you don’t have the permission to create or grant the application in Azure, or if your code is too complex or out of maintenance, and you don’t want to change anything in your source codes, then you can have a try with EA Oauth Service for Offic365. It provides an easy way for the legacy email application that doesn’t support OAUTH 2.0 to send and retrieve email from Office 365 without changing any codes. SMTP, POP, IMAP and SSL/TLS protocols are supported.
Appendix
Comments
If you have any comments or questions about above example codes, please click here to add your comments.