I would like to send an email using Gmail OAuth protocol from Python. For some background, the general process of my program takes user input, creates an image, then sends an email. In theory the program could be sending hundreds of emails at some point. The issue that I ran into is when I tried to retrieve a token for OAuth, I received an Unauthorized redirect url error. The app has not been verified nor do I have a G Suite Admin account, but every tutorial I walk through make no mention of this. The only redirect urls I have enabled are https://developers.google.com/oauthplayground and http://localhost:8080/oauth2callback, which are both in the client_secret.json file I download from the credentials page on google developers.
Here is what I have:
import base64
import httplib2
from email.mime.text import MIMEText
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'client_secret.json'
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'
# Location of the credentials storage file
STORAGE = Storage('gmail.storage')
# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()
# Try to retrieve credentials from storage or run the flow to generate them
# This is where it fails.
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run(flow, STORAGE, http=http)
# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)
# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)
# create a message to send
message = MIMEText("Message goes here.")
message['to'] = "[email protected]"
message['from'] = "[email protected]"
message['subject'] = "your subject goes here"
body = {'raw': base64.b64encode(message.as_string())}
# send it
try:
message = (gmail_service.users().messages().send(userId="me", body=body).execute())
print('Message Id: %s' % message['id'])
print(message)
except Exception as error:
print('An error occurred: %s' % error)


redirect_uriin the OAuth consent screen and after that redownload the JSON file with the credentials. Try to do that and confirm if you still having trouble with this error.redirect_urifield? Try to add it in there and check if you can get past that error. There are some question around the same error too and maybe some already solve your issue 1 or 2run_local_serverto make that page exist. That would handle all the token interaction as stated in the documentation.