oauth-2.0google-oauthgmail-apigoogle-api-python-clientgoogle-cloud-console

I get this error:- Error 400: redirect_uri_mismatch even after I registered the URI in Google Gmail API OAuth 2.0


Hello there I'm a newbie to programming. I was going to authenticate to Gmail API using oauth2 Authentication and I forgot to set the redirect URI at the first place. Then I registered it but I still get the below error code and I watched dozens of youtube videos but couldn't find an error in my code this is the second day I'm trying it. It still shows :-redirect_uri: http://localhost:8080/ in the consent screen like this:-

Please check this image

And this is my main.py file

from __future__ import print_function
import base64
from email.message import EmailMessage

import google.auth
from googleapiclient.discovery import build
import time

from Google import Create_Service

def gmail_send_message():
    """Create and send an email message
    Print the returned  message id
    Returns: Message object, including message id

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds = 'oauthkey.json' 

    scopes = ['https://mail.google.com/']

    mlist = open("mail list.txt", "r")

    #cred = google.auth.default()

    service = Create_Service(creds, 'gmail' ,'v1', scopes)
    message = EmailMessage()

    message.set_content('Hi for checking purposes only ') 

    message['from'] = 'emma.adcreaive@gmail.com'

    message['Subject'] = 'System Generated'

    for mail in mlist:
        message['to'] = mail
        # encoded message
        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

        create_message = {
            'raw': encoded_message
        }
        # pylint: disable=E1101
        send_message = (service.users().messages().send
                             (userId="me", body=create_message).execute())
        print(F'Message Id: {send_message["id"]}')
        return send_message
        time.delay("12")

if __name__ == '__main__':
    gmail_send_message()

Solution

  • You need to go to google developer console for your project and add the redirect uri to the project you must set it to this exactly

    http://localhost:8080/
    

    Credentials on the left -> edit your client add the redirect uri above.

    enter image description here

    See: Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.