在java中使用hotmail访问令牌发送电子邮件

时间:2017-10-29 09:15:42

标签: java json oauth outlook

我正在尝试使用java env上的hotmail授权访问令牌发送电子邮件。 ,我看过documentation,但仍然无法成功发送电子邮件,这是我的代码:

 private String doPostRequest(String accessToken) throws IOException {
    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    String url = "https://outlook.office.com/api/v2.0/me/sendmail";
    String json = "{"+
          "'Message': {"+
        "'Subject': 'Meet for lunch?',"+
        "'Body': {"+
          "'ContentType': 'Text',"+
          "'Content': 'The new cafeteria is open.'"+
        "},"+
        "'ToRecipients': [{"+
            "'EmailAddress': {"+
              "'Address': 'mymail@gmail.com'"+
            "}"+
          "}"+
        "],"+
        "'Attachments': [{"+
            "'@odata.type': '#Microsoft.OutlookServices.FileAttachment',"+
            "'Name': 'menu.txt',"+
            "'ContentBytes': 'bWFjIGFuZCBjaGVlc2UgdG9kYXk='"+
          "}"+
        "]"+
      "},"+
      "'SaveToSentItems': 'false'"+
    "}";


    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().header("User-Agent", "java-tutorial").header("client-request-id", UUID.randomUUID().toString())
            .header("return-client-request-id", "true").header("Authorization", String.format("Bearer %s", accessToken)).url(url).post(body).build();
    Response response = client.newCall(request).execute();
    System.out.println("response :"+response);
    System.out.println("responseHeader :"+response.headers());
    System.out.println("responseMessage :"+response.message());
    return response.body().string();
}

以下是我在控制台上的内容:

    response :Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://outlook.office.com/api/v2.0/me/sendmail}
responseHeader :Set-Cookie: exchangecookie=520b1dfb18d54248ba3bca9becf3a40d; expires=Mon, 29-Oct-2018 08:51:24 GMT; path=/; HttpOnly
WWW-Authenticate: Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000@*", token_types="app_asserted_user_v1 service_asserted_app_v1", authorization_uri="https://login.windows.net/common/oauth2/authorize", error="invalid_token",Basic Realm="",Basic Realm="",Basic Realm=""
request-id: 7d7030b8-c31f-4572-9c18-6a2fce3609a0
client-request-id: 66b1e177-5030-4c0e-892a-7ad276351daf
X-CalculatedFETarget: AM5P190CU001.internal.outlook.com
X-BackEndHttpStatus: 401
X-FEProxyInfo: AM5P190CA0028.EURP190.PROD.OUTLOOK.COM
X-CalculatedBETarget: AM4PR05MB1906.eurprd05.prod.outlook.com
X-BackEndHttpStatus: 401
x-ms-diagnostics: 2000010;reason="ErrorCode: 'PP_E_RPS_CERT_NOT_FOUND'. Message: 'Certificate cannot be found. Certificate required for the operation cannot be found.%0d%0a Internal error: spRPSTicket->ProcessToken failed. Failed to call CRPSDataCryptImpl::UnpackData:Certificate cannot be found. Certificate required for the operation cannot be found.%0d%0a Internal error: Failed to decrypt data. :Failed to get session key. RecipientId=293577. spCache->GetCacheItem returns error.:Cert Name: (null). SKI: ee9f500e98bf0fbc492f0b138028374ec9324da4...'";error_category="invalid_msa_ticket"
X-DiagInfo: AM4PR05MB1906
X-BEServer: AM4PR05MB1906
X-FEServer: AM5P190CA0028
X-Powered-By: ASP.NET
X-FEServer: AM4PR05CA0019
X-MSEdge-Ref: Ref A: 9F523827F0CE47DEB84ECF96913B53AE Ref B: AMS04EDGE0320 Ref C: 2017-10-29T08:51:25Z
Date: Sun, 29 Oct 2017 08:51:24 GMT
Content-Length: 0
OkHttp-Sent-Millis: 1509267094755
OkHttp-Received-Millis: 1509267094903

responseMessage :Unauthorized

请注意,授权令牌是正确的,看起来类似于:

EwAwA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAYDt8KR/8o7V7P+9ynPu97AHv8CIiJA/Zn+...

它与用于获取收件箱文件夹中的电子邮件的内容相同,并将其显示给用户,如this教程所述。 此外,我没有忘记为api添加正确的范围,以便能够发送邮件"Mail.Send"

我需要找到一种使用身份验证令牌成功发送电子邮件的方法,请帮忙。

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,看起来我需要更改网址,因为我根据this documentation调用了错误的网址,我的代码现在看起来

    public void tryingOkHttpClientPostt(String accessToken) {
    OkHttpClient client = new OkHttpClient();
    HttpUrl.Builder urlBuilder = HttpUrl.parse("https://graph.microsoft.com/v1.0/me/sendMail").newBuilder();
    String json = "{" + "'Message': {" + "'Subject': 'Meet for lunch?'," + "'Body': {" + "'ContentType': 'Text',"
            + "'Content': 'The new cafeteria is open.'" + "}," + "'ToRecipients': [{" + "'EmailAddress': {" + "'Address': 'myMail@gmail.com'" + "}" + "}"
            + "]," + "'Attachments': [{" + "'@odata.type': '#Microsoft.OutlookServices.FileAttachment'," + "'Name': 'menu.txt',"
            + "'ContentBytes': 'bWFjIGFuZCBjaGVlc2UgdG9kYXk='" + "}" + "]" + "}," + "'SaveToSentItems': 'false'" + "}";
    RequestBody body = RequestBody.create(JSON, json);
    String url = urlBuilder.build().toString();
    Request request = new Request.Builder().header("Content-Type", "application/json")
            .header("Authorization", String.format("Bearer %s", accessToken)).method("POST", body).url(url).build();
    try {
        Response response = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
}