我已遵循此处描述的所有步骤:https://developers.google.com/identity/protocols/oauth2/service-account
我已经在GSuite中选中了域委派来创建服务帐户。
[我已经添加了在GSuite中发送电子邮件的权限。
[已将应用添加到受信任的应用中。
但是发送邮件时收到以下错误
{
"code": 400,
"errors": [
{
"domain": "global",
"message": "Bad Request",
"reason": "failedPrecondition"
}
],
"message": "Bad Request"
}
代码:
private static final String APPLICATION_NAME = "xxxx-send-email";
private static final GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = "xxxxx-273014-426ae03a7dbd.p12";
private static final List<String> scopes = new ArrayList<String>() {
{
add(GmailScopes.GMAIL_SEND);
add(DirectoryScopes.ADMIN_DIRECTORY_USER);
}
};
public static void main(String[] args) {
try {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("xxxxxxxx57")
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(new File(GmailSend.class.getResource(KEY_FILE_LOCATION).getFile()))
.build();
Gmail gmail = new Gmail.Builder(httpTransport, JSON_FACTORY, null).setHttpRequestInitializer(credential).setApplicationName("xxxxxx-send-email").build();
Message message = new Message();
message.setRaw(RAW_TEST);
gmail.users().messages().send(userId, message).execute();
} catch(Throwable th) {
th.printStackTrace(System.out);
}
}
更改
Gmail gmail = new Gmail.Builder(httpTransport, JSON_FACTORY, null)
到
Gmail gmail = new Gmail.Builder(httpTransport, JSON_FACTORY, credential)
也:您的代码中包含了范围DirectoryScopes.ADMIN_DIRECTORY_USER
。但是您也没有提及您是否已授予服务帐户相应的权限。