通过


使用 Microsoft Graph 向 Java 应用添加电子邮件功能

s

本文将扩展使用 Microsoft Graph 邮件 API 使用 Microsoft Graph 生成 Java 应用 时创建的应用程序。 使用 Microsoft Graph 列出用户的收件箱并发送电子邮件。

列出用户的收件箱

首先,在用户的电子邮件收件箱中列出邮件。

  1. 打开 Graph.java 并将以下函数添加到 Graph 类。

    public static MessageCollectionResponse getInbox() throws Exception {
        // Ensure client isn't null
        if (_userClient == null) {
            throw new Exception("Graph has not been initialized for user auth");
        }
    
        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. App.java 中的空listInbox函数替换为以下内容。

    private static void listInbox() {
        try {
            final MessageCollectionResponse messages = Graph.getInbox();
    
            // Output each message's details
            for (Message message: messages.getValue()) {
                System.out.println("Message: " + message.getSubject());
                System.out.println("  From: " + message.getFrom().getEmailAddress().getName());
                System.out.println("  Status: " + (message.getIsRead() ? "Read" : "Unread"));
                System.out.println("  Received: " + message.getReceivedDateTime()
                    // Values are returned in UTC, convert to local time zone
                    .atZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime()
                    .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)));
            }
    
            final Boolean moreMessagesAvailable = messages.getOdataNextLink() != null;
            System.out.println("\nMore messages available? " + moreMessagesAvailable);
        } catch (Exception e) {
            System.out.println("Error getting inbox");
            System.out.println(e.getMessage());
        }
    }
    
  3. 运行应用,登录,然后选择选项 2 列出收件箱。

    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List my inbox
    3. Send mail
    4. Make a Graph call
    2
    Message: Updates from Ask HR and other communities
      From: Contoso Demo on Yammer
      Status: Read
      Received: 12/30/2021, 4:54:54 AM
    Message: Employee Initiative Thoughts
      From: Patti Fernandez
      Status: Read
      Received: 12/28/2021, 5:01:10 PM
    Message: Voice Mail (11 seconds)
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021, 5:00:46 PM
    Message: Our Spring Blog Update
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021, 4:49:46 PM
    Message: Atlanta Flight Reservation
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021, 4:35:42 PM
    Message: Atlanta Trip Itinerary - down time
      From: Alex Wilber
      Status: Unread
      Received: 12/28/2021, 4:22:04 PM
    
    ...
    
    More messages available? true
    

getInbox 说明

请考虑 函数中的 getInbox 代码。

访问已知邮件文件夹

函数使用 _userClient.me().mailFolders().byMailFolderId("inbox").messages() 请求生成器,该生成器生成对 列表消息 API 的请求。 由于它包含 byMailFolderId("inbox") 请求生成器,API 仅返回所请求邮件文件夹中的邮件。 在这种情况下,由于收件箱是用户邮箱中默认的已知文件夹,因此可通过其已知名称访问该文件夹。 非默认文件夹的访问方式相同,方法是将已知名称替换为邮件文件夹的 ID 属性。 有关可用已知文件夹名称的详细信息,请参阅 mailFolder 资源类型

访问集合

与上一 getUser 部分中返回单个 对象的函数不同,此方法返回消息集合。 Microsoft Graph 中返回集合的大多数 API 不会在单个响应中返回所有可用结果。 相反,它们使用 分页 返回部分结果,同时为客户端提供请求下一页的方法。

默认页面大小

使用分页的 API 实现默认页面大小。 对于消息,默认值为 10。 客户端可以使用 $top 查询参数请求更多 (或更少的 ) 。 在 getInbox中,使用请求配置中的 属性完成top添加$top

注意

top 设置的值是上限,而不是显式数字。 API 返回一些 消息,最多返回 指定值。

获取后续页面

如果服务器上有更多可用的结果,则集合响应将包含一个 @odata.nextLink 具有 API URL 的属性,用于访问下一页。 Java 客户端库针对集合响应对象提供 getOdataNextLink 方法。 如果此方法返回非 null,则有更多可用的结果。

集合排序

函数使用 orderBy 请求配置上的 属性来请求按消息接收时间排序的结果, (receivedDateTime 属性) 。 它包含DESC关键字 (keyword) 以便先列出最近收到的消息。 此属性将 $orderby 查询参数 添加到 API 调用。

发送邮件

现在,添加以经过身份验证的用户身份发送电子邮件的功能。

  1. 打开 Graph.java 并将以下函数添加到 Graph 类。

    public static void sendMail(String subject, String body, String recipient) throws Exception {
        // Ensure client isn't null
        if (_userClient == null) {
            throw new Exception("Graph has not been initialized for user auth");
        }
    
        // Create a new message
        final Message message = new Message();
        message.setSubject(subject);
        final ItemBody itemBody = new ItemBody();
        itemBody.setContent(body);
        itemBody.setContentType(BodyType.Text);
        message.setBody(itemBody);
    
        final EmailAddress emailAddress = new EmailAddress();
        emailAddress.setAddress(recipient);
        final Recipient toRecipient = new Recipient();
        toRecipient.setEmailAddress(emailAddress);
        message.setToRecipients(List.of(toRecipient));
    
        final SendMailPostRequestBody postRequest = new SendMailPostRequestBody();
        postRequest.setMessage(message);
    
        // Send the message
        _userClient.me()
            .sendMail()
            .post(postRequest);
    }
    
  2. App.java 中的空sendMail函数替换为以下内容。

    private static void sendMail() {
        try {
            // Send mail to the signed-in user
            // Get the user for their email address
            final User user = Graph.getUser();
            final String email = user.getMail() == null ? user.getUserPrincipalName() : user.getMail();
    
            Graph.sendMail("Testing Microsoft Graph", "Hello world!", email);
            System.out.println("\nMail sent.");
        } catch (Exception e) {
            System.out.println("Error sending mail");
            System.out.println(e.getMessage());
        }
    }
    
  3. 运行应用,登录并选择选项 3 以向自己发送电子邮件。

    Please choose one of the following options:
    0. Exit
    1. Display access token
    2. List my inbox
    3. Send mail
    4. Make a Graph call
    3
    
    Mail sent.
    

    注意

    如果使用 Microsoft 365 开发人员计划中的开发人员租户进行测试,则发送的电子邮件可能未送达,并且可能会收到无法交付的报告。 如果要取消阻止从租户发送邮件,请通过Microsoft 365 管理中心联系支持人员。

  4. 若要验证是否已收到邮件,请选择选项 2 列出收件箱。

sendMail 说明

请考虑 函数中的 sendMail 代码。

发送邮件

函数使用 _userClient.me().sendMail() 请求生成器,该生成器生成对 发送邮件 API 的请求。 请求生成器采用包含 SendMailPostRequestBody 要发送的消息的对象。

创建对象

与以前调用 Microsoft Graph(仅读取数据)不同,此调用会创建数据。 若要使用客户端库创建项,请创建表示数据 (的类的实例,在这种情况下, com.microsoft.graph.models.Message) 使用 new 关键字 (keyword) ,设置所需的属性,然后在 API 调用中发送它。 由于调用正在发送数据,因此使用 post 方法而不是 get

后续步骤