相关疑难解决方法(0)

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

我正在尝试使用google java api服务发送基于Gmail REST API的邮件.我已通过Google Develover Console配置了应用程序客户端并下载了p12和json文件.

我使用过这个示例程序,https://developers.google.com/gmail/api/guides/sending#sending_messages ...

此示例有效,但这是基于GoogleAuthorizationCodeFlow.我只想从服务器到服务器工作,直接调用,而不是打开浏览器来获取访问令牌......我得到了它(访问令牌)但最后我收到了错误请求....为什么? ?我收到的信息不仅仅是"Bad Request"和"Precondition Failed"

基于此,我按照以下步骤操作:

  1. 第一步:根据我的客户帐户邮件和p12生成的文件创建GoogleCredential对象:

    GoogleCredential  credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport())
                                        .setJsonFactory(new JacksonFactory())
                                        .setServiceAccountId(serviceAccountUserEmail)
                                        .setServiceAccountScopes(scopes)
                                        .setServiceAccountPrivateKeyFromP12File(
                                                    new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))                             
                                                            .build();
    
    Run Code Online (Sandbox Code Playgroud)

在这里,我必须指出,我有很多问题需要使用ClientID而不是ClientMail.它必须使用@ developer.gserviceaccount.com帐户而不是.apps.googleusercontent.com.如果你不发送这个参数确定,你得到一个"无效授予"错误.这在此处说明:https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization

  1. 第二步:根据凭据创建Gmail服务:

    Gmail gmailService = new Gmail.Builder(httpTransport,
                                                  jsonFactory,
                                                  credential)
                                                .setApplicationName(APP_NAME)
                                                    .build();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 第三步从MimmeMessage创建Google原始消息:

    private static Message _createMessageWithEmail(final MimeMessage email) throws MessagingException, IOException {
    
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    email.writeTo(bytes);
    String encodedEmail =       Base64.encodeBase64URLSafeString(bytes.toByteArray());      
    Message message = new Message();    
    message.setRaw(encodedEmail);
    return message;
    
    Run Code Online (Sandbox Code Playgroud)

    }

  3. 第四步调 …

java rest google-cloud-endpoints gmail-api

12
推荐指数
1
解决办法
1万
查看次数

标签 统计

gmail-api ×1

google-cloud-endpoints ×1

java ×1

rest ×1