通过Google API发送电子邮件 - 前提条件失败

发布于 2025-02-13 20:01:32 字数 3462 浏览 1 评论 0 原文

我正在尝试使用我的Google Workspace帐户在我的 Spring Boot 应用程序中发送电子邮件。 我去了Google Cloud Console,我:

  1. 创建了一个新项目,然后选择了它(即 application_name_from_google_console
  2. 启用了Gmail API
  3. 创建的OAuth同意屏幕,该屏幕
  4. 已导航到“凭据”,并创建了一个新的“服务corpertiralsscortenters ) ”,这给了我一封新电子邮件,我会称之为 email_address_created_when_creating_the_service_account

然后我有此代码,该代码会导致失败的前提错误:

    // invoking code
    Gmail service = buildEmailService();
    Message message = createMessage(fromEmailAddress, toEmailAddress, subject, text);
    _sendMessage(service, message);


    private Gmail buildEmailService() throws MessagingException {
        GoogleCredentials credentials = null;
        try {
            String serviceAccountJson = "{\n" +
                    "  \"type\": \"service_account\",\n" +
                    "  \"project_id\": \"lybro-355514\",\n" +
                    "  \"private_key_id\.........." 
            ;

            InputStream targetStream = new ByteArrayInputStream(serviceAccountJson.getBytes());
            credentials = ServiceAccountCredentials.fromStream(targetStream)
                    .createScoped(Collections.singletonList(GmailScopes.GMAIL_SEND))
               .createDelegated(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT);

        } catch (IOException e) {
            e.printStackTrace();
            throw new MessagingException(e.getMessage());
        }
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

        Gmail service = new Gmail.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName(APPLICATION_NAME_FROM_GOOGLE_CONSOLE)
                .build();

        return service;
    }


    private void _sendMessage(Gmail service, Message message) throws MessagingException {
        try {
            // Create send message
            message = service.users().messages().send(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT, message).execute();
            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            GoogleJsonError error = e.getDetails();
            if (error != null && error.getCode() == 403) {
                System.err.println("Unable to send message: " + e.getDetails());
            } else {
                e.printStackTrace();
                throw new MessagingException(e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new MessagingException(e.getMessage());
        }
    }

使用此代码,我会收到以下错误:

javax.mail.MessagingException: 400 Bad Request POST https://gmail.googleapis.com/gmail/v1/users/[email protected]/messages/send {   "code": 400,   "errors": [
    {
      "domain": "global",
      "message": "Precondition check failed.",
      "reason": "failedPrecondition"
    }   ],   "message": "Precondition check failed.",   "status": "FAILED_PRECONDITION" }

I'm trying to use my Google Workspace account to send emails in my Spring Boot application.
I went to the Google Cloud Console and I:

  1. Created a new project and selected it (namely APPLICATION_NAME_FROM_GOOGLE_CONSOLE)
  2. Enabled the Gmail API
  3. Created a OAuth consent screen
  4. Navigated to "Credentials" and created a new "Service account credentials", which gave me a new email I will call it EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT

Then I have this code which causes a FAILED PRECONDITION error:

    // invoking code
    Gmail service = buildEmailService();
    Message message = createMessage(fromEmailAddress, toEmailAddress, subject, text);
    _sendMessage(service, message);


    private Gmail buildEmailService() throws MessagingException {
        GoogleCredentials credentials = null;
        try {
            String serviceAccountJson = "{\n" +
                    "  \"type\": \"service_account\",\n" +
                    "  \"project_id\": \"lybro-355514\",\n" +
                    "  \"private_key_id\.........." 
            ;

            InputStream targetStream = new ByteArrayInputStream(serviceAccountJson.getBytes());
            credentials = ServiceAccountCredentials.fromStream(targetStream)
                    .createScoped(Collections.singletonList(GmailScopes.GMAIL_SEND))
               .createDelegated(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT);

        } catch (IOException e) {
            e.printStackTrace();
            throw new MessagingException(e.getMessage());
        }
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);

        Gmail service = new Gmail.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName(APPLICATION_NAME_FROM_GOOGLE_CONSOLE)
                .build();

        return service;
    }


    private void _sendMessage(Gmail service, Message message) throws MessagingException {
        try {
            // Create send message
            message = service.users().messages().send(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT, message).execute();
            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
        } catch (GoogleJsonResponseException e) {
            // TODO(developer) - handle error appropriately
            GoogleJsonError error = e.getDetails();
            if (error != null && error.getCode() == 403) {
                System.err.println("Unable to send message: " + e.getDetails());
            } else {
                e.printStackTrace();
                throw new MessagingException(e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new MessagingException(e.getMessage());
        }
    }

With this code, I get the following error:

javax.mail.MessagingException: 400 Bad Request POST https://gmail.googleapis.com/gmail/v1/users/[email protected]/messages/send {   "code": 400,   "errors": [
    {
      "domain": "global",
      "message": "Precondition check failed.",
      "reason": "failedPrecondition"
    }   ],   "message": "Precondition check failed.",   "status": "FAILED_PRECONDITION" }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶花眉 2025-02-20 20:01:34
createDelegated(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT)

您应该将其设置的电子邮件是您已配置委托的工作空间帐户上用户的电子邮件。

createDelegated("[email protected]")

发送的发送也应从您的域上的用户发送。服务的方式对您进行预先配置的方式来处理他们在域上模仿用户。这样,服务帐户假装是该用户。

如果您尚未阅读此信息:我强烈建议这样做。

createDelegated(EMAIL_ADDRESS_CREATED_WHEN_CREATING_THE_SERVICE_ACCOUNT)

The email you should be setting this to is the email of the user on your workspace account that you have configured delegation for.

createDelegated("[email protected]")

Send should also be sent from the user on your domain. The way service accounts you preconfigure them to work impersonate a user on your domain. In this way the service account is pretending to be that user.

If you have not already read this: Perform Google Workspace Domain-Wide Delegation of Authority I can highly recommend doing so.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文