package id.boenkkk;
import java.net.URI;
import java.util.*;
import microsoft.exchange.webservices.data.core.*;
import microsoft.exchange.webservices.data.credential.*;
import microsoft.exchange.webservices.data.property.*;
import microsoft.exchange.webservices.data.search.*;
public class MSExchangeEmailService {
private static ExchangeService service;
private static Integer NUMBER_EMAILS_FETCH = 2; // 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://outlook.live.com/ews/exchange.asmx"));
System.out.println("======Set URL OK======");
} catch (Exception e) {
e.printStackTrace();
System.out.println("======Set URL NOT OK======");
}
}
/**
* Initialize the Exchange Credentials.
* Don't forget to replace the "USRNAME","PWD","DOMAIN_NAME" variables.
*/
public MSExchangeEmailService() {
try{
ExchangeCredentials credentials = new WebCredentials("USRNAME", "PWD", "DOMAIN_NAME");
service.setCredentials(credentials);
System.out.println("======CRE OK======");
} catch (Exception e){
e.printStackTrace();
System.out.println("======CRE NOT OK======");
}
}
/**
* 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());
messageData.put("ccRec", emailMessage.getCcRecipients().getItems().toString());
messageData.put("ccDisp", emailMessage.getDisplayCc().toString());
messageData.put("convId", emailMessage.getConversationId().toString());
Date dateTimeCreated = emailMessage.getDateTimeCreated();
messageData.put("SendDate", dateTimeCreated.toString());
Date dateTimeRecieved = emailMessage.getDateTimeReceived();
messageData.put("ReceivedDate", dateTimeRecieved.toString());
messageData.put("Size", emailMessage.getSize() + "");
messageData.put("emailBody", emailMessage.getBody().toString());
System.out.println("======Read Email Item OK======");
} catch (Exception e) {
e.printStackTrace();
System.out.println("======Read Email Item NOT OK======");
}
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));
FolderView view = new FolderView(Integer.MAX_VALUE);
view.setPropertySet(new microsoft.exchange.webservices.data.core.PropertySet(BasePropertySet.IdOnly));
view.getPropertySet().add(FolderSchema.DisplayName);
view.setTraversal(FolderTraversal.Deep);
FindFoldersResults ffr = service.findFolders(new FolderId(WellKnownFolderName.Inbox), view);
int i = 1;
for(Folder folder : ffr){
FolderId id = folder.getId();
for (Item item : service.findItems(folder.getId(), new ItemView(NUMBER_EMAILS_FETCH))) {
Map messageData = new HashMap();
messageData = readEmailItem(item.getId());
System.out.println("===============================================================");
System.out.println("\nEmails #" + (i++) + ":");
System.out.println("EmailItemId : " + messageData.get("emailItemId").toString());
System.out.println("Subject : " + messageData.get("subject").toString());
System.out.println("Sender : " + messageData.get("senderName").toString());
System.out.println("ccRec : " + messageData.get("ccRec").toString());
System.out.println("ccDisp : " + messageData.get("ccDisp").toString());
System.out.println("convId : " + messageData.get("convId").toString());
System.out.println("sendDate : " + messageData.get("SendDate").toString());
System.out.println("ReceivedDate : " + messageData.get("ReceivedDate").toString());
System.out.println("Size : " + messageData.get("Size").toString());
System.out.println("emailBody : " + messageData.get("emailBody").toString());
System.out.println("===============================================================");
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
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
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 and Budi Santoso aka BOENKKK");
EmailMessage message = new EmailMessage(service);
message.setSubject("Test Sending Email");
message.setBody(new MessageBody(strBldr.toString()));
for (String string : recipientsList) {
message.getToRecipients().add(string);
}
for (String string : recipientsListCC){
message.getCcRecipients().add(string);
}
message.sendAndSaveCopy();
System.out.println("======Message Sent======");
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendReply(List
try {
//AQMkADAwATM3ZmYAZS1iZDk3LTBlNWUtMDACLTAwCgBGAAADJNwpX43N/U+gPNHhPb2AYAcAJxZtnJBGzEmnmHlWIHv/pQAAAJEiPZUAAAAnFm2ckEbMSaeYeVYge/+lAAAAztM5qwAAAA==
//AQMkADAwATM3ZmYAZS1iZDk3LTBlNWUtMDACLTAwCgBGAAADJNwpX43N/U+gPNHhPb2AYAcAJxZtnJBGzEmnmHlWIHv/pQAAAJEiPZUAAAAnFm2ckEbMSaeYeVYge/+lAAAAkSJXTwAAAA==
String uniqueId = "AQMkADAwATM3ZmYAZS1iZDk3LTBlNWUtMDACLTAwCgBGAAADJNwpX43N/U+gPNHhPb2AYAcAJxZtnJBGzEmnmHlWIHv/pQAAAJEiPZUAAAAnFm2ckEbMSaeYeVYge/+lAAAAztM5qwAAAA==";
ItemId itm = ItemId.getItemIdFromString(uniqueId );
StringBuilder strBldr = new StringBuilder();
strBldr.append("The client is reply submitted the SendAndSaveCopy request at:");
strBldr.append(Calendar.getInstance().getTime().toString() + " .");
strBldr.append("Thanks and Regards");
strBldr.append("Shantanu Sikdar and Budi Santoso aka BOENKKK");
MessageBody mesBod = new MessageBody(strBldr.toString());
//PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.CcRecipients, EmailMessageSchema.Subject, EmailMessageSchema.Body);
PropertySet propSet = new PropertySet(BasePropertySet.FirstClassProperties);
propSet.add(EmailMessageSchema.From);
propSet.add(EmailMessageSchema.CcRecipients);
//propSet.add(EmailMessageSchema.);
propSet.add(EmailMessageSchema.Subject);
propSet.add(EmailMessageSchema.Body);
EmailMessage message = EmailMessage.bind(service, itm, propSet);
for (String string : recipientsListCC) {
message.getCcRecipients().add(string);
}
boolean replyToAll = true;
ResponseMessage resMsg = message.createReply(replyToAll);
resMsg.setBodyPrefix(mesBod);
//resMsg.sendAndSaveCopy();
System.out.println("service >> "+service);
System.out.println("itm >> "+itm);
System.out.println("propSet >> "+new PropertySet(EmailMessageSchema.CcRecipients));
System.out.println("recipientsListCC >> "+recipientsListCC);
System.out.println("resMsg >> "+resMsg);
System.out.println("message >> "+message);
System.out.println("======Reply Message Sent======");
} catch (Exception e) {
e.printStackTrace();
System.out.println("======Reply Message NOT Sent======");
}
}
public static void main(String[] args) {
MSExchangeEmailService msees = new MSExchangeEmailService();
//msees.readEmails();
//msees.readAppointments();
List recipientsList = new ArrayList<>();
recipientsList.add("email.to@domain1.com");
List recipientsListCc = new ArrayList<>();
recipientsListCc.add("budisantoso.7194@gmail.com");
recipientsListCc.add("email.cc@domain1.com");
//msees.sendEmails(recipientsList,recipientsListCc);
msees.sendReply(recipientsListCc);
}
}