Причина в том, что Microsoft ранее внесла изменения в аутентификацию электронной почты, что привело к невозможности отправки. При поиске ответов в Интернете необходимо применить регистрацию в Azure и добавить разрешения в соответствии с процессом ответа. После этих операций аутентификация не удалась при использовании аутентификации OAuth2. Шаги кода, используемые для сравнения ответов, полностью совпадают, но неясно, настроен ли вопрос в Azure или где-то еще.
Вот код:
package com.tianrun.common.email;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class OAuth2Helper {
public static void main(String[] args) throws Exception {
String accessToken = getAccessToken();
sendEmail(accessToken, "****@outlook.com", "******", "Subject", "Body of the email");
}
private static String getAccessToken() throws Exception {
String clientId = "****";
String clientSecret = "****";
String tenantId = "*****";
String scope = "https://outlook.office365.com/.default";
String authUrl = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
URL url = new URL(authUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
String postParams = "client_id=" + clientId +
"&scope=" + scope +
"&client_secret=" + clientSecret +
"&grant_type=client_credentials";
conn.getOutputStream().write(postParams.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
conn.disconnect();
// Parse the JSON response to get the access token
String accessToken = content.toString().split("\"access_token\":\"")[1].split("\"")[0];
System.out.println(accessToken);
return accessToken;
}
private static void sendEmail(String accessToken, String sender, String recipient, String subject, String body)
throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.host", "smtp.office365.com");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
props.put("mail.smtp.starttls.enable", "true");
// Create a custom Authenticator with the OAuth2 access token
Session session = Session.getInstance(props, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
}
}
Это журнал ошибок
javax.mail.AuthenticationfailedException: 535 5.7.3 Authentication unsuccesful [SI2PR6CA0e12.apcprd6.prod.outlook.com 224-11-1T96:16:51.8952 809172787151CE]
Подробнее здесь: https://stackoverflow.com/questions/791 ... -authentic
Могу ли я спросить, как использовать почтовый сервер Outlook для отправки электронных писем? При просмотре документов тр ⇐ JAVA
Программисты JAVA общаются здесь
1731468769
Anonymous
Причина в том, что Microsoft ранее внесла изменения в аутентификацию электронной почты, что привело к невозможности отправки. При поиске ответов в Интернете необходимо применить регистрацию в Azure и добавить разрешения в соответствии с процессом ответа. После этих операций аутентификация не удалась при использовании аутентификации OAuth2. Шаги кода, используемые для сравнения ответов, полностью совпадают, но неясно, настроен ли вопрос в Azure или где-то еще.
Вот код:
package com.tianrun.common.email;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class OAuth2Helper {
public static void main(String[] args) throws Exception {
String accessToken = getAccessToken();
sendEmail(accessToken, "****@outlook.com", "******", "Subject", "Body of the email");
}
private static String getAccessToken() throws Exception {
String clientId = "****";
String clientSecret = "****";
String tenantId = "*****";
String scope = "https://outlook.office365.com/.default";
String authUrl = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
URL url = new URL(authUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
String postParams = "client_id=" + clientId +
"&scope=" + scope +
"&client_secret=" + clientSecret +
"&grant_type=client_credentials";
conn.getOutputStream().write(postParams.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
conn.disconnect();
// Parse the JSON response to get the access token
String accessToken = content.toString().split("\"access_token\":\"")[1].split("\"")[0];
System.out.println(accessToken);
return accessToken;
}
private static void sendEmail(String accessToken, String sender, String recipient, String subject, String body)
throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.host", "smtp.office365.com");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
props.put("mail.smtp.starttls.enable", "true");
// Create a custom Authenticator with the OAuth2 access token
Session session = Session.getInstance(props, null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
}
}
[b]Это журнал ошибок[/b]
javax.mail.AuthenticationfailedException: 535 5.7.3 Authentication unsuccesful [SI2PR6CA0e12.apcprd6.prod.outlook.com 224-11-1T96:16:51.8952 809172787151CE]
Подробнее здесь: [url]https://stackoverflow.com/questions/79183073/may-i-ask-how-to-use-the-outlook-email-server-to-send-emails-identity-authentic[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия