使用Java代码OAuth2.0认证方式进行outook服务器邮箱发件,出现202后在收件方没有收到任何邮件。

Erik John 40 信誉分
2024-12-06T02:10:37.7366667+00:00

具体原因是通过后提示202状态码,但是收件方是没有收到任何的邮件。

追踪失败原因

用户的图像

分配的权限用户的图像

下方是Java代码

public class SendEmail {

    private static final String CLIENT_ID = "**";
    private static final String CLIENT_SECRET = "**";
    private static final String TENANT_ID = "****";
    private static final String AUTHORITY = "https://login.microsoftonline.com/" + TENANT_ID;
    private static final String GRAPH_API_URL = "https://graph.microsoft.com/v1.0/users/****/sendMail";

    public static void main(String[] args) {
        try {
            ConfidentialClientApplication app = ConfidentialClientApplication.builder(
                            CLIENT_ID,
                            ClientCredentialFactory.createFromSecret(CLIENT_SECRET))
                    .authority(AUTHORITY)
                    .build();

            Set<String> scopes = new HashSet<>(Collections.singletonList("https://graph.microsoft.com/.default"));
            ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(scopes)
                    .build();

            CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
            IAuthenticationResult result = future.join();

            if (result != null) {
                sendEmail(result.accessToken());
            } else {
                System.out.println("Failed to acquire access token.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendEmail(String accessToken) throws Exception {
        String toEmail = "*****";
        String subject = "Test Email";
        JSONObject bodyContent = new JSONObject().put("content", "Hello, this is a test email sent from Java using Microsoft Graph API.")
                .put("contentType", "Text");
        JSONObject messageBody = new JSONObject().put("body", bodyContent);
        JSONObject toRecipient = new JSONObject().put("emailAddress", new JSONObject().put("address", toEmail));
        JSONObject message = new JSONObject().put("message", new JSONObject()
                .put("subject", subject)
                .put("body", bodyContent)
                .put("toRecipients", new JSONArray().put(toRecipient)));

        URL url = new URL(GRAPH_API_URL);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", "Bearer " + accessToken);
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        try (OutputStream os = con.getOutputStream()) {
            byte[] input = message.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = con.getResponseCode();
        System.err.println("### O365Email 请求结果 code:" + responseCode);
        BufferedReader in;
        if (responseCode == 200) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            System.err.println("### O365Email 请求结果 code:" + responseCode);
        }

        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        if (responseCode == 200) {
            Map<String, String> map = JSON.parseObject(response.toString(), HashMap.class);
        }
        System.err.println("### 响应内容: " + response.toString());

    }
}
Windows
Windows
Microsoft 操作系统系列,可跨个人计算机、平板电脑、笔记本电脑、手机、物联网设备、独立混合现实头戴显示设备、大型协作屏幕和其他设备运行。
568 个问题
Outlook
Outlook
Microsoft 电子邮件和日历产品系列。
62 个问题
Windows 365 商业版
{count} 票

你的答案

问题作者可以将答案标记为“接受的答案”,这有助于用户了解已解决作者问题的答案。