Codementor Events

Using Java to integrate with Microsoft Exchange Server

Published Apr 13, 2020Last updated Oct 28, 2022
Using Java to integrate with Microsoft Exchange Server

Do you need to have your Java code reading or sending emails from Microsoft Exchange Server? Or are you interested in the calendars, and you would like your code to get information from there or to sync different calendars?

The traditional way of integrating with all kinds of software is to use its API. So, if you are trying to do an integration with Microsoft Exchange, you are probably trying to find how to use Exchange's API and wondering how to work with the Microsoft Exchange Calendar API in Java.

APIs change a lot – a bit of history on the Microsoft Exchange API

The most common way to integrate with Exchange from Java used to be the Exchange Web Services (EWS). EWS SDK launched as a part of Microsoft Exchange 2007. It is a SOAP-based API. The problem is that, back in July 2018, Microsoft announced it would no longer do any feature updates to it.

But there is another deadline looming on the horizon.

Exactly 6 months from today, on Oct. 13, 2020, Microsoft expects that all administrators with third-party tools that rely on Exchange Web Services for Office 365 integration will have switched to Microsoft Graph. On that same date, support for Basic Authentication in Exchange Web Services (EWS) will fully stop.

Microsoft wants you to move everything over to OAuth. The truth is that OAuth is a much better option, and it is approved as an International Standard (ISO/IEC). If you have not heard of OAuth (what rock were you under?), you can check here and then go deeper here. Keep in mind that although it is a move for the better, the thing is that it is a drastic change happening within 6 months! When support for Basic Authentication ends, your apps will no longer be able to use Basic Authentication to connect to Exchange using EWS. If that is you, you need to start moving, and you need to do it now! The clock is ticking...

So, what do I need to do?

If you want to connect from Java code to Microsoft Exchange via API and you want to adopt Microsoft's recommendations, you should use Microsoft Graph.

Microsoft Graph came to life back in 2015 with Office 365. It delegated calls to different Office 365 Cloud services via one single endpoint https://graph.microsoft.com/. Over time, it evolved, and it now includes access to other Microsoft products such as Exchange.

Within Microsoft Graph, you have two alternatives: Microsoft Graph API or Microsoft Graph data connect. Either way, do check the Terms of Use first. Microsoft is quite precise about what you can and cannot do with their API, so it is definitely best to have a look.

In most cases, Microsoft Graph API is the best fit. We'll go back to it in a bit.

Microsoft Graph data connect is the option to consider if you want to work with big data or if you need granular consent. By granular consent, I mean that the customer gets to review the specific fields and any exclusions - that is not possible with the regular API. However, there is a rule that you need to be aware of if you are considering Microsoft Graph data connect: it only sends data from the customer's Office 365 tenant to the associated Azure tenant.

If none of these two needs resonate with you, you want the regular API, which is the most common option. Two versions of Microsoft Graph REST APIs currently exist – v1.0 and the beta version. You can check the beta version, but, of course, for any serious development, you should keep to the production version 1.0. For that version, you will need to read the documentation and learn the Java SDK. Yes, I know it is not good news, but if you are just starting with this API, there is much studying involved!…

To then use the API, you need to start by registering your app. Yes, I know this is not the most exciting first step ever, but if you are using the API directly, you'll have to go through it. You need an Application ID to represent your application in API calls. To get it, you'll need a work/school account or a Microsoft account, and then you can decide whether you want to register using:

• the Microsoft Application Registration Portal

• the Azure Active Directory management portal

The later is intended for enterprise-class applications.

If your application is a confidential client (a service), you need to create a new app password to secure it. After you've registered, an application ID is going to be created for your app and displayed on your new app's properties page.

Lastly, please note that Microsoft Graph keeps changing all the time. Have a look at the changelog, to get an idea of changes over time (since Dec 2015). If you want to work with it, I do recommend you always check what the current production version of the API is.

Is there another way around it?

If you are not much into:

• Working with Microsoft in the first place

• Spending tons of time to study the documentation

• Having to keep up with the future changes to the Microsoft Graph API and spend time fixing the problems you get as a consequence

You might be wondering if there is an alternative. Yes, there is a better way forward!

Replace using the API directly, with using Connect Bridge. Connect Bridge is a thin layer you can put between you and the API. It is thin enough to have everything efficient and fast, but thick enough to ensure you never have to touch Microsoft Exchange or the Microsoft Graph API.

Connect Bridge is a paid tool, but a free trial is available so you can see if it works for you. The beauty of this tool is that it ensures forward and backward compatibility.

You build your Java code integrating with Connect Bridge, and then your users can upgrade Exchange, Microsoft can launch new versions of the API… and you won't have to worry about it. It does not matter what will come after Microsoft Graph API v1.0. Your solution will still work! You write your code once, and then all the complexity is something you simply don't ever have to worry about.

There is no limitation on the environment where you can use this tool. You can run it on

• An Azure-built SaaS platform managed by Connecting software

• On-premises or self-hosted (on your own cloud servers or virtual machines)

What is Connect Bridge doing behind the scenes? How does it work? It basically translates standard SQL statements into API calls. On your code, it looks like you are getting data to and from a relational database using JDBC (ODBC and Web services are also supported). You write your regular SELECT, INSERT, UPDATE and DELETE statements. You use what looks like stored procedures. But it is all just a layer of abstraction.

You are not accessing Microsoft Exchange's database (and trust me, you don't want to do that!).

Connect Bridge comes with a user-friendly Query tool where you can test your (fake) queries, see the (fake) columns of the (fake) tables or even find a convenient (fake) stored procedure. As I said, it feels exactly as if it were using a SQL database, but it is just an abstraction.

Once you have finished all the testing you want, you move on to code! Just put in the connection and the queries in your code as if you were using JDBC to connect to a database… and that's all!

A little example of Java code accessing Microsoft Exchange

Let's see a sample of the Java code you could use for a simple integration of Java and SharePoint

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Program {
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("com.cnsconnect.mgw.jdbc.MgDriver");
        // STEP 1: Create a JDBC connection to each target server 
        // you get the data for the connection string from Connect Bridge
        String exchangeConnectionString = "jdbc:MgDriver:IMPL=CORBA;ENC=UTF8;HOST=123.456.789.000;PORT=8087;UID=demouser;PWD='password';ACC=accountExchange;";
        String sharepointConnectionString =        "jdbc:MgDriver:IMPL=CORBA;ENC=UTF8;HOST=123.456.789.000;PORT=8087;UID=demouser;PWD='password';ACC=accountSharePoint;";
        Connection exchangeConn =
        DriverManager.getConnection(exchangeConnectionString);
        Connection sharepointConn =
        DriverManager.getConnection(sharepointConnectionString);
        Statement exchangeSt = exchangeConn.createStatement();
        System.out.println("Connecting to Exchange...");
        //STEP 2: Provide an appropriate object like a ResultSet in JAVA
        //STEP 3: Fill the object with data from the source server
        ResultSet exchangeRs = exchangeSt.executeQuery("SELECT * FROM [Appointment]");
        //create a new JDBC statement for inserting PreparedStatement
        sharepointSt = sharepointConn.prepareStatement("INSERT INTO [Calendar] ([Title], [Description], [Location], [StartTime], [EndTime]) VALUES ( ?, ?, ?, ?, ?)");
        //STEP 4: Manipulate the data and or apply a workflow rule
        //in this case, check if the appointment is private, if not, insert it into sharepoint
        while (exchangeRs.next()) {
            Boolean isPrivate = exchangeRs.getBoolean("IsPrivate");
            if (isPrivate != null && isPrivate)
            {
            System.out.println("Skipping '" + exchangeRs.getString("Subject") + "'");
            continue;
            }
            // Title
            //fill its parameters with values for the sharepoint account 
            sharepointSt.setString(1, exchangeRs.getString("Subject"));
            sharepointSt.setString(2, exchangeRs.getString("Body")); 
            sharepointSt.setString(3, exchangeRs.getString("Location"));
            sharepointSt.setTimestamp(4, exchangeRs.getTimestamp("StartDate")); 
            sharepointSt.setTimestamp(5, exchangeRs.getTimestamp("EndDate"));
            
            System.out.println("Inserting '" + exchangeRs.getString("Subject") + "'");
            //STEP 5: INSERT the data into the target server
            sharepointSt.execute();
        }
        exchangeRs.close();
        exchangeSt.close();
        sharepointSt.close();
        //STEP 6: Close Connections 
        exchangeConn.close();
        sharepointConn.close();
    }
}

Yeap, it is that simple!

The best thing is that once you finished your code and you have a working solution, you know it requires zero maintenance. That's right! All the maintenance effort is on the side of Connect Bridge. That is why it is a paid tool. Try it out, and you'll see it is worth every penny!

It is also good to note that Connect Bridge also handles authentication and security, which can take up a significant amount of time if you are developing from scratch.

Takeaway

I have shown you how accessing Microsoft Exchange data in Java can be easily done using the Connect Bridge integration platform.

And the good news are that this is also possible with Microsoft Dynamics and Microsoft SharePoint! In fact, I have written another article on the integration of SharePoint from Java code. Plus, you can connect to other Microsoft software, Salesforce, GMail and many others. You just need to get Connect Bridge, as the base integration platform, and choose the right connector.

In case you want to know what connectors are currently available for Connect Bridge, either go to https://www.connecting-software.com/connectors/ or ask me about it in the comments, and I will check it out (new connectors are launched regularly).

It is also important to note that some ready-made, out-of-the-box products use Connect Bridge. An important example is CB Exchange Server Sync, which allows you to choose custom one-way or two-way synchronization of appointments, emails, folders, tasks, and contacts with no coding at all.

So, now you know: there is a better way and it is called Connect Bridge. Why don't you give it a try?

Let me know if you enjoyed this article in the comments below!

Discover and read more posts from Ana Neto
get started
post commentsBe the first to share your opinion
Tomáš Johan Prítrský
3 years ago

the title says “Microsoft Exchange Server” and somehow you are talking about the Microsoft cloud service, the “Microsoft Exchange Online”…

Ana Neto
3 years ago

If you are interested in integrating an on-premises Microsoft Exchange Server, you could the option of using Connect Bridge as discussed or try a web services approach https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/start-using-web-services-in-exchange

iFitnessvn
4 years ago

Thanks much for your great article.

Show more replies