(Ruby) OAuth2 for a GMail using a Service Account Key

Demonstrates how to use GMail with OAuth2 for a Google Service Account. The 1st step is to obtain a temporary access token from the Google OAuth 2.0 Authorization Server. This can be accomplished using Chilkat HTTP.

Once the access token is obtained, it may be used to send email. The access token may be used while it remains valid to send as many emails as desired. Once it expires, a new access token needs to be obtained (using the same procedure).

Note: This is for OAuth2 using Google Service account keys.

Chilkat Ruby Downloads

require 'chilkat'
# This example requires the Chilkat API to have been previously unlocked.# See Global Unlock Sample for sample code.# --------------------------------------------------------------------# Important: In most cases, this example is not what you are looking for.# This example is for OAuth2 using a Google Service Account Key.# # It is more likely that the example you actually need is here:# Get GMail SMTP Access Token# --------------------------------------------------------------------
http = Chilkat::CkHttp.new()
# When a service account (Client ID) is created at https://code.google.com/apis/console/# Google will generate a P12 key. This is a PKCS12 (PFX) file that you will download# and save. The password to access the contents of this file is "notasecret".# NOTE: The Chilkat Pfx API provides the ability to load a PFX/P12 and re-save# with a different password.# Begin by loading the downloaded .p12 into a Chilkat certificate object:
cert = Chilkat::CkCert.new()
success = cert.LoadPfxFile("/myDir/API Project-1c43a291e2a1-notasecret.p12","notasecret")
if (success != true)
print cert.lastErrorText() + "\n";
exitend# The next (and final) step is to request the access token. Chilkat internally# does all the work of forming the JWT header and JWT claim set, encoding and# signing the JWT, and sending the access token request.# The application need only provide the inputs: The iss, scope(s), sub, and the# desired duration with a max of 3600 seconds (1 hour).# # Each of these inputs is defined as follows# (see https://developers.google.com/accounts/docs/OAuth2ServiceAccount# iss: The email address of the service account.# scope: A space-delimited list of the permissions that the application requests.# sub: The email address of the user for which the application is requesting delegated access.# the "sub" may be empty if no delegation exists.# numSec: The number of seconds for which the access token will be valid (max 3600).
iss = "761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com"
scope = "https://mail.google.com/"# The sub should be your Google Apps user email address (not a gmail.com address)
sub = "YOUR_GOOGLE_APPS_USER_EMAIL_ADDRESS"
numSec = 3600
accessToken = http.g_SvcOauthAccessToken(iss,scope,sub,numSec,cert)
if (http.get_LastMethodSuccess() != true)
print http.lastErrorText() + "\n";
exitelseprint"access token: " + accessToken + "\n";
end# Now that we have the access token, it may be used to send as many emails as desired# while it remains valid. Once the access token expires, a new access token should be# retrieved and used.# -----------------------------------------------------------------------
mailman = Chilkat::CkMailMan.new()
# Set the properties for the GMail SMTP server:
mailman.put_SmtpHost("smtp.gmail.com")
mailman.put_SmtpPort(587)
mailman.put_StartTLS(true)
mailman.put_SmtpUsername("YOUR_GOOGLE_APPS_USER_EMAIL_ADDRESS")
mailman.put_OAuth2AccessToken(accessToken)
# Create a new email object
email = Chilkat::CkEmail.new()
email.put_Subject("This is a test")
email.put_Body("This is a test")
email.put_From("YOUR NAME <YOUR_GOOGLE_APPS_USER_EMAIL_ADDRESS>")
success = email.AddTo("Chilkat Admin","admin@chilkatsoft.com")
# To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.# Call SendEmail to connect to the SMTP server and send.# The connection (i.e. session) to the SMTP server remains# open so that subsequent SendEmail calls may use the# same connection.
success = mailman.SendEmail(email)
if (success != true)
print mailman.lastErrorText() + "\n";
exitend# You may close the connection here. If the connection is kept open,# the next call to mailman.SendEmail will continue using the already-established connection# (and automatically re-connect if needed).
success = mailman.CloseSmtpConnection()
if (success != true)
print"Connection to SMTP server not closed cleanly." + "\n";
endprint"Email Sent via GMail using an OAuth2 Service Account Key." + "\n";