Gmail SMTP, IMAP, and POP3: Obtain an OAuth2 Token
See more OAuth2 Examples
Obtain a Gmail OAuth2 access token and an offline refresh token for a desktop application using the system browser and a loopback listener. This one authorization works with SMTP, IMAP, and POP3 for the same account; a separate consent flow for each protocol is unnecessary.
In Google Cloud, configure the consent screen and create an OAuth client of type Desktop app. Supply that client's ID and secret. Add the account as a test user while an external app is in Testing. Desktop clients are public clients: an embedded client secret is not a reliable secret. This example uses PKCE with S256 and Chilkat's authorization state handling. The browser and application must run on the same computer; this is not a web-backend redirect handler.
access_type=offline requests a refresh token; prompt=consent is used for this initial setup. Subsequent runs should refresh the saved grant instead of prompting every time. The checked file write saves gmail-mail-token.json in a private working directory without printing credentials. Use one cache per account and OAuth client. Applications with concurrent jobs should serialize and atomically replace cache files.
For an external application in Testing, a refresh token with the mail scope normally expires after seven days. Revocation, account password changes, and organization policies can also require fresh authorization. An access token is short-lived; use its expires_in and the saved UTC obtained_at, allowing a clock margin, to schedule refresh.
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.
Chilkat Objective-C Downloads
#import <CkoOAuth2.h>
#import <NSString.h>
#import <CkoJsonObject.h>
#import <CkoDateTime.h>
BOOL success = NO;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkoOAuth2 *oauth = [[CkoOAuth2 alloc] init];
oauth.TokenEndpoint = @"https://oauth2.googleapis.com/token";
oauth.ClientId = @"YOUR_DESKTOP_CLIENT_ID";
oauth.ClientSecret = @"YOUR_DESKTOP_CLIENT_SECRET";
oauth.AuthorizationEndpoint = @"https://accounts.google.com/o/oauth2/v2/auth";
oauth.LocalHost = @"127.0.0.1";
oauth.ListenPort = [NSNumber numberWithInt:55568];
oauth.ListenPortRangeEnd = [NSNumber numberWithInt:55578];
oauth.CodeChallenge = YES;
oauth.CodeChallengeMethod = @"S256";
oauth.Scope = @"https://mail.google.com/";
success = [oauth AddAuthQueryParam: @"access_type" value: @"offline"];
if (success != YES) {
NSLog(@"%@",@"Could not configure offline access.");
return;
}
// This is the interactive setup step. Subsequent refreshes use the saved refresh token.
success = [oauth AddAuthQueryParam: @"prompt" value: @"consent"];
if (success != YES) {
NSLog(@"%@",@"Could not configure consent.");
return;
}
NSString *authUrl = [oauth StartAuth];
if (oauth.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not start the loopback listener.");
return;
}
success = [oauth LaunchBrowser: authUrl];
if (success != YES) {
[oauth Cancel];
NSLog(@"%@",@"Could not open the system browser.");
return;
}
int waited = 0;
while ((([oauth.AuthFlowState intValue] < 3) && (waited < 180000))) {
[oauth SleepMs: [NSNumber numberWithInt: 200]];
waited = waited + 200;
}
if ([oauth.AuthFlowState intValue] < 3) {
[oauth Cancel];
NSLog(@"%@",@"Authorization timed out.");
return;
}
if ([oauth.AuthFlowState intValue] != 3) {
NSLog(@"%@%d",@"Authorization did not complete. Flow state: ",[oauth.AuthFlowState intValue]);
return;
}
CkoJsonObject *token = [[CkoJsonObject alloc] init];
success = [token Load: oauth.AccessTokenResponse];
if (success != YES) {
NSLog(@"%@",@"Could not parse the token response.");
return;
}
if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOfEquals: @"refresh_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"No offline refresh token was issued. The existing cache was preserved.");
return;
}
if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOfEquals: @"access_token" value: @"" caseSensitive: YES] == YES)) {
NSLog(@"%@",@"The response did not contain an access token. The existing cache was preserved.");
return;
}
CkoDateTime *obtained = [[CkoDateTime alloc] init];
[obtained SetFromCurrentSystemTime];
[token UpdateString: @"obtained_at" value: [obtained GetAsTimestamp: NO]];
// The token response includes expires_in (seconds). Refresh before the access token expires.
// The file contains credentials: use a private, access-controlled directory.
success = [token WriteFile: @"gmail-mail-token.json"];
if (success != YES) {
NSLog(@"%@",@"Could not save the token file.");
return;
}
NSLog(@"%@",@"Credentials saved in the private working directory.");