2017-10-29 5 views
2

java env의 hotmail 인증 액세스 토큰을 사용하여 전자 메일을 보내려고합니다. 내가 콘솔에 무엇을 얻을 여기Java의 hotmail 액세스 토큰을 사용하여 전자 메일 보내기

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': '[email protected]'"+ 
      "}"+ 
      "}"+ 
     "],"+ 
     "'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(); 
} 

되고 : 나는 성공적으로 이메일을 보낼 수 없습니다 여전히 documentation하지만 보았다, 여기 내 코드입니다

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="[email protected]*", 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+... 

그리고 그것은받은 편지함 폴더에서 이메일을 얻을하고 사용자에게 표시하는 데 사용 된 것과 동일 무엇,668,359을3210 자습서에서 설명합니다. 또한 api에 올바른 범위를 추가하여 메일을 보낼 수 있음을 잊지 않았습니다. "Mail.Send".

인증 토큰을 사용하여 성공적으로 이메일을 보내는 방법을 찾아야합니다. 도움을 받으십시오.

+0

왜 SMTP/자바 메일 API를 사용하지 않는? – madhead

+0

보낸 사람 전자 메일 주소와 인증 토큰 만 있기 때문에 암호가 없기 때문에 SMTP를 사용하면 암호를 알지 못해도 기꺼이 사용할 수 있지만 여전히 모릅니다! –

+0

내가 원하는 것을 수행하는 정확한 방법을 보여주는 다음 항목을 발견했지만 호출 할 때 핸드 셰이크와 관련하여 예외가 발생합니다. OutputStreamWriter streamWriter = new OutputStreamWriter (connection.getOutputStream()); 예외 "되지 않는 curveId 29"이다 이이 [링크]이다 (https://pritomkumar.blogspot.com/2016/12/java-send-email-using-office-365-oauth. html) 내가 필요한 것을 보여줍니다. –

답변

0

나는 해결책을 발견 한 내가 잘못된 this documentation에 따라, 내 코드는 지금 보이는 호출 된 이후 나는 URL을 변경해야 할 것 같습니다

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': '[email protected]'" + "}" + "}" 
      + "]," + "'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(); 
    } 
}