Edit

Share via

Build Java apps with Microsoft Graph

Send mail

In this section you will add the ability to send an email message as the authenticated user.

  1. Open Graph.java and add the following function to the Graph class.

    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. Replace the empty sendMail function in App.java with the following.

    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. Run the app, sign in, and choose option 3 to send an email to yourself.

    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.
    

    Note

    If you are testing with a developer tenant from the Microsoft 365 Developer Program, the email you send might not be delivered, and you might receive a non-delivery report. If this happens to you, please contact support via the Microsoft 365 admin center.

  4. To verify the message was received, choose option 2 to list your inbox.

Code explained

Consider the code in the sendMail function.

Sending mail

The function uses the _userClient.me().sendMail() request builder, which builds a request to the Send mail API. The request builder takes a SendMailPostRequestBody object containing the message to send.

Creating objects

Unlike the previous calls to Microsoft Graph that only read data, this call creates data. To do this with the client library you create an instance of the class representing the data (in this case, com.microsoft.graph.models.Message) using the new keyword, set the desired properties, then send it in the API call. Because the call is sending data, the post method is used instead of get.