Office 365 SDK is available on Microsoft Website as well as GitHub. Use this link to download Office 365 SDK with Demo Application

Following are the steps to integrate Office SDK in your Android Application

Prerequisites:

This will require Client ID as well as Application ID from Microsoft Azure by using which application gets connected to Active Directory and gets permission to access user’s emails. To create this following steps are necessary

  1. Create Office 365 account if you do not have one.
  2. Create Microsoft Azure Account if you do not have one.
  3. Follow following steps to generate your Client ID and Application ID.

Linking of office 365 Admin account with Microsoft Azure AD

Step 1: Login into Microsoft Azure

Step 2: Click on “New” in left top corner

Step 3: Search for ‘Active Directory’ (It will display dropdown in which active directory is listed.)

Step 4: Click on “Active directory” from dropdown. (It will display results related to active directory)

Step 5: Click on “Active directory” from results. (It will display information related to active directory)

Step 6: Scroll down on newly opened Right side window and click on “Create”

Step 7: Above step will redirect to old azure portal and it will open dialog with Add directory title.

Step 8: Select “Use existing directory” option from drop down list also check the check box of “I am ready to be signed out now” option and click on proceed (tick mark). (It will logout from azure and ask for login)

Step 9: Login with your office 365 account (With Global Rights)

Step 10: It will ask to continue with your active directory. (Note down the name of directory which is highlighted in Single quotes.) Click on “Continue

Step 11: Click on “Sign out now”.

Step 12: It will ask for login again. Click on “Go to the new azure portal” (It will redirect you to new portal)

Step 13: Login with your azure account.

Step 14: Click on “profile Icon” at right top corner.(It will open drop down with all the directory options)

Step 15:  Select directory which you noted down in Step 10. (It will select this directory as current directory).

Step 16: Click on “Azure Active Directory” on left navigation panel.

Step 17: Click on “App Registrations” in newly opened window.

Step 18: Click on “Add” button in newly opened window.

Step 19: Type application name as “YOUR_APPLICATION_NAME” in Name field. Select Application type as “Native“ and enter Sign-on URL as “urn:ietf:wg:oauth:2.0:oob” (This is Redirect URI). Click on create button. (It will add new application in app listing)

Step 20: Click on newly created (YOUR_APPLICATION_NAME) app. Note down “APPLICATION ID

Step 21: Go to settings-àRequired permissions. (It will open new window with title required permissions).

Step 22: Click on “Add” and then click on “Select an API”. Select “Office 365 Exchange online” option from listing and click on “Select” (It will open enable access window).

Step 23: Check “Send mail as user” check box and click on “Select” button.

Step 24: Click on “Done” button in “Add API access” window.

Step 25: Share “APPLICATION ID” noted in Step20 with us.

Integration of Office 365 SDK in your Android Application

 

  1. Download Office 365 SDK with Demo Application
  2. Create your Android Application
  3. Once your android application is ready with Android Studio copy following lines in your app level gradle file
compile('com.microsoft.services:discovery-services:1.0.0@aar') {
transitive = true
}
compile('com.microsoft.services:outlook-services:1.0.0@aar') {
transitive = true
}
  1. Sync your Android Studio Project.
  2. Copy following Java files in you project from the downloaded Office 365 SDK
    1. AuthenticationManager.java
    2. DiscoveryManager.java
    3. MailManager.java
    4. OperationCallback.java
    5. Constants.java
  3. Change the package name in all of the above java files and resolve errors of dependency, if there are any.
  4. Once all the errors are resolved Open Constants.java file and replace your Client ID / Application ID as well as Redirect URI as follows
public static final String CLIENT_ID        = "Your_Client_Or_Application_ID";
public static final String REDIRECT_URI     = "urn:ietf:wg:oauth:2.0:oob";
  1. Now your office 365 application is ready for coding. You can work on Office 365 API to send and receive mails.

Authentication using Office 365 SDK

 

  1. Copy following code to check whether credentials (Client ID / Application ID and Redirect URI) are valid or not
try {
UUID.fromString(Constants.CLIENT_ID);
URI.create(Constants.REDIRECT_URI);
} catch (IllegalArgumentException e) {
Toast.makeText(
this
, "The client ID or redirect URI is not valid. Enter a valid client ID and redirect URI in the Constants.java file and run again"
, Toast.LENGTH_LONG).show();

}
  1. Copy following code to ask for login of user(s) with their office 365 account
AuthenticationManager.getInstance().connect(
new AuthenticationCallback<AuthenticationResult>() {
@Override
public void onSuccess(AuthenticationResult result) {accessToken = result.getAccessToken();refreshToken = result. getRefreshToken ();
Log.i("Office365", "onConnectButtonClick - Successfully connected to Office 365");
}
@Override
public void onError(final Exception e) {
Log.e("Office365", "onCreate - " + e.getMessage());
}
});

This code will open a WebView in which it will automatically open Office 365 Login. When user will get authenticated it will transfer it’s data to the activity and user’s data to onSuccess method.

  1. To set the valid authentication copy following code in your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AuthenticationManager
.getInstance()
.getAuthenticationContext()
.onActivityResult(requestCode, resultCode, data);
}
  1. onSuccess method will give you accessToken and refreshToken to send access user(s) profile.
  2. Office 365 also provides send email method to send customized mail to any email address but that does not provide attachment to attach to the mail. So that you can use explicit API call to send email with attachment.
  3. These tokens get expired over the time period. So by using an API call we can renew the existing token / request a new one.

Renew tokens with explicit API calls

 

public void processLoginRequest() {

try {
RequestBody formBody = new FormBody.Builder()
.add("grant_type", "refresh_token")
.add("refresh_token", refreshToken)
.add("client_id", Constants.CLIENT_ID)
.add("resource", "https://outlook.office365.com")
.build();

Request request = new Request.Builder().addHeader("client-request-id", Constants.CLIENT_ID)
.addHeader("return-client-request-id", "true")
.addHeader("Authorization", "Bearer " + accessToken)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("User-Agent", "APPLICATION_NAME/1.0")
.url(Constants.GET_TOKEN)
.post(formBody)
.build();

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("GET_TOKEN", e.getMessage());
}

@Override
public void onResponse(Call call, final Response response) throws IOException {
//Toast.makeText(context, response.code(), Toast.LENGTH_SHORT).show();
final int statusCode = response.code();
Log.e("STATUS_CODE", statusCode + "");
try {
final String responseStr = response.body().string();
if (response.code() == 200) {

JSONObject jsonObject = new JSONObject(responseStr);
accessToken = jsonObject.get('access_token').toString();
refreshToken = jsonObject.get('refresh_token').toString();

}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}

Send email using explicit API calls

 

public void processSendMail() {
/**
* Creation of JSON Object to send mail to Office 365
* */

JSONObject jsonObject = new JSONObject();
try {

JSONObject jsonMessage = new JSONObject();
jsonMessage.put("Subject", "Your_Email_Subject");

JSONObject jsonBody = new JSONObject();
jsonBody.put("ContentType", "HTML");
jsonBody.put("Content", "Your_Email_Body_In_HTML_Code");

jsonMessage.put("Body", jsonBody);

JSONObject jsonAddress = new JSONObject();
jsonAddress.put("Address", "test@gmail.com");

JSONObject jsonEmailAddress = new JSONObject();
jsonEmailAddress.put("EmailAddress", jsonAddress);

JSONArray jsonRecipients = new JSONArray();
jsonRecipients.put(jsonEmailAddress);

jsonMessage.put("ToRecipients", jsonRecipients);

JSONArray jsonAttachments = new JSONArray();

JSONObject jsonAttachment = new JSONObject();
jsonAttachment.put("@odata.type", "#Microsoft.OutlookServices.FileAttachment");
jsonAttachment.put("Name", "MyFileName.txt");
jsonAttachment.put("ContentBytes", "BASE64_CONTENTS_OF_FILE");
jsonAttachments.put(jsonAttachment);

jsonMessage.put("Attachments", jsonAttachments);

jsonObject.put("Message", jsonMessage);
jsonObject.put("SaveToSentItems", true);

} catch (Exception e) {
e.printStackTrace();
}

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonObject.toString());

Request request = new Request.Builder()
.addHeader("client-request-id", Constants.CLIENT_ID)
.addHeader("return-client-request-id", "true")
.addHeader("Authorization", "Bearer " + accessToken)
.addHeader("Content-Type", "application/json")
.addHeader("User-Agent", "APPLICATION_NAME/1.0")
.url(Constants.SEND_MAIL)
.post(body)
.build();

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("SEND_MAIL", e.getMessage());
/**
* Email sending failed             
* */
}

@Override
public void onResponse(Call call, Response response) {
final int statusCode = response.code();
try {
if (statusCode == 202) {
/**
* Mail Sent Successfully
* */

} else {
/**
* Email sending failed                    
* */

}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *