試圖使用Gmail API將電子郵件發送到App Engine。以前,我在Credentials頁面中創建了一個Service帳號密鑰,它會生成一個位於setServiceAccountPrivateKeyFromP12File參數中的.P12文件。它有一個ID帳號加入帳號[email protected]到服務帳號頁面。代碼:通過Gmail API發送電子郵件Google App Engine
/* Application name. */
private static final String APPLICATION_NAME = "appnamefromappengine";
String emailAddress = "[email protected]";
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
try {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Set<String> scopes = new HashSet<String>();
scopes.add(GmailScopes.GMAIL_SEND);
scopes.add(GmailScopes.GMAIL_COMPOSE);
scopes.add(GmailScopes.MAIL_GOOGLE_COM);
scopes.add("https://www.googleapis.com/auth/admin.directory.user");
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(emailAddress)
.setServiceAccountPrivateKeyFromP12File(new File("/home/myuser/Test/src/main/webapp/resources/**somename**cd30e7118ad5.p12"))
.setServiceAccountScopes(scopes)
.setServiceAccountUser("[email protected]")
.build();
Gmail gmail = new Gmail
.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Test Mail");
message.setText("Test Mail");
Message msg = createMessageWithEmail(message); //createMessageWithEmail function from Gmail API
msg = gmail.users().messages().send(emailAddress, msg).execute();
System.out.println("Mail was sent. Message id: " + msg.getId());
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
它返回我這個錯誤:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request { "code" : 400,
"errors" : [ { "domain" : "global", "message" : "Bad Request", "reason" : "failedPrecondition" } ],
"message" : "Bad Request" }
我不知道我設置錯了這裏的代碼或到谷歌雲控制檯哪個參數。我還能嘗試什麼?
入住這太問題[Gmail的REST API:400錯誤的請求+失敗前提條件(http://stackoverflow.com/questions/29327846/gmail-rest- api-400-bad-request-failed-precondition)如果它可以幫助你:) – KENdi
@KENdi提供的鏈接有幫助嗎?你是否能夠縮小或解決失敗的先決條件? – Nicholas
這是@Nicholas。問題在於我沒有將委派域範圍的權限配置到服務帳戶到管理控制檯中。無論哪種方式,如果有人想使用Gmail API發送電子郵件,所有代碼都可以完全工作。這個問題可以補充回答如何使用Email API授權發件人進入代碼。一旦某人在該部分註冊了一封電子郵件,該如何引用該電子郵件。感謝所有。 –