Following snippets explains you to write Java Clients that consumes Microsoft Exchange Web Services.
From Exchange Server 2010 Microsoft stopped WEBDAV support on exchange server. Java Clients using WEBDAV needs to migrate to consume EWS to fetch mail, compose, send emails ..etc
Read five email items from inbox
Some time it is possible for single user to have multiple mail boxes. Following snippet shows you to access non default mail box for eg sysadmin@abc.com
From Exchange Server 2010 Microsoft stopped WEBDAV support on exchange server. Java Clients using WEBDAV needs to migrate to consume EWS to fetch mail, compose, send emails ..etc
Read five email items from inbox
package demo; import java.net.URI; import microsoft.exchange.webservices.data.ExchangeCredentials; import microsoft.exchange.webservices.data.ExchangeService; import microsoft.exchange.webservices.data.FindItemsResults; import microsoft.exchange.webservices.data.Item; import microsoft.exchange.webservices.data.ItemView; import microsoft.exchange.webservices.data.WebCredentials; import microsoft.exchange.webservices.data.WellKnownFolderName; public class EWSDemo { public static void main(String[] args) throws Exception { ExchangeService service = new ExchangeService(); // Provide Crendentials ExchangeCredentials credentials = new WebCredentials("username", "password"); service.setCredentials(credentials); // Set Exchange WebSevice URL service.setUrl(new URI("https://myexchangehost/EWS/exchange.asmx")); // Get five items from mail box ItemView view = new ItemView(5); // Search Inbox FindItemsResultsReading Body- findResults = service.findItems(WellKnownFolderName.Inbox, view); // iterate thru items for (Item item : findResults.getItems()) { System.out.println(item.getSubject()); } } }
item.getBody()Reading body using the method item.getBody() it yields to exception
Exception in thread "main" microsoft.exchange.webservices.data.ServiceObjectPropertyException: You must load or assign this property before you can read its value.To overcome it first the body needs to be loaded.
item.load();Reading Non default mail box
Some time it is possible for single user to have multiple mail boxes. Following snippet shows you to access non default mail box for eg sysadmin@abc.com
Mailbox mb = new Mailbox(); mb.setAddress("syadmin@abc.com"); FolderId folderId = new FolderId(WellKnownFolderName.Inbox, mb); // Search Inbox syadmin@abc.com FindItemsResultsReading UnRead Emails- findResults = service.findItems( folderId, view);
// Get five items from mail box ItemView view = new ItemView(5); //Set Filter to Read UnRead emails SearchFilter itemFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true); // Search Inbox FindItemsResultsMarking mail as read- findResults = service.findItems(WellKnownFolderName.Inbox,itemFilter,view); // iterate thru items for (Item item : findResults.getItems()) { System.out.println(item.getSubject()); }
// iterate thru items for (Item item : findResults.getItems()) { //Type cast it to EmailMessage EmailMessage em = (EmailMessage) item; em.setIsRead(true); em.update(ConflictResolutionMode.AlwaysOverwrite); System.out.println(em.getSubject()); }Reading mail Headers and body
// iterate thru items for (Item item : findResults.getItems()) { item.load(); String subject=item.getSubject(); //Read Body String body = MessageBody.getStringFromMessageBody(item.getBody()); System.out.println(subject); System.out.println(body); //Reading Header InternetMessageHeaderCollection headers = item.getInternetMessageHeaders(); for(InternetMessageHeader header:headers){ System.out.println("Header Name: "+header.getName()+" Header Value: "+header.getValue() ); } }
Where did you get microsoft.exchange.webservices.data.xxx code from?
ReplyDeleteThat's not what's generated from the wsdl.
Thanks
Bob
For old versions of Exchange (2000-2003-2007) good alternative is WebDAV library for Exchange http://www.independentsoft.de/jwebdav/index.html
ReplyDeleteany idea how to import webdav library to netbeans ?
ReplyDeleteIts Really a good post. It helped me a lot
ReplyDeleteHere are some of the other Items I want to add for this post. This would help others ....
ReplyDeleteTo Find the Mail Box Folders Size
ReplyDelete=====================================
public static void findInboxSize2(ExchangeService service) throws Exception
{
ExtendedPropertyDefinition extendedProperty
= new ExtendedPropertyDefinition(0xe08, MapiPropertyType.Long);
PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties,extendedProperty);
FindFoldersResults folders=null;
FolderView view = new FolderView(Integer.MAX_VALUE);
int pagesize = 50;
do {
folders = service.findFolders(WellKnownFolderName.MsgFolderRoot,
new FolderView(pagesize, view.getOffset(), OffsetBasePoint.Beginning));
for(Folder folder : folders)
{
folder.load(propertySet);
ExtendedPropertyCollection extCollection = folder.getExtendedPropertiesForService();
for (Iterator it = extCollection.iterator(); it.hasNext(); ) {
ExtendedProperty extProp = it.next();
Object value = extProp.getValue();
System.out.println(folder.getDisplayName()+" : " + value);
}
}
int i = view.getOffset();
}while(folders.isMoreAvailable());
}
TO Send Mail using Exchange Web Services (EWS)
ReplyDelete================================================
public static void sendEmail(ExchangeService service, String to, String subject, String body)
throws Exception
{
EmailMessage email = new EmailMessage(service);
email.getToRecipients().add(to);
email.setSubject(subject);
email.setBody(new MessageBody(body));
email.send();
}
Thanks praveen its working for me.
DeleteHi Praveen,
DeleteCan u tell me how to send email on multiple recipient.
Hi,
ReplyDeleteits very helpfull for me thanks alot
Hi,
ReplyDeleteGreat post!
How can I listen to INBOX folder and get an incomming mail with attachmens(more than 2).
I also need to filter the mails according to conditions, i.e - if the subject contain certain string, or an out of office reply mail.
Appriciate your help here.
Thanks
Joe
Hi,
ReplyDeleteHow can i attach inline attachments by using the EWS Managed API.
Actually i want a logo on my form,
Appriciate your help here.
Hi,
ReplyDeleteI can't mark unread message as read.
Get connection failed exception.
Please, help.!
What about load all distribution groups from exchange server??
ReplyDeletehello guys ...
ReplyDeletei have created a account on outlook.com
and now I am trying to read the Inbox as shown below.
But it is not working for me.
My code gets stuck at the line: service.autodiscoverUrl(EMAIL_ID);
Can someone point me to the solution.
Is this EWS suppose to work with Outlook.com?
----------------------------------------------------------------------------------------------------------
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(EMAIL_ID, EMAIL_PWD);
service.setCredentials(credentials);
try {
System.out.println("111111111111111");
service.autodiscoverUrl(EMAIL_ID);
System.out.println("222222222222222");
ItemView view = new ItemView(10);
FindItemsResults findResults;
findResults = service.findItems(WellKnownFolderName.Inbox, view);
for(Item item : findResults.getItems())
{
item.load();
System.out.println(item.getSubject());
}
} catch (Exception e) {
e.printStackTrace();
}
Hi,i want to get email any body tell me what i do for this.i am new in android .i cannot know how i start .
ReplyDeleteHello , I want to know if I can use this code to connect Exchange server 2013.
ReplyDeleteThanks in advance!
I think you ca specify on the Exchange constructor the latest available version and it will work with 2013
DeleteLike:
new ExchangeService(ExchangeVersion.Exchange2010_SP2)
Unser Unternehmen bietet beste Qualität und Web-Entwicklung Dienstleistungen in Deutschland. Wir bieten derzeit Web und mobile Anwendung Entwicklungsdienstleistungen .http://www.accuratesolutionsltd.com/web-entwicklung/
ReplyDeleteHi i am always getting connection timed out error what will be the issue.
ReplyDeleteCan some one tell code how to download email attachments on HD using Java EWS api
ReplyDeleteThis one is good. Keep up the good work I also visit here: and I get lot of information. advertising agencies in missouri
ReplyDelete