Google-Dotnet-Samples icon indicating copy to clipboard operation
Google-Dotnet-Samples copied to clipboard

Error Bad Request [400] using Gmail API

Open kiquenet opened this issue 7 years ago • 1 comments

I have this code, using Service Account:

`

            string[] Scopes = {
                Google.Apis.Gmail.v1.GmailService.Scope.MailGoogleCom,
                Google.Apis.Gmail.v1. GmailService.Scope.GmailModify,
                Google.Apis.Gmail.v1.GmailService.Scope.GmailCompose,
                Google.Apis.Gmail.v1.GmailService.Scope.GmailSend };

        var pathSecrets = @".\ContactosProject-dcbe8450d418.json";
        var serviceAccountEmail = "[email protected]";

        var gmailSvc = GmailAPI.ServiceAccountHelper.AuthenticateServiceAccount(serviceAccountEmail, pathSecrets, Scopes);

        string plainText = "To: [email protected]\r\n" +
                           "Subject: subject Test\r\n" +
                           "Content-Type: text/html; charset=us-ascii\r\n\r\n" +
                           "<h1>Body Test </h1>";

        var newMsg = new Google.Apis.Gmail.v1.Data.Message();
        newMsg.Raw = Base64UrlEncode(plainText.ToString());
        gmailSvc.Users.Messages.Send(newMsg, "me").Execute();`

I use your AuthenticateServiceAccount class for samples.

I get the error:

Result StackTrace: at Google.Apis.Requests.ClientServiceRequest1.<ParseResponse>d__34.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Google.Apis.Requests.ClientServiceRequest1.Execute()

Google.GoogleApiException: Google.Apis.Requests.RequestError Bad Request [400] Errors [ Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global] ]

The same error for

        Google.Apis.Gmail.v1.UsersResource.LabelsResource.ListRequest request = gmailSvc.Users.Labels.List("me");
        var Labels = request.Execute().Labels;

Any suggestions?

kiquenet avatar Feb 08 '18 08:02 kiquenet

Linda Lawton says:

Service accounts will only work with Gsuite email accounts. The admin of the Gsuite (domain) account will have to grant the service account access to the users email account. Unfortunately i don't have access to a Gsuite account so cant help you set it up. This might help Perform G Suite Domain-Wide Delegation of Authority

If this is a normal Gmail user account you are trying to access then you cant use a service account. You will either have to go though the SMTP / IMAP servers or using Oauth2 to authenticate the user.

Then, any full sample step-by-step using Oauth2 to authenticate the user?

kiquenet avatar Feb 14 '18 16:02 kiquenet