将不同的电子邮件设置为收件人时,拒绝委托my.mail@email.com&qot;的Gmail API返回

人气:619 发布:2022-10-16 标签: gmail-api kotlin

问题描述

我正在使用Gmail API创建草稿。 当我创建收件人是我自己的电子邮件(生成凭据的电子邮件)的草稿邮件时,一切正常,但当我尝试使用不同的电子邮件时,会打印以下消息:

{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Delegation denied for my.email.here@gmail.com",
    "reason" : "forbidden"
  } ],
  "message" : "Delegation denied for my.email.here@gmail.com",
  "status" : "PERMISSION_DENIED"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)

这就是我如何组装MimeMessage

val props = Properties()
val session = Session.getDefaultInstance(props, null)
val message = MimeMessage(session)
message.setFrom(message.sender)
message.addRecipient(JavaxMessage.RecipientType.TO, InternetAddress("different.email.here@gmail.com"))
message.subject = subject

我正在使用的作用域:

// "https://www.googleapis.com/auth/gmail.compose"
GmailScopes.GMAIL_COMPOSE

我尝试了很多方法以使其起作用,但没有任何成功。

推荐答案

my.email.here@gmail.com的委派被拒绝

此电子邮件似乎是标准的Gmail电子邮件地址。您似乎正在尝试将服务帐户委派给具有标准Gmail电子邮件地址的用户。

服务帐户仅适用于Google工作区电子邮件帐户。您需要设置对serveries帐户的全域委派,然后才能设置委派用户。

如果要使用标准Gmail帐户,则需要使用OAuth2授权用户。

private fun getCredentials(httpTransport: NetHttpTransport): Credential? {
    val inputStream = File("credentials.json").inputStream()
    val clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, InputStreamReader(inputStream))
    val flow = GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(FileDataStoreFactory(File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build()
    val receiver = LocalServerReceiver.Builder().setPort(8888).build()
    return AuthorizationCodeInstalledApp(flow, receiver).authorize("user")
}



 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;
    }

Sending

325