我有一个Google Apps帐户。我尝试使用服务帐户代表用户发送电子邮件。
我已经浏览过互联网,没有任何工作,我几乎不知所措。
我已经关注了Java指南,我仍然继续com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
为什么这段代码片段会给我401 Unauthorized?
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("something@something-something.iam.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(new File("path/to/file/myProject.p12"))
.setServiceAccountScopes(GmailScopes.all())
.setServiceAccountUser("user@mydomain.org")
.build();
Gmail gmailService = new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName("My App") // DOES IT MATTER WHAT THIS IS SET TO?
.build();
MimeMessage mimeMessage = createEmail("myemail@gmail.com", "user@mydomain.org", "Testing", "hey");
sendMessage(gmailService, "me", mimeMessage);
这些方法基本上是从Googles文档中复制/粘贴的:
/**
* Create a MimeMessage using the parameters provided.
*
* @param to email address of the receiver
* @param from email address of the sender, the mailbox account
* @param subject subject of the email
* @param bodyText body text of the email
* @return the MimeMessage to be used to send email
* @throws MessagingException
*/
public static MimeMessage createEmail(String to,
String from,
String subject,
String bodyText)
throws MessagingException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO,
new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
/**
* Send an email from the user's mailbox to its recipient.
*
* @param service Authorized Gmail API instance.
* @param userId User's email address. The special value "me"
* can be used to indicate the authenticated user.
* @param email Email to be sent.
* @throws MessagingException
* @throws IOException
*/
public static void sendMessage(Gmail service, String userId, MimeMessage email)
throws MessagingException, IOException {
Message message = createMessageWithEmail(email);
System.out.println("userId = " + userId);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
/**
* Create a Message from an email
*
* @param email Email to be set to raw of message
* @return Message containing base64url encoded email.
* @throws IOException
* @throws MessagingException
*/
public static Message createMessageWithEmail(MimeMessage email)
throws MessagingException, IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
email.writeTo(baos);
String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
我刚收到这个堆栈跟踪:
com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
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.my.services.NotificationServiceTest.testGmailCredential(NotificationServiceTest.java:96)
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)
我已创建服务帐户并设置为域范围授权,此处是我的Manage API客户端访问范围的屏幕截图:
我错过了什么,我一直得到401 Unauthorized?
答案 0 :(得分:6)
在与Google支持人员进行了长时间且有用的电话通话后,我们终于找到了如果我将GmailScopes.all()
更改为下面的明确范围,那么它就可以了。
Collection<String> SCOPES
= Collections.unmodifiableCollection(
Arrays.asList(
new String[]{
GmailScopes.GMAIL_COMPOSE,
GmailScopes.GMAIL_SEND
}));
支持人员并不是100%肯定,但他认为可能因为我的用户无法访问所有gmail范围而且我指定GmailScopes.all()
它是错误的&#39在检查我试图使用的范围之前,使用401 Unauthorized。
答案 1 :(得分:3)
查看here,您好像还没有访问令牌!将refeshToken添加到您的代码中:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("something@something-something.iam.gserviceaccount.com")
.setServiceAccountPrivateKeyFromP12File(new File("path/to/file/myProject.p12"))
.setServiceAccountScopes(GmailScopes.all())
.setServiceAccountUser("user@mydomain.org")
.build();
credential.refreshToken();
答案 2 :(得分:2)
使用访问令牌进行API调用时,最常见的错误是:
有时,HTTP 4xx的响应正文中存在更多解释。例如,在Java客户端中,您应该记录错误,因为它有助于排除故障:
try {
// Make your Google API call
} catch (GoogleJsonResponseException e) {
GoogleJsonError error = e.getDetails();
// Print out the message and errors
}
每当您获得HTTP 4xx并记录该响应时,您可以在此处获取现有代码并进行API调用。这将返回一些有用的信息。
如果令牌无效,您可以按照以下步骤操作。
您可以通过this链接调试所有内容。它甚至有一个教程视频!