DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Java Is Greener on Arm
  • How to Get Plain Text From Common Documents in Java

Trending

  • AI-Powered Flashcard Application With Next.js, Clerk, Firebase, Material UI, and LLaMA 3.1
  • Build Retrieval-Augmented Generation (RAG) With Milvus
  • Java 23: What Developers Need to Know
  • Boosting Efficiency: Implementing Natural Language Processing With AWS RDS Using CloudFormation
  1. DZone
  2. Coding
  3. Java
  4. Send, read Emails and Appointments From MS Exchange [using Java]

Send, read Emails and Appointments From MS Exchange [using Java]

This code will help you connect your app to MS Exchange using the EWS Java API. In its current form, the snippet fetches emails and appointments and can be broadened.

By 
Shantanu Sikdar user avatar
Shantanu Sikdar
·
Dec. 27, 16 · Code Snippet
Likes (6)
Comment
Save
Tweet
Share
66.0K Views

Join the DZone community and get the full member experience.

Join For Free

While enabling my application with MS Exchange, I end up writing this code. I used the EWS Java API (EWSJavaAPI_1.2.jar) (The JAR I uploaded with this snippet.). 

The snippet fetches emails and appointments with limited features, like subjects, sender name, appointment times, etc. But we can very well add other components and make it a full-fledged email application. Feel free to add your components.

I've tested the code against Exchange Version 2010 and 2007 and it worked well. But firs, please check to see if EWS is enabled for the MS Exchange you are using.

Also, if any of you readers have something better to suggest, please do so.

It's been quite long I revisited this post of mine. In the original version, I, unfortunately, missed the email sending code. That's been remedied, and you can find the email sending code in the snippet below. 

import microsoft.exchange.webservices.data.*;

import java.net.URI;
import java.util.*;

/**
 * @author Shantanu Sikdar
 */

public class MSExchangeEmailService {

    private static ExchangeService service;
    private static Integer NUMBER_EMAILS_FETCH = 5; // only latest 5 emails/appointments are fetched.

    /**
     * Firstly check, whether "https://webmail.xxxx.com/ews/Services.wsdl" and "https://webmail.xxxx.com/ews/Exchange.asmx"
     * is accessible, if yes that means the Exchange Webservice is enabled on your MS Exchange.
     */
    static {
        try {
            service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
//service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); //depending on the version of your Exchange. 
            service.setUrl(new URI("https://webmail.xxxx.com/ews/Exchange.asmx"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialize the Exchange Credentials.
     * Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
     */
    public MSExchangeEmailService() {
        ExchangeCredentials credentials = new WebCredentials("USRNAME", "PWD", "DOMAIN_NAME");
        service.setCredentials(credentials);
    }

    /**
     * Reading one email at a time. Using Item ID of the email.
     * Creating a message data map as a return value.
     */
    public Map readEmailItem(ItemId itemId) {
        Map messageData = new HashMap();
        try {
            Item itm = Item.bind(service, itemId, PropertySet.FirstClassProperties);
            EmailMessage emailMessage = EmailMessage.bind(service, itm.getId());
            messageData.put("emailItemId", emailMessage.getId().toString());
            messageData.put("subject", emailMessage.getSubject().toString());
            messageData.put("fromAddress", emailMessage.getFrom().getAddress().toString());
            messageData.put("senderName", emailMessage.getSender().getName().toString());
            Date dateTimeCreated = emailMessage.getDateTimeCreated();
            messageData.put("SendDate", dateTimeCreated.toString());
            Date dateTimeRecieved = emailMessage.getDateTimeReceived();
            messageData.put("RecievedDate", dateTimeRecieved.toString());
            messageData.put("Size", emailMessage.getSize() + "");
            messageData.put("emailBody", emailMessage.getBody().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageData;
    }

/**
 * Number of email we want to read is defined as NUMBER_EMAILS_FETCH, 
 */
    public List>

    readEmails() {
        List > msgDataList = new ArrayList > ();
        try {
            Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
            FindItemsResults results = service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH));
            int i = 1;
            for (Item item : results) {
                Map messageData = new HashMap();
                messageData = readEmailItem(item.getId());
                System.out.println("\nEmails #" + (i++) + ":");
                System.out.println("subject : " + messageData.get("subject").toString());
                System.out.println("Sender : " + messageData.get("senderName").toString());
                msgDataList.add(messageData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msgDataList;
    }

    /**
     * Reading one appointment at a time. Using Appointment ID of the email.
     * Creating a message data map as a return value.
     */
    public Map readAppointment(Appointment appointment) {
        Map appointmentData = new HashMap();
        try {
            appointmentData.put("appointmentItemId", appointment.getId().toString());
            appointmentData.put("appointmentSubject", appointment.getSubject());
            appointmentData.put("appointmentStartTime", appointment.getStart() + "");
            appointmentData.put("appointmentEndTime", appointment.getEnd() + "");
            //appointmentData.put("appointmentBody", appointment.getBody().toString());
        } catch (ServiceLocalException e) {
            e.printStackTrace();
        }
        return appointmentData;
    }

    /**
     *Number of Appointments we want to read is defined as NUMBER_EMAILS_FETCH,
     *  Here I also considered the start data and end date which is a 30 day span.
     *  We need to set the CalendarView property depending upon the need of ours.   
     */
    public List>

    readAppointments() {
        List > apntmtDataList = new ArrayList > ();
        Calendar now = Calendar.getInstance();
        Date startDate = Calendar.getInstance().getTime();
        now.add(Calendar.DATE, 30);
        Date endDate = now.getTime();
        try {
            CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
            CalendarView cView = new CalendarView(startDate, endDate, 5);
            cView.setPropertySet(new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));// we can set other properties 
            // as well depending upon our need.
            FindItemsResults appointments = calendarFolder.findAppointments(cView);
            int i = 1;
            List appList = appointments.getItems();
            for (Appointment appointment : appList) {
                System.out.println("\nAPPOINTMENT #" + (i++) + ":");
                Map appointmentData = new HashMap();
                appointmentData = readAppointment(appointment);
                System.out.println("subject : " + appointmentData.get("appointmentSubject").toString());
                System.out.println("On : " + appointmentData.get("appointmentStartTime").toString());
                apntmtDataList.add(appointmentData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return apntmtDataList;
    }

    public void sendEmails(List recipientsList) {
        try {
            StringBuilder strBldr = new StringBuilder();
            strBldr.append("The client submitted the SendAndSaveCopy request at:");
            strBldr.append(Calendar.getInstance().getTime().toString() + " .");
            strBldr.append("Thanks and Regards");
            strBldr.append("Shantanu Sikdar");
            EmailMessage message = new EmailMessage(service);
            message.setSubject("Test sending email");
            message.setBody(new MessageBody(strBldr.toString()));
            for (String string : recipientsList) {
                message.getToRecipients().add(string);
            }
            message.sendAndSaveCopy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("message sent");
    }

    public static void main(String[] args) {
        MSExchangeEmailService msees = new MSExchangeEmailService();
        msees.readEmails();
        msees.readAppointments();
        List recipientsList = new ArrayList<>();
        recipientsList.add("email.id1@domain1.com");
        recipientsList.add("email.id2@domain1.com");
        recipientsList.add("email.id3@domain2.com");
        msees.sendEmails(recipientsList);
    }
}
Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta WebSocket Essentials: A Guide to Full-Duplex Communication in Java
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Java Is Greener on Arm
  • How to Get Plain Text From Common Documents in Java

Partner Resources


Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: