Search code examples
.netemailgoogle-apigmail-apigoogle-api-dotnet-client

Gmail api .Net send message using access token


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?


Solution

  • 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.