1

I have a google access token, registred with scopes for gmail api and google contacts api. I get it this way:

  var code = Request.QueryString["code"];

  OAuth2Parameters parameters = new OAuth2Parameters()
        {
            ClientId = clientId,
            ClientSecret = clientSecret,
            RedirectUri = redirectUri,
            Scope = scopes
        };

        if (code == null)
        {
            string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            return Redirect(url);
        }

        parameters.AccessCode = code;
        OAuthUtil.GetAccessToken(parameters);

And now I need to send email via gmail api. But in google documentation I found only one way to authenticate in gmail api use UserCredential:

  var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

But I already have working access token, how can I use it to send email?

Dmitriy Kovalenko
  • 3,437
  • 3
  • 19
  • 39
  • [This answer](http://stackoverflow.com/questions/24728793/creating-a-message-for-gmail-api-in-c-sharp) might give some clues. – Tholle Jul 26 '16 at 12:36

2 Answers2

2

https://github.com/google/google-api-dotnet-client/issues/761

Looks like you used the same examples i did, turns out when you exchange the code for a token response thats the flow you need to pass into the constructor for the UserCredential object.

var clientSecrets = new ClientSecrets { ClientId = clientId, ClientSecret = secret };
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes = new[] { @"https://www.googleapis.com/auth/gmail.settings.basic" }

            });

            TokenResponse token = await flow.ExchangeCodeForTokenAsync("userEmail", authCode, "http://localhost:30297", CancellationToken.None);

            UserCredential cred = new UserCredential(flow, "me", token);

            string accessToken = token.AccessToken;
            var service = new GmailService(
                new BaseClientService.Initializer { HttpClientInitializer = cred });
0

From what I can tell, the .NET client doesn't allow you to create a UserCredential object from an existing access token. Instead, use the authorization flows provided by the library and use them to generate the correct objects.

Eric Koleda
  • 12,420
  • 1
  • 33
  • 51