在将邮件发送为中添加其他电子邮件地址
我想使用Google Gmail API在Send mail as部分添加另一个电子邮件地址。我试过这个代码,有人能帮帮我吗?
SendAs primaryAlias = null;
ListSendAsResponse aliases = service.users().settings().sendAs().list("me").execute();
for (SendAs alias: aliases.getSendAs()) {
if (alias.getIsPrimary()) {
primaryAlias = alias;
break;
}
}
System.out.println("Updated signature for " + primaryAlias.getDisplayName());
SendAs aliasSettings = new SendAs().setSignature("I heart cats.")
.setSendAsEmail("j.ohnast.baby@gmail.com");
SendAs r = service.users().settings().sendAs().create("me", aliasSettings).execute();
System.out.println("Updated signature for " + r.getDisplayName());
线程"Main"中出现异常
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Access restricted to service accounts that have been delegated domain-wide authority",
"reason" : "forbidden"
} ],
"message" : "Access restricted to service accounts that have been delegated domain-wide authority"
}
解决方案
别名只能由具有全域权限的服务帐号使用Users.settings.sendAs: create
创建,可以从documentation中撤回。
.p12
文件。
以下是如何在Java中设置服务帐户的示例:
public class ServiceAccountJava
{
private static final String APPLICATION_NAME = "XXX";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final List<String> SCOPES = Collections.singletonList(XXX);
public static void main(String... args) throws IOException, GeneralSecurityException
{
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
File pk12=new File("XXX.p12");
String serviceAccount="XXX@XXX-XXX.iam.gserviceaccount.com";
// Builder necessary for the ability to refresh tokens
GoogleCredential getCredentials = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(serviceAccount)
.setServiceAccountPrivateKeyFromP12File(pk12) //RESOURCES_CLIENT_SECRETS_JSON, SRC_RESOURCES_KEY_P12
.setServiceAccountScopes(SCOPES)
.setServiceAccountUser("XXX") //the user whom you want to impersonate
.build();
...
}
}
相关文章