提问人:k0nditor 提问时间:10/7/2023 最后编辑:k0nditor 更新时间:10/9/2023 访问量:101
Java javax.mail、msal4j Oauth2 使用 Office 365 发送电子邮件
Java javax.mail, msal4j Oauth2 send email using Office 365
问:
我想发送电子邮件。我使用 Java 1.8、com.microsoft.aad.msal4j 和 javax.mail。 但是,我收到以下错误。无论我指定什么:
5.7.3 Authentication unsuccessful [........PROD.OUTLOOK.COM 2023-10-07T15:04:28.150Z ....]
Exception in thread "main" javax.mail.AuthenticationFailedException: 535 5.7.3 Authentication unsuccessful [........PROD.OUTLOOK.COM 2023-10-07T15:04:28.150Z ...]
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:947)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:858)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:762)
at javax.mail.Service.connect(Service.java:366)
不幸的是,您几乎找不到文档,并且此处的测试实现 4 也不好。
我使用:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>msal4j</artifactId>
<version>1.13.10</version>
</dependency>
虽然仅适用于 .default 或 https://outlook.office365.com/.default 作为范围,但对我有用。
这是我的实现(简短版本):
public static void main(String[] args) throws ExecutionException, InterruptedException, MessagingException, MalformedURLException {
Properties props = new Properties();
props.put("mail.smtp.port", "587");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.smtp.auth.mechanisms", "XOAUTH2");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.debug.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.auth.xoauth2.disable", "false");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth.login.disable", "true");
props.put("mail.smtp.auth.plain.disable", "true");
Session session = Session.getInstance(props);
Transport transport = session.getTransport("smtp");
IAuthenticationResult t = tokenFor("https://outlook.office365.com/.default").get();
String token = t.accessToken();
transport.connect("smtp.office365.com", 587, "[email protected]", token);
transport.send(new MimeMessage(session));
}
private static CompletableFuture<IAuthenticationResult> tokenFor(String... scopes) throws MalformedURLException {
String tenantId = "...";
String clientId = "...";
String url = "https://login.microsoftonline.com/%s/oauth2/v2.0/token";
String authority = String.format(url, tenantId);
String clientSecret = "...";
IClientCredential secret = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication.Builder app = ConfidentialClientApplication.builder(clientId, secret)
.authority(authority);
ClientCredentialParameters.ClientCredentialParametersBuilder clientCredentialParam =
ClientCredentialParameters.builder
(new HashSet<>(Arrays.asList(scopes)));
return app.build().acquireToken(clientCredentialParam.build());
}
有人可以试试这个吗?
答: 暂无答案
评论