Sample code for 30+ languages & platforms
Dart

OAuth2 for a GMail using a P12 Service Account Key

See more GMail REST API Examples

Demonstrates how to use GMail with OAuth2 for a service account within a Google Workspace Account where your email domain is custom (e.g., @yourcompany.com).

Note: This example does not work for Personal Google Accounts where the email domain is @gmail.com

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  final http = CkHttp();

  // --------------------------------------------------------------------------------
  // 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
  // --------------------------------------------------------------------------------
  // Begin by loading your Google service account key (.p12)
  final cert = CkCert();
  try {
    cert.loadPfxFile('c:/someDirectory/keys/chilkat25-cbd7b42afbd8.p12', 'notasecret');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // The ISS is your service account email address ending in gserviceaccount.com.
  final iss = 'chilkatsvc@chilkat25.iam.gserviceaccount.com';

  // The scope is always the following string:
  final scope = 'https://mail.google.com/';

  // The sub is your company email address
  final oauthSub = 'bob@yourcompany.com';

  // The access token is valid for this number of seconds.
  final numSec = 3600;

  final String accessToken;
  try {
    accessToken = http.gSvcOauthAccessToken(iss, scope, oauthSub, numSec, cert);
    print('access token: $accessToken');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.

  // -----------------------------------------------------------------------
  final mailman = CkMailMan();

  // Set the properties for the GMail SMTP server:
  mailman.smtpHost = 'smtp.gmail.com';
  mailman.smtpPort = 587;
  mailman.startTLS = true;

  mailman.smtpUsername = 'bob@yourcompany.com';
  mailman.oAuth2AccessToken = accessToken;

  // Create a new email object
  final email = CkEmail();

  email.subject = 'This is a test';
  email.body = 'This is a test';
  email.from = 'Bob <bob@yourcompany.com>';
  email.addTo('Recipient', 'recipient@example.com');
  // To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

  try {
    mailman.sendEmail(email);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    mailman.closeSmtpConnection();
  } on ChilkatException {
    print('Connection to SMTP server not closed cleanly.');
  }

  print('Successfully sent email using Gmail with a service account key.');
}