Для отправки электронных писем в серверном приложении без взаимодействия с пользователем я пытаюсь заменить базовое соединение аутентификации с Exchange 365 соединением OAuth 2.0.
Я знаю, что существует альтернативный способ отправки электронных писем через Exchange 365 с помощью Microsoft Graph, но из-за ограничений API Graph, таких как определение максимум 5 пользовательских заголовков, я не могу использовать Graph.
Что касается конфигурации Exchange, я создал приложение приложение и опробовал все различные комбинации разрешений приложения и делегированного API (Mail. и SMTP.SendAsApp) для Office 365 Exchange Online.
Я также настроил это через Exchange Powershell: Set-CASMailbox -Identity -SmtpClientAuthenticationDisabled $false.
При тестировании следующего кода я всегда получаю это ошибка: Исключение в потоке «основной» jakarta.mail.AuthenticationFailedException: 535 5.7.3 Аутентификация не удалась.
В настоящее время я не уверен, забыл ли я что-то настроить в Exchange или код Java неверен. Может быть, кто-то из вас уже решил эту проблему?
package com.example.dev;
import jakarta.mail.Message;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import tools.jackson.databind.ObjectMapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
public class Main {
private static final String FROM_USER = "";
private static final String TO_USER = "";
private static final String CLIENT_ID = "";
private static final String TENANT_ID = "";
private static final String CLIENT_SECRET = "";
static void main() throws Exception {
sendMimeMessage(createMimeMessage());
}
public static MimeMessage createMimeMessage() throws Exception {
Properties props = new Properties();
Session session = Session.getInstance(props);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(FROM_USER));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(TO_USER));
mimeMessage.setSubject("My Test Subject");
mimeMessage.setText("My Test Mail Content");
mimeMessage.saveChanges();
return mimeMessage;
}
public static void sendMimeMessage(MimeMessage mimeMessage) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.writeTo(baos);
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.auth.login.disable", "true");
props.put("mail.smtp.auth.plain.disable", "true");
Session session = Session.getInstance(props);
session.setDebug(true);
String smtpUser = mimeMessage.getFrom()[0].toString();
String accessToken = getAccessToken();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.office365.com", smtpUser, accessToken);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
}
private static String getAccessToken() throws IOException {
String tokenUrl = "https://login.microsoftonline.com/" + TENANT_ID + "/oauth2/v2.0/token";
String body = "client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&scope=https%3A%2F%2Foutlook.office365.com%2F.default"
+ "&grant_type=client_credentials";
HttpURLConnection con = (HttpURLConnection) new URL(tokenUrl).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.getOutputStream().write(body.getBytes(StandardCharsets.UTF_8));
int responseCode = con.getResponseCode();
if (responseCode != 200) {
String errorResponse = new String(con.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
throw new IOException("Token request failed with HTTP " + responseCode + ": " + errorResponse);
}
String response = new String(con.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
Map json = mapper.readValue(response, Map.class);
return (String) json.get("access_token");
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... smtp-oauth