Gmail Api服务帐户提供失败的前提条件响应

时间:2016-10-27 22:15:32

标签: java gmail service-accounts

我尝试使用服务帐户在JUnit测试中简单地从gmail发送电子邮件。

我有这个测试:

@Test
public void testGmailCredential() throws GeneralSecurityException, URISyntaxException {
    try {
        InputStream is = getClass().getClassLoader().getResourceAsStream("myProject.json");
        GoogleCredential credential = GoogleCredential.fromStream(is).createScoped(GmailScopes.all());

        System.out.println("Scopes are " + credential.getServiceAccountScopesAsString());

        Gmail gmailService = new Gmail.Builder(getHttpTransport(), JSON_FACTORY, credential)
                  .setApplicationName("WHAT SHOULD THIS VALUE BE?")
                  //.setHttpRequestInitializer(credential)
                  .build();

        InternetAddress to = new InternetAddress("myemail@myurl.com", "Tom Catfish");
        InternetAddress from = new InternetAddress("myServiceAccountId@xxxxxxxxxx.iam.gserviceaccount.com", "Some Name");

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);

        email.setFrom(from);
        email.addRecipient(javax.mail.Message.RecipientType.TO, to);
        email.setSubject("Subject here");
        email.setText("body here");

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        email.writeTo(buffer);
        byte[] bytes = buffer.toByteArray();
        String encodedEmail = Base64.getUrlEncoder().encodeToString(bytes);
        Message message = new Message();
        message.setRaw(encodedEmail);     
        message = gmailService.users().messages().send("me", message).execute();

        System.out.println("Message id: " + message.getId());
        System.out.println(message.toPrettyString());
        // other code...
}

这失败了:

Scopes are https://www.googleapis.com/auth/gmail.compose
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Bad Request",
    "reason" : "failedPrecondition"
  } ],
  "message" : "Bad Request"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at com.op.services.NotificationServiceTest.testGmailCredential(NotificationServiceTest.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

我的文件src/test/resources/myProject.json包含以下信息:

{
  "type": "service_account",
  "project_id": "xxxxxxxxxxx",
  "private_key_id": "28341330...",
  "private_key": "-----BEGIN PRIVATE KEY-----\.........\n-----END PRIVATE KEY-----\n",
  "client_email": "myServiceAccountId@xxxxxxxxxx.iam.gserviceaccount.com",
  "client_id": "1182....",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myApp%40xxxxxxx.iam.gserviceaccount.com"
}

如何排除造成这种愚蠢行为的原因,而不是Google提供的有效的失败保护措施?

1 个答案:

答案 0 :(得分:0)

您可以从此处获得解决问题的完整程序:

Gmail REST API : 400 Bad Request + Failed Precondition

对于400个不良请求,我给出了答案。你可以通过这个。

  1. https://stackoverflow.com/a/36290762/2293534
  2. 此处也提供了类似的答案:Google Admin Directory API is returning 400 bad request