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.
Join the DZone community and get the full member experience.
Join For FreeWhile 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);
}
}
Opinions expressed by DZone contributors are their own.
Comments