Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.0.0+

Gmail SMTP, IMAP, and POP3: Refresh an OAuth2 Token

See more OAuth2 Examples

Refresh a Gmail access token without opening a browser. Use the same OAuth client and the offline refresh token saved during initial authorization. A refreshed token can authenticate SMTP, IMAP, or POP3 for the authorized mailbox.

Google normally does not return another refresh token. The example retains the saved refresh token when omitted, accepts a replacement when provided, preserves the granted scope when omitted, and records the new access token's issue time and lifetime. A failed exchange leaves the old cache untouched. File writes are checked; production applications should use protected storage and serialize/atomically commit updates.

Access tokens normally last about an hour. Refresh ahead of expiry and reconnect long-lived protocol sessions when necessary. Refresh does not add scopes or restore a revoked grant. An invalid_grant response can require fresh user authorization; do not retry it indefinitely. External apps in Testing normally receive seven-day refresh tokens for this scope.

Gmail SMTP, IMAP, and POP3 use the https://mail.google.com/ OAuth scope. Narrower Gmail REST scopes such as gmail.send or gmail.readonly do not authorize these protocols. Public applications using this restricted scope must meet Google's verification requirements. See Gmail OAuth scopes and XOAUTH2.

Google documentation

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
oauth: HCkOAuth2;
fresh: HCkJsonObject;
obtained: HCkDateTime;

begin
success := False;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

token := CkJsonObject_Create();
success := CkJsonObject_LoadFile(token,'gmail-mail-token.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read gmail-mail-token.json from the private working directory.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(token,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(token,'refresh_token','',True) = True)) then
  begin
    Memo1.Lines.Add('Authorize the account for offline access first.');
    Exit;
  end;
oauth := CkOAuth2_Create();
CkOAuth2_putTokenEndpoint(oauth,'https://oauth2.googleapis.com/token');
CkOAuth2_putClientId(oauth,'YOUR_DESKTOP_CLIENT_ID');
CkOAuth2_putClientSecret(oauth,'YOUR_DESKTOP_CLIENT_SECRET');
CkOAuth2_putRefreshToken(oauth,CkJsonObject__stringOf(token,'refresh_token'));
success := CkOAuth2_RefreshAccessToken(oauth);
if (success <> True) then
  begin
    Memo1.Lines.Add('Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.');
    Exit;
  end;
fresh := CkJsonObject_Create();
success := CkJsonObject_Load(fresh,CkOAuth2__accessTokenResponse(oauth));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not parse the refresh response.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(fresh,'access_token') <> 1) or (CkJsonObject_StringOfEquals(fresh,'access_token','',True) = True)) then
  begin
    Memo1.Lines.Add('The refresh response did not contain an access token.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(fresh,'refresh_token') <> 1) or (CkJsonObject_StringOfEquals(fresh,'refresh_token','',True) = True)) then
  begin
    CkJsonObject_UpdateString(fresh,'refresh_token',CkJsonObject__stringOf(token,'refresh_token'));
  end;
if ((CkJsonObject_HasMember(fresh,'scope') <> True) and (CkJsonObject_JsonTypeOf(token,'scope') = 1)) then
  begin
    CkJsonObject_UpdateString(fresh,'scope',CkJsonObject__stringOf(token,'scope'));
  end;
//  Google normally omits refresh_token on refresh. Keep the previous one in that case.
//  Use the new expires_in, not the old response's expiration information.
obtained := CkDateTime_Create();
CkDateTime_SetFromCurrentSystemTime(obtained);
CkJsonObject_UpdateString(fresh,'obtained_at',CkDateTime__getAsTimestamp(obtained,False));
success := CkJsonObject_WriteFile(fresh,'gmail-mail-token.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the refreshed credentials.');
    Exit;
  end;
Memo1.Lines.Add('Refreshed the access token.');

CkJsonObject_Dispose(token);
CkOAuth2_Dispose(oauth);
CkJsonObject_Dispose(fresh);
CkDateTime_Dispose(obtained);