
1. Java通过Microsoft Graph调用Outlook实战进阶在上一篇文章中我们已经介绍了如何搭建Java与Microsoft Graph的基础连接环境。这次我们将深入探讨两个核心功能读取收件箱邮件列表和发送新邮件。作为企业级应用开发中的常见需求邮件交互功能在OA系统、自动通知服务等场景中具有广泛应用价值。提示本文假设您已经完成Azure应用注册并获取了必要的API权限Mail.Read, Mail.Send等。若尚未完成请参考本系列第一篇文章进行配置。1.1 环境准备与SDK配置首先确保项目中已引入最新版Microsoft Graph SDK。对于Maven项目pom.xml需包含以下依赖dependency groupIdcom.microsoft.graph/groupId artifactIdmicrosoft-graph/artifactId version5.73.0/version /dependency dependency groupIdcom.microsoft.graph/groupId artifactIdmicrosoft-graph-auth/artifactId version1.19.0/version /dependency建议同步配置Lombok以简化实体类代码dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId version1.18.30/version scopeprovided/scope /dependency2. 收件箱邮件列表获取实现2.1 核心API调用方法以下是获取用户收件箱前25封邮件的完整实现public static MessageCollectionResponse getInbox() throws Exception { if (_userClient null) { throw new Exception(Graph客户端未初始化); } return _userClient.me() .mailFolders() .byMailFolderId(inbox) .messages() .get(requestConfig - { // 选择需要返回的字段 requestConfig.queryParameters.select new String[] { from, isRead, receivedDateTime, subject }; // 设置返回结果数量上限 requestConfig.queryParameters.top 25; // 按接收时间降序排列 requestConfig.queryParameters.orderby new String[] { receivedDateTime DESC }; }); }2.2 结果解析与展示获取到MessageCollectionResponse后需要处理分页和时区转换private static void listInbox() { try { final MessageCollectionResponse messages Graph.getInbox(); DateTimeFormatter formatter DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT) .withLocale(Locale.getDefault()); messages.getValue().forEach(message - { System.out.println(主题: message.getSubject()); System.out.println( 发件人: message.getFrom() .getEmailAddress().getName()); System.out.println( 状态: (message.getIsRead() ? 已读 : 未读)); System.out.println( 接收时间: message.getReceivedDateTime() .atZoneSameInstant(ZoneId.systemDefault()) .format(formatter)); }); System.out.println(\n是否有更多邮件: (messages.getOdataNextLink() ! null)); } catch (Exception e) { System.out.println(获取收件箱失败: e.getMessage()); } }2.3 关键技术点解析邮件文件夹访问byMailFolderId(inbox)用于访问默认文件夹自定义文件夹需使用文件夹ID替代inbox分页控制默认每页返回10条记录通过top参数可调整每页数量最大不超过1000odataNextLink用于获取下一页数据字段筛选使用select指定返回字段可显著减少网络传输量建议只请求业务必需的字段经验在生产环境中建议添加重试机制处理API限流HTTP 429响应并设置合理的超时时间。3. 邮件发送功能实现3.1 邮件构建与发送发送邮件需要构造完整的Message对象public static void sendMail(String subject, String body, String recipient) throws Exception { if (_userClient null) { throw new Exception(Graph客户端未初始化); } Message message new Message(); message.setSubject(subject); ItemBody itemBody new ItemBody(); itemBody.setContent(body); itemBody.setContentType(BodyType.TEXT); // 或BodyType.HTML message.setBody(itemBody); EmailAddress emailAddress new EmailAddress(); emailAddress.setAddress(recipient); Recipient toRecipient new Recipient(); toRecipient.setEmailAddress(emailAddress); message.setToRecipients(List.of(toRecipient)); // 可选添加附件 // FileAttachment attachment new FileAttachment(); // attachment.setName(report.pdf); // attachment.setContentBytes(Files.readAllBytes(Paths.get(report.pdf))); // message.setAttachments(List.of(attachment)); SendMailPostRequestBody postRequest new SendMailPostRequestBody(); postRequest.setMessage(message); _userClient.me() .sendMail() .post(postRequest); }3.2 发送功能调用示例private static void sendMail() { try { User user Graph.getUser(); String email user.getMail() ! null ? user.getMail() : user.getUserPrincipalName(); Graph.sendMail( 系统测试邮件, 这是一封来自Java应用的测试邮件, email); System.out.println(邮件发送成功); } catch (Exception e) { System.out.println(邮件发送失败: e.getMessage()); } }3.3 高级功能实现HTML格式邮件itemBody.setContentType(BodyType.HTML); itemBody.setContent(h1标题/h1pHTML内容/p);抄送/密送message.setCcRecipients(List.of(ccRecipient)); message.setBccRecipients(List.of(bccRecipient));邮件重要性设置message.setImportance(Importance.HIGH);4. 常见问题与调试技巧4.1 权限问题排查问题现象可能原因解决方案403 Forbidden未授予Mail.Read权限检查Azure门户中的API权限配置401 Unauthorized访问令牌过期实现令牌自动刷新机制400 Bad Request请求参数错误检查邮件地址格式等输入参数4.2 性能优化建议批量操作使用$batch端点合并多个请求一次批处理最多包含20个操作增量查询requestConfig.queryParameters.deltaToken latestDeltaToken;选择性扩展requestConfig.queryParameters.expand new String[]{attachments};4.3 日志记录策略建议在初始化客户端时添加日志拦截器GraphServiceClientUser graphClient GraphServiceClient.builder() .authenticationProvider(authProvider) .logger(new DefaultLogger() { Override public void logDebug(String message) { logger.debug(message); } }) .buildClient();5. 生产环境注意事项证书管理定期检查服务器证书有效期实现自动化的证书更新机制错误处理增强try { // Graph API调用 } catch (GraphServiceException ex) { if (ex.getResponseCode() 429) { // 处理限流 long retryAfter Long.parseLong( ex.getResponseHeaders().get(Retry-After).get(0)); Thread.sleep(retryAfter * 1000); // 重试逻辑 } }邮件内容安全对用户输入的邮件内容进行HTML净化附件文件类型检查敏感信息加密在实际项目中我们还需要考虑与Spring Boot等框架的集成方案。例如可以将Graph客户端配置为BeanBean public GraphServiceClientUser graphClient() { TokenCredentialAuthProvider authProvider new TokenCredentialAuthProvider(scopes, credential); return GraphServiceClient.builder() .authenticationProvider(authProvider) .buildClient(); }对于企业级应用建议实现邮件发送队列和重试机制确保在高负载或网络不稳定的情况下仍能可靠地处理邮件发送任务。同时要注意遵守Microsoft Graph的速率限制默认每10分钟10,000个请求。