skip to Main Content

I’m working on a flutter app that has a module which help user to listen to his gmail and notify him if there is a new mail delivered it’s look like this bot on telegram

for example i want list his all message so i went to this api and tring it on postmant

my request as thier guide is

curl --location --request GET 'https://gmail.googleapis.com/gmail/v1/users/me/profile?key=AIzaSyB4Eg2A34XlMp89XEdLA0aJUFAsTPn9B3o' 
--header 'Authorization: Bearer ya29.a0Ad52N395ZScRVeFUSJvAaD8jIQQE3BpdZf4awh-W_XmNc3Gb92N2CPw5Sc3BYz6QrOfPwuqP1YkzMoBxuuYAzkV7vy4MJ2alLiNI3uOfyET9Yiwga7vpVkc81LY5_4FD-ejw83DyOV9janee8EFnKo6JIafbzS6_MeFVXxfTawaCgYKAa4SARESFQHGX2Mi_H5hxg6MtI_NEFJXp91Ngw0177' 
--header 'Content-Type: application/json'

but i get this reponse

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "errors": [
            {
                "message": "Invalid Credentials",
                "domain": "global",
                "reason": "authError",
                "location": "Authorization",
                "locationType": "header"
            }
        ],
        "status": "UNAUTHENTICATED"
    }
}

i tried to do Oauth in flutter using

oauth2: ^2.0.2
oauth2_client: ^3.2.2
flutter_appauth: ^6.0.4
googleapis_auth: ^1.5.0
extension_google_sign_in_as_googleapis_auth: ^2.0.12

no one worked for me, always there is something is missing like customUriScheme / redirectUri /discoveryUrl / etc

anyone could help me how to deal with gmail api, please?

2

Answers


  1. Instead of testing it in Postman, I opted to code directly within the app. Utilizing the google_sign_in package, I obtained the current user’s access credentials/headers and utilized them to authenticate with Google’s API package(googleapis).

    Get AuthHeaders Using google_sign_in

    await _googleSignIn.signIn();
    Map<String, String>? headers = await _googleSignIn.currentUser?.authHeaders;
    
    import 'package:googleapis/gmail/v1.dart' as gMail;
    
    final authHeaders =headers; // usersAuthHeaders
    final authenticateClient = GoogleAuthClient(authHeaders);
    gmailApi = gMail.GmailApi(authenticateClient);
    

    GoogleAuthClient

    import 'package:http/http.dart' as http;
    
    class GoogleAuthClient extends http.BaseClient {
      final Map<String, String> _headers;
    
      final http.Client _client = http.Client();
    
      GoogleAuthClient(this._headers);
    
      @override
      Future<http.StreamedResponse> send(http.BaseRequest request) {
        return _client.send(request..headers.addAll(_headers));
      }
    

    Following this setup, you can proceed to iterate through and retrieve messages:

    for (gMail.Message message in results.messages ?? []) {
        // Your code here
    }
    
    Login or Signup to reply.
  2. Result is list of gMail.Message

    i’ll share more snippet of my code

    Future<void> init() async {
        final authHeaders = headers;
        final authenticateClient = GoogleAuthClient(authHeaders);
        gmailApi = gMail.GmailApi(authenticateClient);
    
        try {
          gMail.ListMessagesResponse results = await gmailApi.users.messages
              .list('me', q: 'is:inbox');
    
          for (gMail.Message message in results.messages ?? []) {
            print("Message ID : ${message.id}");
    
            gMail.Message messageData =
                await gmailApi.users.messages.get("me", message.id ?? "-");
    
            setState(() {
              messagesList.add(messageData);
            });
          }
        } catch (e) {
          print('Error initializing Gmail API: $e');
          // Handle error gracefully, maybe show an error message to the user.
        }
      }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search