Zig
Zig
OAuth2 for a GMail using a JSON Service Account Key
See more GMail SMTP/IMAP/POP Examples
This example shows how to obtain an OAuth2 access token for Gmail using a Google Service Account and a JSON private key. Once acquired, the access token can be used to send emails. Remember, upon token expiration, this process needs to be repeated to obtain a new token. Note: This procedure is specific to OAuth2 with Google Service Account keys.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// --------------------------------------------------------------------------------
// For a step-by-step guide for setting up your Google Workspace service account,
// see Setup Google Workspace Account for Sending SMTP GMail from a Service Account
// --------------------------------------------------------------------------------
// First load the JSON key into a string.
const fac = try chilkat.FileAccess.init();
defer fac.deinit();
const json_key = fac.readEntireTextFile(alloc, "qa_data/googleApi/chilkat25-b4214220e565.json", "utf-8") catch {
std.debug.print("{s}\n", .{try fac.getLastErrorText(alloc)});
return;
};
// A Google service account JSON private key looks like this:
// {
// "type": "service_account",
// "project_id": "chilkat25",
// "private_key_id": "b4214220f565881e19eeb97c2699bf5a0d1e3e0b",
// "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQ...NXcM=\n-----END PRIVATE KEY-----\n",
// "client_email": "chilkatsvc@chilkat25.iam.gserviceaccount.com",
// "client_id": "109122032928932715958",
// "auth_uri": "https://accounts.google.com/o/oauth2/auth",
// "token_uri": "https://oauth2.googleapis.com/token",
// "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
// "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/chilkatsvc%40chilkat25.iam.gserviceaccount.com",
// "universe_domain": "googleapis.com"
// }
const g_auth = try chilkat.AuthGoogle.init();
defer g_auth.deinit();
g_auth.setJsonKey(json_key);
// Specify a scope.
g_auth.setScope("https://mail.google.com/");
// Request an access token that is valid for this many seconds.
g_auth.setExpireNumSeconds(3600);
// When using a Google Workspace account with Gmail APIs, a service account can impersonate a user
// via a process called domain-wide delegation � and the "sub" claim in the JWT is what enables this.
// Domain-wide delegation allows a Google Workspace administrator to authorize a service account to
// act on behalf of any user in the domain, without user interaction.
// This is required for server-to-server access to user data � such as reading/sending Gmail from a background service.
// This is your company email address.
g_auth.setSubEmailAddress("info@chilkat.xyz");
// Connect to www.googleapis.com using TLS
const tls_sock = try chilkat.Socket.init();
defer tls_sock.deinit();
tls_sock.connect("www.googleapis.com", 443, true, 5000) catch {
std.debug.print("{s}\n", .{try tls_sock.getLastErrorText(alloc)});
return;
};
// Send the request to obtain the access token.
g_auth.obtainAccessToken(tls_sock) catch {
std.debug.print("{s}\n", .{try g_auth.getLastErrorText(alloc)});
return;
};
// Examine the access token:
const access_token = try g_auth.getAccessToken(alloc);
std.debug.print("Access Token: {s}\n", .{access_token});
// Sample output:
// ya29.a0AW4XtxjGTD67Z8 .... IRw0218
// The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.
// -----------------------------------------------------------------------
const mailman = try chilkat.MailMan.init();
defer mailman.deinit();
// Set the properties for the GMail SMTP server:
mailman.setSmtpHost("smtp.gmail.com");
mailman.setSmtpPort(587);
mailman.setStartTLS(true);
mailman.setSmtpUsername("info@chilkat.xyz");
mailman.setOAuth2AccessToken(access_token);
// Create a new email object
const email = try chilkat.Email.init();
defer email.deinit();
email.setSubject("This is a test");
email.setBody("This is a test");
email.setFrom("Chilkat Test <info@chilkat.xyz>");
try email.addTo("Chilkat Software", "info@chilkatsoft.com");
// To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.
mailman.sendEmail(email) catch {
std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
return;
};
mailman.closeSmtpConnection() catch {
std.debug.print("Connection to SMTP server not closed cleanly.\n", .{});
};
std.debug.print("Successfully sent email using Gmail with a service account key.\n", .{});
}