目录
问题提出
问解决题
注意
1、注册应用程序
2、引入需要依赖jar包——重点
3、微软管理员授予应用合适权限
参考链接
在2022年10月份,微软公司出于安全考虑,陆续取消了Exchange邮件发送的Basic认证。通俗来说就是不能再用用户名密码来直接进行认证了,但是系列的邮件服务不能停,所以需要切换Exchange邮件的认证和发送方式,所以首先放弃掉以前的ews-java-api相关的所有jar包,重新开始。
微软官方目前推荐以Graph的方式来发送Outlook系列邮件。
话不多说,直接贴代码,替换必要参数后,可以直接运行:
public class Test {//这些配置基本都可以从Azure云管理中心搜索Azure Active Directory配置public static void main(String[] args){IAuthenticationProvider authProvider = new ClientCredentialProvider(//应用id"clientId",//默认scopeArrays.asList("https://graph.microsoft.com/.default"),//客户端密钥"clientSecret",//租户id"tenant",NationalCloud.Global);test(authProvider);}public static void test(IAuthenticationProvider authProvider){IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();Message message = new Message();message.subject = "Meet for lunch?";ItemBody body = new ItemBody();body.contentType = BodyType.TEXT;body.content = "The new cafeteria is open.";message.body = body;LinkedList toRecipientsList = new LinkedList();Recipient toRecipients = new Recipient();EmailAddress emailAddress = new EmailAddress();emailAddress.address = "123456@outlook.com";toRecipients.emailAddress = emailAddress;toRecipientsList.add(toRecipients);message.toRecipients = toRecipientsList;LinkedList attachmentsList = new LinkedList();FileAttachment attachments = new FileAttachment();attachments.name = "attachment.txt";attachments.contentType = "text/plain";attachments.contentBytes = Base64.getDecoder().decode("SGVsbG8gV29ybGQh");attachmentsList.add(attachments);AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();attachmentCollectionResponse.value = attachmentsList;AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);message.attachments = attachmentCollectionPage;graphClient.users("456@outlook.com").sendMail(message, false).buildRequest().post();}
}
使用如上代码有几点需要注意:
首先你需要登录微软云平台,搜索Azure Active Directory配置一个应用。
具体步骤如下:

放下文档链接:配置应用程序文档。
按照笔者的经验,学会注册就可以了,不要完全按文档来,对于Java代码级发送邮件基本没帮助。
这样就可以获取到上面的一系列参数了。
com.microsoft.graph microsoft-graph-auth 0.2.0
com.microsoft.graph microsoft-graph-core 2.0.12
com.microsoft.graph microsoft-graph-core 1.0.0
这个版本配置,是笔者的心血之作,调试了好久才最终成型,这里要好好吐槽一下微软官方文档,他们依赖配置的错误百出,按照文档完全运行不了。
这里同一个jar包配置了2个版本,就是这么神奇,只有这样才能完美运行,按照官方文档完全不行。
需要在AD应用的API权限菜单配置合适的Graph权限,最要紧的是要管理员授予权限,之后就可以正常访问了。

最后,再给大家提供几个微软获取token的参考文档:
微软身份平台和 OAuth 2.0 授权代码流
Graph使用参考,支持各种语言
最后说一句,直接用我的代码及pom即可。