Build Java apps with Microsoft Graph
This tutorial teaches you how to build a Java console app that uses the Microsoft Graph API to access data on behalf of a user.
Note
To learn how to use Microsoft Graph to access data using app-only authentication, see this app-only authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download the completed code through the quick start tool, which automates app registration and configuration. The downloaded code works without any modifications required.
You can also download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have the Java SE Development Kit (JDK) and Gradle installed on your development machine.
You should also have a Microsoft work or school account with an Exchange Online mailbox. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a 1-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with OpenJDK version 17.0.2 and Gradle 7.4.2. The steps in this guide may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Azure Active Directory to enable user authentication. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Register application for user authentication
In this section you will register an application that supports user authentication using device code flow.
Open a browser and navigate to the Microsoft Entra admin center and login using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph User Auth Tutorial
.Set Supported account types as desired. The options are:
Option Who can sign in? Accounts in this organizational directory only Only users in your Microsoft 365 organization Accounts in any organizational directory Users in any Microsoft 365 organization (work or school accounts) Accounts in any organizational directory ... and personal Microsoft accounts Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and save it, you will need it in the next step. If you chose Accounts in this organizational directory only for Supported account types, also copy the Directory (tenant) ID and save it.
Select Authentication under Manage. Locate the Advanced settings section and change the Allow public client flows toggle to Yes, then choose Save.
Note
Notice that you did not configure any Microsoft Graph permissions on the app registration. This is because the sample uses dynamic consent to request specific permissions for user authentication.
Create a Java console app
In this section you'll create a basic Java console app.
Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command to create a new Gradle project.
gradle init --dsl groovy --test-framework junit --type java-application --project-name graphtutorial --package graphtutorial
Once the project is created, verify that it works by running the following command to run the app in your CLI.
./gradlew --console plain run
If it works, the app should output
Hello World.
.
Install dependencies
Before moving on, add some additional dependencies that you will use later.
- Azure Identity client library for Java to authenticate the user and acquire access tokens.
- Microsoft Graph SDK for Java to make calls to the Microsoft Graph.
Open ./app/build.gradle. Update the
dependencies
section to add those dependencies.dependencies { // Use JUnit test framework. testImplementation 'junit:junit:4.13.2' // This dependency is used by the application. implementation 'com.google.guava:guava:33.2.1-jre' implementation 'com.azure:azure-identity:1.13.0' implementation 'com.microsoft.graph:microsoft-graph:6.13.0' }
Add the following to the end of ./app/build.gradle.
run { standardInput = System.in }
The next time you build the project, Gradle will download those dependencies.
Load application settings
In this section you'll add the details of your app registration to the project.
Create a new directory named graphtutorial in the ./app/src/main/resources directory.
Create a new file in the ./app/src/main/resources/graphtutorial directory named oAuth.properties, and add the following text in that file.
app.clientId=YOUR_CLIENT_ID_HERE app.tenantId=common app.graphUserScopes=user.read,mail.read,mail.send
Update the values according to the following table.
Setting Value app.clientId
The client ID of your app registration app.tenantId
If you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as common
.Important
If you're using source control such as git, now would be a good time to exclude the oAuth.properties file from source control to avoid inadvertently leaking your app ID.
Design the app
In this section you will create a simple console-based menu.
Open ./app/src/main/java/graphtutorial/App.java and add the following
import
statements.package graphtutorial; import java.io.IOException; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.InputMismatchException; import java.util.Properties; import java.util.Scanner; import com.microsoft.graph.models.Message; import com.microsoft.graph.models.MessageCollectionResponse; import com.microsoft.graph.models.User;
Replace the existing
main
function with the following.public static void main(String[] args) { System.out.println("Java Graph Tutorial"); System.out.println(); final Properties oAuthProperties = new Properties(); try { oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties")); } catch (IOException e) { System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details."); return; } initializeGraph(oAuthProperties); greetUser(); Scanner input = new Scanner(System.in); int choice = -1; while (choice != 0) { System.out.println("Please choose one of the following options:"); System.out.println("0. Exit"); System.out.println("1. Display access token"); System.out.println("2. List my inbox"); System.out.println("3. Send mail"); System.out.println("4. Make a Graph call"); try { choice = input.nextInt(); } catch (InputMismatchException ex) { // Skip over non-integer input } input.nextLine(); // Process user choice switch(choice) { case 0: // Exit the program System.out.println("Goodbye..."); break; case 1: // Display access token displayAccessToken(); break; case 2: // List emails from user's inbox listInbox(); break; case 3: // Send an email message sendMail(); break; case 4: // Run any Graph code makeGraphCall(); break; default: System.out.println("Invalid choice"); } } input.close(); }
Add the following placeholder methods at the end of the file. You'll implement them in later steps.
private static void initializeGraph(Properties properties) { // TODO } private static void greetUser() { // TODO } private static void displayAccessToken() { // TODO } private static void listInbox() { // TODO } private static void sendMail() { // TODO } private static void makeGraphCall() { // TODO }
This implements a basic menu and reads the user's choice from the command line.
- Delete ./app/src/test/java/graphtutorial/AppTest.java.
Add user authentication
In this section you will extend the application from the previous exercise to support authentication with Azure AD. This is required to obtain the necessary OAuth access token to call the Microsoft Graph. In this step you will integrate the Azure Identity client library for Java into the application and configure authentication for the Microsoft Graph SDK for Java.
The Azure Identity library provides a number of TokenCredential
classes that implement OAuth2 token flows. The Microsoft Graph client library uses those classes to authenticate calls to Microsoft Graph.
Configure Graph client for user authentication
In this section you will use the DeviceCodeCredential
class to request an access token by using the device code flow.
Create a new file in the ./app/src/main/java/graphtutorial directory named Graph.java and add the following code to that file.
package graphtutorial; import java.util.List; import java.util.Properties; import java.util.function.Consumer; import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenRequestContext; import com.azure.identity.DeviceCodeCredential; import com.azure.identity.DeviceCodeCredentialBuilder; import com.azure.identity.DeviceCodeInfo; import com.microsoft.graph.models.BodyType; import com.microsoft.graph.models.EmailAddress; import com.microsoft.graph.models.ItemBody; import com.microsoft.graph.models.Message; import com.microsoft.graph.models.MessageCollectionResponse; import com.microsoft.graph.models.Recipient; import com.microsoft.graph.models.User; import com.microsoft.graph.serviceclient.GraphServiceClient; import com.microsoft.graph.users.item.sendmail.SendMailPostRequestBody;
Add an empty Graph class definition.
public class Graph { }
Add the following code to the Graph class.
private static Properties _properties; private static DeviceCodeCredential _deviceCodeCredential; private static GraphServiceClient _userClient; public static void initializeGraphForUserAuth(Properties properties, Consumer<DeviceCodeInfo> challenge) throws Exception { // Ensure properties isn't null if (properties == null) { throw new Exception("Properties cannot be null"); } _properties = properties; final String clientId = properties.getProperty("app.clientId"); final String tenantId = properties.getProperty("app.tenantId"); final String[] graphUserScopes = properties.getProperty("app.graphUserScopes").split(","); _deviceCodeCredential = new DeviceCodeCredentialBuilder() .clientId(clientId) .tenantId(tenantId) .challengeConsumer(challenge) .build(); _userClient = new GraphServiceClient(_deviceCodeCredential, graphUserScopes); }
Replace the empty
initializeGraph
function in App.java with the following.private static void initializeGraph(Properties properties) { try { Graph.initializeGraphForUserAuth(properties, challenge -> System.out.println(challenge.getMessage())); } catch (Exception e) { System.out.println("Error initializing Graph for user auth"); System.out.println(e.getMessage()); } }
This code declares two private properties, a DeviceCodeCredential
object and a GraphServiceClient
object. The InitializeGraphForUserAuth
function creates a new instance of DeviceCodeCredential
, then uses that instance to create a new instance of GraphServiceClient
. Every time an API call is made to Microsoft Graph through the _userClient
, it will use the provided credential to get an access token.
Test the DeviceCodeCredential
Next, add code to get an access token from the DeviceCodeCredential
.
Add the following function to the
Graph
class.public static String getUserToken() throws Exception { // Ensure credential isn't null if (_deviceCodeCredential == null) { throw new Exception("Graph has not been initialized for user auth"); } final String[] graphUserScopes = _properties.getProperty("app.graphUserScopes").split(","); final TokenRequestContext context = new TokenRequestContext(); context.addScopes(graphUserScopes); final AccessToken token = _deviceCodeCredential.getTokenSync(context); return token.getToken(); }
Replace the empty
displayAccessToken
function in App.java with the following.private static void displayAccessToken() { try { final String accessToken = Graph.getUserToken(); System.out.println("Access token: " + accessToken); } catch (Exception e) { System.out.println("Error getting access token"); System.out.println(e.getMessage()); } }
Build and run the app. Enter
1
when prompted for an option. The application displays a URL and device code.Java Graph Tutorial 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 1 To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RB2RUD56D to authenticate.
Open a browser and browse to the URL displayed. Enter the provided code and sign in.
Important
Be mindful of any existing Microsoft 365 accounts that are logged into your browser when browsing to
https://microsoft.com/devicelogin
. Use browser features such as profiles, guest mode, or private mode to ensure that you authenticate as the account you intend to use for testing.Once completed, return to the application to see the access token.
Tip
For validation and debugging purposes only, you can decode user access tokens (for work or school accounts only) using Microsoft's online token parser at https://jwt.ms. This can be useful if you encounter token errors when calling Microsoft Graph. For example, verifying that the
scp
claim in the token contains the expected Microsoft Graph permission scopes.
Get user
In this section you will incorporate the Microsoft Graph into the application. For this application, you will use the Microsoft Graph Java Client Library to make calls to Microsoft Graph.
Open Graph.java and add the following function to the Graph class.
public static User getUser() throws Exception { // Ensure client isn't null if (_userClient == null) { throw new Exception("Graph has not been initialized for user auth"); } return _userClient.me().get(requestConfig -> { requestConfig.queryParameters.select = new String[] {"displayName", "mail", "userPrincipalName"}; }); }
Replace the empty
greetUser
function in App.java with the following.private static void greetUser() { try { final User user = Graph.getUser(); // For Work/school accounts, email is in mail property // Personal accounts, email is in userPrincipalName final String email = user.getMail() == null ? user.getUserPrincipalName() : user.getMail(); System.out.println("Hello, " + user.getDisplayName() + "!"); System.out.println("Email: " + email); } catch (Exception e) { System.out.println("Error getting user"); System.out.println(e.getMessage()); } }
If you run the app now, after you log in the app welcomes you by name.
Hello, Megan Bowen!
Email: [email protected]
Code explained
Consider the code in the greetUser
function. It's only a few lines, but there are some key details to notice.
Accessing 'me'
The function uses the _userClient.me
request builder, which builds a request to the Get user API. This API is accessible two ways:
GET /me
GET /users/{user-id}
In this case, the code will call the GET /me
API endpoint. This is a shortcut method to get the authenticated user without knowing their user ID.
Note
Because the GET /me
API endpoint gets the authenticated user, it is only available to apps that use user authentication. App-only authentication apps cannot access this endpoint.
Requesting specific properties
The function uses the select
property on the request configuration to specify the set of properties it needs. This adds the $select query parameter to the API call.
Strongly-typed return type
The function returns a com.microsoft.graph.models.User
object deserialized from the JSON response from the API. Because the code uses select
, only the requested properties will have values in the returned User
object. All other properties will have default values.
List inbox
In this section you will add the ability to list messages in the user's email inbox.
Open Graph.java and add the following function to the Graph class.
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" }; }); }
Replace the empty
listInbox
function in App.java with the following.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()); } }
Run the app, sign in, and choose option 2 to list your inbox.
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
Code explained
Consider the code in the getInbox
function.
Accessing well-known mail folders
The function uses the _userClient.me().mailFolders().byMailFolderId("inbox").messages()
request builder, which builds a request to the List messages API. Because it includes the byMailFolderId("inbox")
request builder, the API will only return messages in the requested mail folder. In this case, because the inbox is a default, well-known folder inside a user's mailbox, it's accessible via its well-known name. Non-default folders are accessed the same way, by replacing the well-known name with the mail folder's ID property. For details on the available well-known folder names, see mailFolder resource type.
Accessing a collection
Unlike the getUser
function from the previous section, which returns a single object, this method returns a collection of messages. Most APIs in Microsoft Graph that return a collection do not return all available results in a single response. Instead, they use paging to return a portion of the results while providing a method for clients to request the next "page".
Default page sizes
APIs that use paging implement a default page size. For messages, the default value is 10. Clients can request more (or less) by using the $top query parameter. In getInbox
, this is accomplished with the top
property in the request configuration.
Note
The value set in top
is an upper-bound, not an explicit number. The API returns a number of messages up to the specified value.
Getting subsequent pages
If there are more results available on the server, collection responses include an @odata.nextLink
property with an API URL to access the next page. The Java client library exposes this as the getOdataNextLink
method on collection response objects. If this method returns non-null, there are more results available.
Sorting collections
The function uses the orderBy
property on the request configuration to request results sorted by the time the message is received (receivedDateTime
property). It includes the DESC
keyword so that messages received more recently are listed first. This adds the $orderby query parameter to the API call.
Send mail
In this section you will add the ability to send an email message as the authenticated user.
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); }
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()); } }
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.
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
.
Optional: add your own code
In this section you will add your own Microsoft Graph capabilities to the application. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Update the app
Open Graph.java and add the following function to the Graph class.
public static void makeGraphCall() { // INSERT YOUR CODE HERE }
Replace the empty
MakeGraphCallAsync
function in App.java with the following.private static void makeGraphCall() { try { Graph.makeGraphCall(); } catch (Exception e) { System.out.println("Error making Graph call"); System.out.println(e.getMessage()); } }
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the Create event API. You can use one of the examples in the API documentation, or you can customize an API request in Graph Explorer and use the generated snippet.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, or personal Microsoft accounts, for example.
- To call an API with user authentication (if the API supports user (delegated) authentication), add the required permission scope in oAuth.properties.
- To call an API with app-only authentication see the app-only authentication tutorial.
Add your code
Copy your code into the makeGraphCallAsync
function in Graph.java. If you're copying a snippet from documentation or Graph Explorer, be sure to rename the GraphServiceClient
to _userClient
.
Congratulations!
You've completed the Java Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features.
- Learn how to use app-only authentication with the Microsoft Graph Java SDK.
- Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
Java samples
Have an issue with this section? If so, please give us some feedback so we can improve this section.