Authorize a desktop application to use Gmail
See more GMail REST API Examples
Enable the Gmail API, configure the OAuth consent screen, and create a Desktop app OAuth client. Launch the system browser and receive the authorization code on a loopback listener. The sample requests read-only access with PKCE and offline access. For another operation, select the scope in that example before authorizing. Gmail scopes.
Run in a private, user-only directory. The file contains bearer credentials. In a deployed application use protected credential storage. To reuse an existing grant, copy the older examples’ qa_data/tokens/gmail.json to gmail-token.json in this private directory. The token retains its original scopes. Gmail clients using IMAP, POP, or SMTP with OAuth need the https://mail.google.com/ scope. Use a separate cache for each user and client.
Chilkat Rust Downloads
// Assumes Chilkat is unlocked. See Global Unlock Sample.
let oauth = chilkat::OAuth2::new();
oauth.set_token_endpoint("https://oauth2.googleapis.com/token");
oauth.set_client_id("YOUR_DESKTOP_CLIENT_ID");
oauth.set_client_secret("YOUR_DESKTOP_CLIENT_SECRET");
oauth.set_authorization_endpoint("https://accounts.google.com/o/oauth2/v2/auth");
oauth.set_local_host("127.0.0.1");
oauth.set_listen_port(55568);
oauth.set_listen_port_range_end(55578);
oauth.set_code_challenge(true);
oauth.set_code_challenge_method("S256");
oauth.set_scope("https://www.googleapis.com/auth/gmail.readonly");
if oauth.add_auth_query_param("access_type", "offline").is_err() {
println!("Could not configure offline access.");
return;
}
// This is the interactive setup step. Subsequent refreshes use the saved refresh token.
if oauth.add_auth_query_param("prompt", "consent").is_err() {
println!("Could not configure consent.");
return;
}
let Ok(auth_url) = oauth.start_auth() else {
println!("Could not start the loopback listener.");
return;
};
if oauth.launch_browser(&auth_url).is_err() {
let _ = oauth.cancel();
println!("Could not open the system browser.");
return;
}
let mut waited = 0;
while (oauth.auth_flow_state() < 3) && (waited < 180000) {
oauth.sleep_ms(200);
waited = waited + 200;
}
if oauth.auth_flow_state() < 3 {
let _ = oauth.cancel();
println!("Authorization timed out.");
return;
}
if oauth.auth_flow_state() != 3 {
println!("Authorization did not complete. Flow state: {}", oauth.auth_flow_state());
return;
}
let token = chilkat::JsonObject::new();
if token.load(&oauth.access_token_response()).is_err() {
println!("Could not parse the token response.");
return;
}
if (token.json_type_of("refresh_token") != 1) || (token.string_of_equals("refresh_token", "", true)) {
println!("No offline refresh token was issued. The existing cache was preserved.");
return;
}
if token.write_file("gmail-token.json").is_err() {
println!("Could not save the token file.");
return;
}
println!("Credentials saved in the private working directory.");