By default, you need to enable ” Allowing less secure apps” in Gmail, then you can send email with user/password SMTP authentication.
However Google will disable traditional user authentication in the future, switching to Google OAuth is strongly recommended now.
Sections:
EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). Before you can use the following example codes, you should download the EASendMail Installer and install it on your machine at first.
To use EASendMail SMTP ActiveX Object in your project, the first step is “Add reference
of EASendMail to your project”. Please select menu -> Project
-> References
->
and select EASendMailObj ActiveX Object
, click OK
, the reference will be added
to current project, and you can start to use it to send email in your VB6 project.
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 send email in your VBA project.
The Gmail IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Google Web Login instead of inputting user and password directly in application.
To send email using Gmail OAuth in your application, you should create a project in the Google Cloud console, go to Menu menu > IAM & Admin > Create a Project:
In the Google Cloud console, go to Menu ->APIs & Services
->Dashboard
->OAuth consent screen
, selectExternal
user type, input necessary information and click Save.
APIs & Services
-> Dashboard
-> Credentials
Credentials
-> Create Credentials
-> OAuth client ID
-> Web application
or Other (Desktop Application)
. It depends on your application type."Create"
, you will get client id
and client secret
, download and save them for later use."Library"
-> Search "Gmail"
, then click "Gmail API"
and enable it."OAuth consent screen"
-> "Edit App"
..../auth/userinfo.email
, .../auth/userinfo.profile
, openid
, https://mail.google.com/
and .../auth/gmail.send
scopes in OAuth consent screen
-> Edit App
-> Scopes
-> Add or remove scopes
.Gmail supports SMTP + OAuth, but the API (https://mail.google.com/
) scope is restricted API
which requests to have full access to the Gmail account. Restricted API is throttled before your project is authenticated in by Google.
Using less restricted API (https://www.googleapis.com/auth/gmail.send
) scope to send email via Gmail server is recommended.
"../auth/gmail.send"
scope to avoid your app throttled;https://mail.google.com/
scope.If you use OAuth in a web application, you should use a web page or controller to
get authorization code from Google OAuth Server.
So you need to add your page or web application routing path to Authorized Redirect URIs
in APIs & Services
-> Dashboard
-> Credentials
->
OAuth 2.0 Client IDs
-> Your Client ID
.
By default, your app is in test mode, you should add the user email address to the test users, then the user can test your app.
Go to OAuth consent screen
-> Test users
-> Add users
-> input the user email address.
If you want to publish your app, you should submit your app for verification by clicking “Publish”.
If your users are seeing the “unverified app” screen, it is because your OAuth request includes additional scopes that haven’t been approved. The user can still choose to proceed with the request, but the app will be limited in the number of users that can grant permission to your app when requesting unapproved sensitive or restricted scopes.
Learn more detail from: https://developers.google.com/workspace/guides/create-project.
Please have the following option checked while the user logins by web browser and grants the consent. By default it is not checked due to Google security policy.
Because HttpWebRequest is used to get access token from web service.
If you’re using .NET framework (.NET 2.0 - 3.5 and .NET 4.x),
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
You can use client id and client secret to get the user email address and access token like this:
EASendMail Installation Path\Samples_{Programming language/Developer Tool}\Oauth
project.You don’t have to open browser 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.
After it is expired, you can use refresh token
to refresh access token
directly without opening browser.
You can find full sample project in EASendMail installation path
to learn how to refresh token
.
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.
Here is a simple application which demonstrates how to use Google OAuth to do user authentication and send email.
Note
This sample cannot handle the event of Web Browser is closed by user manually before authentication is completed.
You can refer to the better sample project which uses Web Browser Control
in EASendMail installation path.
Option Explicit
Const ConnectNormal = 0
Const ConnectSSLAuto = 1
Const ConnectSTARTTLS = 2
Const ConnectDirectSSL = 3
Const ConnectTryTLS = 4
Const AuthAuto = -1
Const AuthLogin = 0
Const AuthNtlm = 1
Const AuthCramMd5 = 2
Const AuthPlain = 3
Const AuthMsn = 4
Const AuthXoauth2 = 5
' client configuration
' 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 clientID = "507778793027-cfod2rvnnks95ed17d7ejepp16l1tvg8.apps.googleusercontent.com"
Const clientSecret = "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"
Const scope = "openid%20profile%20email%20https://mail.google.com"
Const authUri = "https://accounts.google.com/o/oauth2/auth"
Const tokenUri = "https://oauth2.googleapis.com/token"
Public Sub DoOauthAndSendEmail()
Dim httpListener As New EASendMailObjLib.httpListener
' Creates a redirect URI using an available port on the loopback address.
If Not httpListener.Create("127.0.0.1", 0) Then
Debug.Print "Failed to listen on " & httpListener.GetLastError()
Exit Sub
End If
Dim szUri
szUri = "http://127.0.0.1:" & httpListener.ListenPort
Debug.Print "listen on " & szUri
' Creates the OAuth 2.0 authorization request.
Dim authorizationRequest
authorizationRequest = authUri
authorizationRequest = authorizationRequest & "?response_type=code&scope="
authorizationRequest = authorizationRequest & scope
authorizationRequest = authorizationRequest & "&redirect_uri="
authorizationRequest = authorizationRequest & szUri
authorizationRequest = authorizationRequest & "&client_id="
authorizationRequest = authorizationRequest & clientID
Debug.Print "open " & authorizationRequest
' Opens request in the browser.
Dim browserUi As New EASendMailObjLib.browserUi
browserUi.OpenUrl authorizationRequest
' Waits for the OAuth authorization response.
Do While True
If Not httpListener.GetRequestUrl(100) Then
Debug.Print "Failed to wait:"
Debug.Print httpListener.GetLastError()
Exit Do
End If
If httpListener.RequestUrl <> "" Then
Exit Do
End If
DoEvents
Loop
' Send response and stop http listener.
httpListener.SendResponse "200", "text/html; charset=utf-8", "<html><head></head><body>Please return to the app and close current window.</body></html>"
httpListener.Close
Dim requestUri
requestUri = httpListener.RequestUrl
Debug.Print "RequestUri: " & requestUri
Dim errorCode
' Checks for errors.
errorCode = ParseParameter(requestUri, "error=")
If errorCode <> "" Then
Debug.Print "OAuth authorization error: " & errorCode
Exit Sub
End If
' Check authorization code
Dim code
code = ParseParameter(requestUri, "code=")
If code = "" Then
Debug.Print "Malformed authorization response: " & requestUri
Exit Sub
End If
Debug.Print "Authorization code: " & code
Dim responseText
responseText = RequestAccessToken(code, szUri)
Debug.Print responseText
Dim parser As New EASendMailObjLib.OAuthResponseParser
parser.Load responseText
Dim user, accessToken
user = parser.EmailInIdToken
accessToken = parser.accessToken
If accessToken = "" Then
Debug.Print "Failed to request access token, return!"
Exit Sub
End If
Debug.Print "User: " & user
Debug.Print "AccessToken: " & accessToken
SendMailWithXOAUTH2 user, accessToken
End Sub
' path?parameter1=value1¶meter2=value2#anchor;
Private Function ParseParameter(ByVal uri As String, ByVal key As String) As String
ParseParameter = ""
If uri = "" Or key = "" Then
Exit Function
End If
Dim pos As Integer
pos = InStr(1, uri, "?")
If pos <= 0 Then
Exit Function
End If
uri = Mid(uri, pos + 1)
Dim i, parameters, uriParameter
parameters = Split(uri, "&")
For i = LBound(parameters) To UBound(parameters)
uriParameter = parameters(i)
If InStr(1, uriParameter, key, vbTextCompare) = 1 Then
Dim value
value = Mid(uriParameter, Len(key) + 1)
pos = InStr(1, value, "#")
If pos > 0 Then
value = Mid(value, 1, pos - 1)
End If
ParseParameter = value
Exit Function
End If
Next
End Function
Private Function RequestAccessToken(ByVal code As String, ByVal redirectUri As String) As String
Debug.Print "Exchanging code for tokens..."
RequestAccessToken = ""
Dim responseText
responseText = ""
Dim httpRequest
Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP.6.0")
Dim tokenRequestBody
tokenRequestBody = "code="
tokenRequestBody = tokenRequestBody & code
tokenRequestBody = tokenRequestBody & "&redirect_uri="
tokenRequestBody = tokenRequestBody & redirectUri
tokenRequestBody = tokenRequestBody & "&client_id="
tokenRequestBody = tokenRequestBody & clientID
tokenRequestBody = tokenRequestBody & "&client_secret="
tokenRequestBody = tokenRequestBody & clientSecret
tokenRequestBody = tokenRequestBody & "&grant_type=authorization_code"
httpRequest.setOption 2, 13056
httpRequest.Open "POST", tokenUri, True
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send tokenRequestBody
Do While httpRequest.ReadyState <> 4
DoEvents
httpRequest.waitForResponse (1)
Loop
Dim Status
Status = httpRequest.Status
responseText = httpRequest.responseText
RequestAccessToken = responseText
If Status < 200 Or Status >= 300 Then
Debug.Print "Failed to refresh access token from server."
End If
End Function
Private Sub SendMailWithXOAUTH2(ByVal userEmail As String, ByVal accessToken As String)
Dim oSmtp As New EASendMailObjLib.Mail
oSmtp.LicenseCode = "TryIt"
' Gmail SMTP server address
oSmtp.ServerAddr = "smtp.gmail.com"
' Using 587 port, you can also use 465 or 25 port
oSmtp.ServerPort = 587
' Enable SSL/TLS connection
oSmtp.ConnectType = ConnectSSLAuto
' OAUTH/XOAUTH2 type
oSmtp.AuthType = AuthXoauth2
' set user authentication
oSmtp.UserName = userEmail
' use access token as password
oSmtp.Password = accessToken
' Your email address
oSmtp.FromAddr = userEmail
' Please change recipient address to yours for test
oSmtp.AddRecipient "Support Team", "support@emailarchitect.net", 0
oSmtp.Subject = "Test email using Gmail Oauth"
oSmtp.BodyText = "Hello, this is a test...."
Debug.Print "start to send email using OAUTH 2.0 ..."
If oSmtp.SendMail() = 0 Then
Debug.Print "The email has been submitted to server successfully!"
Else
Debug.Print oSmtp.GetLastErrDescription()
End If
End Sub
If you use Google OAuth in classic ASP application, you should use a ASP page to
get authorization code instead of HttpListener. You need to add your path
to Authorized Redirect URIs
in your Google project.
' Please add http://localhost/gmailoauth/default.asp to Authorized redirect URIs in your Google/MS Azure project.
Dim code
code = Request.QueryString("code")
You can find a full sample project in EASendMail installation path\Samples_ASPClassic
.
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 Gmail. It provides an easy way for the legacy email application that doesn’t support OAUTH 2.0 to send and retrieve email from Gmail without changing any codes. SMTP, POP, IMAP and SSL/TLS protocols are supported.
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.