How to Set Up Google OAuth 2.0 Login and Gmail SMTP Print

  • OAuth client ID, Gmail SMTP, Authorized redirect URIs, Login with Google, Email client setup, SSL, oogle OAuth 2.0, App Password, STARTTLS, Google Workspace SMTP, SMTP, OAuth consent screen
  • 423

Set up Google OAuth 2.0 for website sign-in by creating a web OAuth client and registering your app’s callback URL. To send mail through Gmail SMTP, configure a separate method: OAuth 2.0 with XOAUTH2, an app password where permitted, or the Google Workspace SMTP relay.

Choose the setup you need

Goal What to configure
Let users sign in with Google Use Google OpenID Connect and a web OAuth client. Request only the identity information your app needs.
Send Gmail messages from an app that supports OAuth Use smtp.gmail.com with XOAUTH2 and authorize the sending mailbox for Gmail access.
Send mail from a client that needs an SMTP password Use a Google app password if the account supports it and your organization allows it.
Send application or device mail for a Workspace domain Ask your Workspace administrator to configure smtp-relay.gmail.com for the approved senders and sending servers.

Set up Sign in with Google for a web application

  1. Choose a Cloud project. Open Google Auth Platform in the Google Cloud console. In Branding, identify the app. In Audience, choose Internal if the project and users belong to the same eligible Google Workspace organization. Choose External for users outside the organization.
  2. Create a web client. Under Clients, choose Create client and select Web application. For the server-side flow, add your framework’s exact callback under Authorized redirect URIs, for example https://example.com/auth/google/callback. If you use the browser-based Google Identity Services button, register the site under Authorized JavaScript origins as required by that integration.
  3. Configure your framework’s OpenID Connect library. Set the client ID and callback URL. Keep the client secret on the server. Request openid and add email or profile if the app uses those claims. Use the library to validate the sign-in response, including the ID token’s signature, issuer, audience and expiry. Use the token’s sub claim as the stable Google account identifier.
  4. Test and publish. Test against the registered callback with an account allowed by your app’s audience settings. Review the publishing and verification requirements in Google Auth Platform before expanding access, particularly if the app requests sensitive or restricted scopes.

For details, see Google’s OpenID Connect guide and web client configuration instructions.

Configure Gmail SMTP authentication

Setting Value for direct Gmail SMTP
Host smtp.gmail.com
Port and encryption 587 with STARTTLS, or 465 with implicit TLS.
Username and sender Use the full address of the authenticated Google mailbox. Test with that same address in the From field. Use a different From address only after it is configured and authorized.
Authentication XOAUTH2 for OAuth-capable clients or a Google app password where permitted.

Option 1: Use OAuth 2.0 with XOAUTH2

  1. Use a mail client or library that supports XOAUTH2 for SMTP. Configure authorization for the sending mailbox with the https://mail.google.com/ scope. The openid, email and profile scopes used for login do not authorize Gmail SMTP.
  2. Complete authorization as the sending user. Configure token refresh for unattended sending and store tokens in your server’s secrets manager. For an External app in Testing, Google generally issues refresh tokens for Gmail access that expire after seven days.
  3. Send a test message from the authorized mailbox and verify delivery. If your application only needs to send and can use an HTTP API, consider the Gmail API’s narrower gmail.send scope.

See Google’s documentation for Gmail XOAUTH2, refresh-token expiration and Gmail API scopes. For Node.js, see Nodemailer’s OAuth 2.0 setup.

Option 2: Use an app password if your account allows it

Enable 2-Step Verification and create an app password in your Google Account if the option is available. Use that value in the SMTP password field. Some account or organization settings make app passwords unavailable. In that case, use OAuth or ask your Workspace administrator about relay.

Option 3: Configure Google Workspace SMTP relay

A Workspace administrator can open Apps → Google Workspace → Gmail → Routing in the Admin console and configure SMTP relay service. Select the allowed senders and approved authentication settings, such as restricting access to specific public sending IP addresses. Follow your organization’s TLS policy and use smtp-relay.gmail.com with the port specified in the configuration. See Google’s SMTP relay setup instructions.

Send a test email with Nodemailer or PHPMailer

These examples use a Google app password and STARTTLS on port 587. Set GMAIL_USER, GMAIL_APP_PASSWORD and TEST_RECIPIENT in the process environment. Use a recipient inbox you control.

Node.js with Nodemailer

Install Nodemailer with npm install nodemailer. Save the example in a .cjs file and run it with Node.js.

const nodemailer = require('nodemailer');

async function sendTestEmail() {
  const { GMAIL_USER, GMAIL_APP_PASSWORD, TEST_RECIPIENT } = process.env;
  if (!GMAIL_USER || !GMAIL_APP_PASSWORD || !TEST_RECIPIENT) {
    throw new Error('Set GMAIL_USER, GMAIL_APP_PASSWORD and TEST_RECIPIENT.');
  }

  const transport = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false,
    requireTLS: true,
    auth: { user: GMAIL_USER, pass: GMAIL_APP_PASSWORD }
  });

  await transport.sendMail({
    from: GMAIL_USER,
    to: TEST_RECIPIENT,
    subject: 'Gmail SMTP test',
    text: 'This message was sent over Gmail SMTP using STARTTLS.'
  });
}

sendTestEmail().catch((error) => {
  console.error('SMTP test failed:', error.message);
  process.exitCode = 1;
});

PHP with PHPMailer

Install PHPMailer with composer require phpmailer/phpmailer. Save the PHP file alongside your Composer project’s vendor directory and run it from the command line.

<?php
use PHPMailer\PHPMailer\PHPMailer;

require __DIR__ . '/vendor/autoload.php';

$user = getenv('GMAIL_USER');
$password = getenv('GMAIL_APP_PASSWORD');
$recipient = getenv('TEST_RECIPIENT');

if (!$user || !$password || !$recipient) {
    throw new RuntimeException('Set GMAIL_USER, GMAIL_APP_PASSWORD and TEST_RECIPIENT.');
}

$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
$mail->Username = $user;
$mail->Password = $password;
$mail->setFrom($user);
$mail->addAddress($recipient);
$mail->Subject = 'Gmail SMTP test';
$mail->Body = 'This message was sent over Gmail SMTP using STARTTLS.';
$mail->send();

Troubleshoot sign-in and SMTP errors

  • redirect_uri_mismatch: Compare the callback your app actually sends with the URI registered in Google, including the scheme, hostname, port, path and trailing slash.
  • access_denied: Check the app’s audience, allowed test users and, for a managed account, the organization’s app access policy.
  • SMTP authentication failed: Check that the username matches the sending mailbox. Verify the app password is still valid, or confirm the OAuth token has Gmail access and can be refreshed.
  • TLS handshake failed: Pair port 587 with STARTTLS or port 465 with implicit TLS. Check outbound access from your application server and leave certificate verification enabled.
  • Relay denied: Confirm that the sending IP, authentication method and sender match the Workspace relay policy.
  • Message accepted by SMTP but missing from the inbox: Check for a bounce and inspect the recipient’s spam folder. For a custom domain, make sure SPF covers your actual sending services, enable DKIM through your mail provider, and review DMARC alignment.

Was this answer helpful?

« Back