Helper module for Gmail OAuth2 authentication flow.
This module helps you obtain and refresh OAuth2 tokens for Gmail API.
Getting Initial Tokens
Get the authorization URL and visit it in a browser:
iex> Voile.Mailer.GmailAuth.authorization_url()
After user authorizes, you'll get a code in the redirect URL
Exchange the code for tokens:
iex> {:ok, tokens} = Voile.Mailer.GmailAuth.get_tokens("YOUR_CODE_HERE") iex> IO.inspect(tokens) %{ "access_token" => "...", "refresh_token" => "...", "expires_in" => 3599, "scope" => "https://www.googleapis.com/auth/gmail.send", "token_type" => "Bearer" }
Store these in your environment variables:
export GMAIL_ACCESS_TOKEN="..." export GMAIL_REFRESH_TOKEN="..."
Summary
Functions
Generate the OAuth2 authorization URL.
Get the client ID from environment or config.
Get the client secret from environment or config.
Exchange an authorization code for access and refresh tokens.
Interactive helper to walk through the OAuth2 flow in IEx.
Get the redirect URI from environment or config. Defaults to http://localhost:4000/auth/gmail/callback for development. Note: This is different from the Google OAuth login callback (/auth/google/callback)
Refresh an access token using a refresh token.
Functions
Generate the OAuth2 authorization URL.
Visit this URL in a browser to authorize the application. After authorization, you'll be redirected with a code parameter.
Get the client ID from environment or config.
Get the client secret from environment or config.
Exchange an authorization code for access and refresh tokens.
Example
{:ok, tokens} = Voile.Mailer.GmailAuth.get_tokens("4/0AeanS...")Returns:
{:ok, %{
"access_token" => "...",
"refresh_token" => "...",
"expires_in" => 3599,
"scope" => "...",
"token_type" => "Bearer"
}}
Interactive helper to walk through the OAuth2 flow in IEx.
Usage
iex> Voile.Mailer.GmailAuth.interactive_setup()
Get the redirect URI from environment or config. Defaults to http://localhost:4000/auth/gmail/callback for development. Note: This is different from the Google OAuth login callback (/auth/google/callback)
Refresh an access token using a refresh token.
Example
{:ok, new_access_token} = Voile.Mailer.GmailAuth.refresh_token(
refresh_token,
client_id,
client_secret
)