Monday, December 19, 2016

Java Send Email Using Office 365 OAuth Connection

Download source code from here

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html



package com.pkm.office_oauth;

import com.google.gson.Gson;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by pritom on 18/12/2016.
 */
public class JavaSendMailUsingOffice365OAuth {
    private static final String OFFICE_ACCESS_TOKEN = "xxxxx";
    private static String mailUUID = "";

    /**
     * API URL
     * https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#MessageResource
     * https://msdn.microsoft.com/en-us/office/office365/api/extended-properties-rest-operations
     */

    public static void main(String[] args) throws Exception {
        send();
    }

    private static void send() throws Exception {
        Map<String, Object> message = new HashMap<>();
        message.put("Subject", "Some Sample Subject");
        message.put("Body", getBody());
        addRecipients(message);
        addCustomHeader(message);
        addAttachment(message);

        Map<String, Map> messagePayload = new HashMap<>();
        messagePayload.put("Message", message);

        Gson gson = new Gson();
        String messageAsJson = gson.toJson(messagePayload);

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        headers.add("Content-Type: application/json");
        headers.add("Content-Length: " + messageAsJson.length());

        String url = "https://outlook.office.com/api/v2.0/me/sendmail";
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, messageAsJson, headers);
        System.out.println("STATUS_CODE=" + response.httpCode);
        if (response.httpCode == 202) {
            System.out.println("MESSAGE SENT\r\n\r\nTRY TO RETRIEVE MAIL SENT");
            filterMessageSent();
        }
        else {
            System.out.println(response);
        }
    }

    private static void filterMessageSent() throws Exception {
        String query = "SingleValueExtendedProperties/Any" +
                URLEncoder.encode("(ep: ep/PropertyId eq 'String {" + mailUUID + "} Name CUSTOM_HEADER_1' and ep/Value eq 'CUSTOM_HEADER_1_VALUE_" + mailUUID + "')", "UTF-8");
        String select = "Id,InternetMessageId";
        String url = "https://outlook.office.com/api/v2.0/me/messages?$filter=" + query + "&$select=" + select;

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, "", headers);
        if (response.httpCode == 200) {
            Map result = new Gson().fromJson(response.httpResponse, Map.class);
            result = (Map) ((List) result.get("value")).get(0);
            System.out.println("UNIQUE_OFFICE_MAIL_ID_OF_SEND_EMAIL=" + result.get("Id"));
            System.out.println("UNIQUE_MESSAGE_ID_OF_SEND_EMAIL=" + result.get("InternetMessageId"));
        }
    }

    private static void addCustomHeader(Map<String, Object> message) {
        List<Map> list = new ArrayList<>();
        mailUUID = UUID.randomUUID().toString();

        Map<String, String> val1 = new HashMap<>();
        val1.put("PropertyId", "String {" + mailUUID + "} Name CUSTOM_HEADER_1");
        val1.put("Value", "CUSTOM_HEADER_1_VALUE_" + mailUUID);

        list.add(val1);

        message.put("SingleValueExtendedProperties", list);
    }

    private static JavaSendMailUsingOffice365OAuth.Response executeSend(String url, String messageAsJson, List<String> headers) throws Exception {
        int httpCode = 0, timeOutMilli = 1000 * 30;;
        String httpResponse = "", responseMessage = "";

        HttpURLConnection connection = null;
        try {
            System.setProperty("https.protocols", "TLSv1.1,SSLv3,SSLv2Hello");
            connection = (HttpURLConnection) new URL(url).openConnection();
            if (messageAsJson.length() > 0) {
                connection.setRequestMethod("POST");
            }
            else {
                connection.setRequestMethod("GET");
            }
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            for (int i = 0; i < headers.size(); i++) {
                String header = headers.get(i);
                connection.setRequestProperty(header.substring(0, header.indexOf(":")), header.substring(header.indexOf(":") + 1));
            }

            if (messageAsJson.length() > 0) {
                connection.setDoInput(true);
                OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
                streamWriter.write(messageAsJson);
                streamWriter.flush();
                streamWriter.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream inputStream = null;

            if (httpCode >= 200 && httpCode <= 399) {
                inputStream = connection.getInputStream();
            }
            else {
                inputStream = connection.getErrorStream();
            }

            if (inputStream != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
                Reader reader = new BufferedReader(new InputStreamReader(inputStream));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
                httpResponse = writer.toString();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            responseMessage = ex.getMessage();
        }
        return new JavaSendMailUsingOffice365OAuth.Response(httpCode, responseMessage, httpResponse);
    }

    private static Map<String, Object> getBody() throws Exception {
        Map<String, Object> body = new HashMap<>();

        body.put("ContentType", "HTML");
        body.put("Content", new String("<DIV><B>HTML BODY CONTENT</B></DIV>".getBytes(), "UTF-8"));

        return body;
    }

    private static void addRecipients(Map<String, Object> message) {
        Map<String, Map> recipientMap = new HashMap<>();
        Map<String, String> recipientAddress = new HashMap<>();
        recipientAddress.put("Address", "pritom@xxxxx.com");
        recipientMap.put("EmailAddress", recipientAddress);

        List<Map> recipients = new ArrayList<>();
        recipients.add(recipientMap);

        message.put("ToRecipients", recipients);
    }

    private static void addAttachment(Map<String, Object> message) throws Exception {
        List<Map> attachments = new ArrayList<>();

        File file = new File("src/com/pkm/office_oauth/Attachment_Image_1.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        file = new File("src/com/pkm/office_oauth/Attachment_Pdf_1.pdf");
        fileInputStream = new FileInputStream(file);
        toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("@odata.type", "#Microsoft.OutlookServices.FileAttachment");
        attachment.put("Name", file.getName());
        attachment.put("ContentBytes", encodeBase64(toByte));

        attachments.add(attachment);
        message.put("Attachments", attachments);
    }

    private static String encodeBase64(byte[] bytes) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes);
    }

    private static class Response {
        int httpCode = 0;
        String httpResponse = "", responseMessage = "";

        public Response(int httpCode, String responseMessage, String httpResponse) {
            this.httpCode = httpCode;
            this.responseMessage = responseMessage;
            this.httpResponse = httpResponse;
        }

        public String toString() {
            Map<String, Object> output = new HashMap<>();
            output.put("httpCode", httpCode);
            output.put("responseMessage", responseMessage);
            output.put("httpResponse", httpResponse);
            return new Gson().toJson(output);
        }
    }
}

No comments:

Post a Comment