Windows
Microsoft 操作系统系列,可跨个人计算机、平板电脑、笔记本电脑、手机、物联网设备、独立混合现实头戴显示设备、大型协作屏幕和其他设备运行。
568 个问题
具体原因是通过后提示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());
}
}