By default, you need to enable ” Allowing less secure apps” in Gmail/G Suite, 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:
Before you can use the following codes, please download EASendMail SMTP Component and install it on your machine at first. Full sample proejcts are included in this installer.
Install from NuGet
You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:
Install-Package EASendMail
Note
If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.
To use EASendMail SMTP Component in your project, the first step is Add reference
of EASendMail to your project
. Please create or open your project with Visual Studio,
then go to menu
-> Project
-> Add Reference
-> .NET
-> Browse...
, and select
Installation Path\Lib\net[version]\EASendMail.dll
from your disk, click Open
-> OK
, the reference of EASendMail
will be added to your project, and you can start to use it to send email
in your project.
Because EASendMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.
Separate builds of run-time assembly for .NET Framework 1.1, 2.0, 3.5, 4.0, 4.5, 4.6.1, .NET Core 3.1, .NET 5.0, .NET Standard 2.0 and .NET Compact Framework 2.0, 3.5.
File | .NET Framework Version |
Lib\net20\EASendMail.dll |
Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version. |
Lib\net40\EASendMail.dll |
Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version. |
Lib\net45\EASendMail.dll |
Built with .NET Framework 4.5
It requires .NET Framework 4.5 or later version. |
Lib\net461\EASendMail.dll |
Built with .NET Framework 4.6.1
It requires .NET Framework 4.6.1 or later version. |
Lib\netcoreapp3.1\EASendMail.dll |
Built with .NET Core 3.1
It requires .NET Core 3.1 or later version. |
Lib\net5.0\EASendMail.dll |
Built with .NET 5.0
It requires .NET 5.0 or later version. |
Lib\netstandard2.0\EASendMail.dll |
Built with .NET Standard 2.0
It requires .NET Standard 2.0 or later version. |
Lib\net20-cf\EASendMail.dll |
Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version. |
Lib\net35-cf\EASendMail.dll |
Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version. |
Normal OAuth requires user input user/password in Web Browser. Obviously, it is not suitable for background service. In this case, you should use google service account to access G Suite email service without user interaction. Service account only works for G Suite user, it doesn’t work for personal Gmail account.
To use “G Suite Service Account OAuth” in your application, you should create a project in Google Developers Console at first.
Important
You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite. But G Suite administrator must authorize service account in G Suite Admin Console to access user mailbox.
Open Google Developer Console, create a new project by https://console.developers.google.com/projectcreate.
After you created the project, select it from projects list as current project.
Click "Credentials"
-> "Manage service accounts"
Click "CREATE SERVICE ACCOUNT"
Input a name for your service account, click "CREATE"
In "Service account permissions"
, select "Project"
-> "Owner"
as role
In "Grant users access to this service account"
, keep everything default and click "DONE"
After service account is created, you should enable "Domain-wide delegation"
and create service key pair
to access G Suite user mailbox.
Go back to your service account, click "Edit"
-> "SHOW DOMAIN-WIDE DELEGATION"
,
check "Enable G Suite Domain-wide Delegation"
, input a name for product oauth consent, click "Save"
.
Go back to your service account again, click "Create Key"
, you can select "p12"
or "json"
key type,
both can work well, then you will get a file which contains private key, save the file to local disk.
Now you have created service account with key pair successfully. You can use created private key in your
codes to request "access token"
impersonating a user in G Suite.
To access user data in G Suite, you must get authorization from G Suite administrator.
You should go to service accounts list, click "View Client ID"
like this:
Then copy your “Client ID” and service account email address, forward it to G Suite administrator for authorization.
Enable Gmail API in "Library"
-> Search "Gmail"
, then click "Gmail API"
and enable it.
If you use Gmail API protocol to send email, you should enable this API, if you use SMTP protocol, you don’t have to enable it.
To use service account to access user mailbox in G Suite, G Suite Administrator should authorize specified service account at first.
Important
Important Notice: You can use any google user to create service account, it doesn’t require service account owner is a user in G Suite. But G Suite administrator must authorize service account in G Suite Admin Console to access user mailbox.
G Suite Administrator should open admin.google.com, go to Admin Console, click "Security"
> API Control
;
Click Add new and enter your service account client ID.
Enter the client ID
of the service account or OAuth2 client ID of the app.
In OAuth Scopes, add each scope that the application can access (should be appropriately narrow).
and input https://mail.google.com/
, email
, profile
in One or More API Scopes, click "Authorize"
.
If you use Gmail API protocol instead of SMTP protocol, input: https://mail.google.com/
, email
, profile
.
After G Suite administrator authorized service account, you can use it to access any users mailbox in G Suite domain.
Because HttpWebRequest is used to get access token from web service.
If you’re using legacy .NET framework (.NET 2.0 and .NET 4.0),
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 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.
' You can install Google.Apis.Auth.OAuth2 by NuGet
' Install-Package Google.Apis.Auth
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Security.Cryptography.X509Certificates
Imports System.Net
Imports System.IO
Imports Google.Apis.Auth.OAuth2
Imports EASendMail
Public Sub SendMail()
Try
' service account email address
Const serviceAccount As String = "xxxxxx@xxxxx.iam.gserviceaccount.com"
' import service account key p12 certificate.
Dim certificate = New X509Certificate2("D:\MyData\myoauth-77dec4d192ec.p12", "notasecret", X509KeyStorageFlags.Exportable)
' G Suite user email address
Dim gsuiteUser = "user@gsuitdomain.com"
Dim serviceAccountCredentialInitializer = New ServiceAccountCredential.Initializer(serviceAccount) With {
.User = gsuiteUser,
.Scopes = {"https://mail.google.com/"}
}.FromCertificate(certificate)
' if service account key is in json format, copy the private key from json file:
' "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
' and import it like this:
' Dim privateKey As String = "-----BEGIN PRIVATE KEY-----" & vbLf & "MIIEv...revdd" & vbLf & "-----END PRIVATE KEY-----" & vbLf
' Dim serviceAccountCredentialInitializer = New ServiceAccountCredential.Initializer(serviceAccount) With {
' .User = gsuiteUser,
' .Scopes = {"https://mail.google.com/"}
' }.FromPrivateKey(privateKey)
' request access token
Dim credential = New ServiceAccountCredential(serviceAccountCredentialInitializer)
If Not credential.RequestAccessTokenAsync(CancellationToken.None).Result Then
Throw New InvalidOperationException("Access token failed.")
End If
Dim server = New SmtpServer("smtp.gmail.com 587")
server.ConnectType = SmtpConnectType.ConnectSSLAuto
server.User = gsuiteUser
server.Password = credential.Token.AccessToken
server.AuthType = SmtpAuthType.XOAUTH2
Dim mail = New SmtpMail("TryIt")
mail.From = gsuiteUser
mail.[To] = "support@emailarchitect.net"
mail.Subject = "service account oauth test"
mail.TextBody = "this is a test, don't reply"
Dim smtp = New SmtpClient()
smtp.SendMail(server, mail)
Console.WriteLine("Message delivered!")
Catch ep As Exception
Console.WriteLine(ep.ToString())
End Try
End Sub
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.