且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Gmail REST API:400 错误请求 + 失败的前提条件

更新时间:2021-09-25 07:22:24

这是我设法让它与 Google Apps 域一起使用的方法:

This is how I managed to get it work with a Google Apps domain:

1.- 使用谷歌应用程序的用户打开开发者控制台

1.- Using a google apps user open the developer console

2.- 创建一个新的项目(即MyProject)

2.- Create a new project (ie MyProject)

3.- 转到 [Apis &auth] > [Credentials] 并创建一个新的[Service Account] 客户 ID

3.- Go to [Apis & auth] > [Credentials] and create a new [Service Account] client ID

4.- 复制 [service account] 的 [Client ID](例如 xxx.apps.googleusercontent.com)以备后用

4.- Copy the [service account]'s [Client ID] (the one like xxx.apps.googleusercontent.com) for later use

5.- 现在您必须将域范围的权限委派给服务帐户strong> 以授权您的应用程序代表 Google Apps 域中的用户访问用户数据...所以转到您的 google 应用程序域管理控制台

5.- Now you have to Delegate domain-wide authority to the service account in order to authorize your appl to access user data on behalf of users in the Google Apps domain ... so go to your google apps domain admin console

6.- 转到 [安全] 部分并找到 [高级设置] (它可能已隐藏,因此您必须单击 [显示更多..])

6.- Go to the [Security] section and find the [Advanced Settings] (it might be hidden so you'd have to click [Show more..])

7.- 点击 [Manage API Client Access]

7.- Click con [Manage API Client Access]

8.- 将您之前在 [4] 中复制的 [Client ID] 粘贴到 [Client Name] 文本框中.

8.- Paste the [Client ID] you previously copied at [4] into the [Client Name] text box.

9.- 要授予您的应用对 Gmail 的完全访问权限,请在 [API 范围] 文本框中输入:https://mail.google.com, https://www.googleapis.com/auth/gmail.composehttps://www.googleapis.com/auth/gmail.modifyhttps://www.googleapis.com/auth/gmail.readonly(输入所有范围非常重要)

9.- To grant your app full access to gmail, at the [API Scopes] text box enter: https://mail.google.com, https://www.googleapis.com/auth/gmail.compose, https://www.googleapis.com/auth/gmail.modify, https://www.googleapis.com/auth/gmail.readonly (it's very important that you enter ALL the scopes)

现在你已经完成了所有的设置……现在是代码:

Now you've done all the settings... now the code:

1.- 创建一个 HttpTransport

1.- Create an HttpTransport

private static HttpTransport _createHttpTransport() throws GeneralSecurityException,
                                                           IOException { 
    HttpTransport httpTransport = new NetHttpTransport.Builder()                                                 
                                                      .trustCertificates(GoogleUtils.getCertificateTrustStore())
                          .build();
    return httpTransport;
}

2.- 创建一个 JSonFactory

2.- Create a JSonFactory

private static JsonFactory _createJsonFactory() {
    JsonFactory jsonFactory = new JacksonFactory();
    return jsonFactory;
}

3.- 创建谷歌凭证

private static GoogleCredential _createCredentialUsingServerToken(final HttpTransport httpTransport,
                                                                  final JsonFactory jsonFactory) throws IOException,
                                                                                                        GeneralSecurityException {
    // Use the client ID when making the OAuth 2.0 access token request (see Google's OAuth 2.0 Service Account documentation).
    String serviceAccountClientID = "327116756300-thcjqf1mvrn0geefnu6ef3pe2sm61i2q.apps.googleusercontent.com"; 

    // Use the email address when granting the service account access to supported Google APIs 
    String serviceAccountUserEmail = "xxxx@developer.gserviceaccount.com";

    GoogleCredential credential = new GoogleCredential.Builder()
                                                .setTransport(httpTransport)
                                                .setJsonFactory(jsonFactory)
                                                .setServiceAccountId(serviceAccountUserEmail)    // requesting the token
                                                .setServiceAccountPrivateKeyFromP12File(new File(SERVER_P12_SECRET_PATH))
                                                .setServiceAccountScopes(SCOPES)    // see https://developers.google.com/gmail/api/auth/scopes
                                                .setServiceAccountUser("user@example.com")
                                                .build();    
    credential.refreshToken();
    return credential;
}

注意:在 setServiceAccountUser() 方法中使用来自您的 Google Apps 域的任何用户

NOTE: At setServiceAccountUser() method use any user from your google apps domain

4.- 创建 Gmail 服务

4.- Create a Gmail Service

private static Gmail _createGmailService(final HttpTransport httpTransport,
                                         final JsonFactory jsonFactory,
                                         final GoogleCredential credential) {
    Gmail gmailService = new Gmail.Builder(httpTransport,
                                            jsonFactory,
                                            credential)
                                   .setApplicationName(APP_NAME)
                                   .build();
    return gmailService;
}

现在您可以使用 GmailService 执行任何您想做的事情,例如发送电子邮件;-) 如 https://developers.google.com/gmail/api/guides/sending

Now you can do whatever you want with the GmailService like send an email ;-) as described at https://developers.google.com/gmail/api/guides/sending