Search Wiki:
Resource Page Description
Java implementation of the Exchange Web Services (EWS) API. This API gives developers programmatic access to Exchange Server 2007 SP1 and above.


Last edited Sep 30 2010 at 3:53 PM  by paulwim, version 2
Comments
KRISC wrote  Oct 21 2010 at 1:55 PM  
That would be great! got a date?

alexsott wrote  Nov 8 2010 at 11:51 PM  
Right, what is the time frame? Can't wait.
Also, what are the external dependencies?

paulwim wrote  Dec 11 2010 at 5:41 PM  
The EWS Java API 1.1 is now ready for download

Rodi wrote  Dec 24 2010 at 4:47 AM  
I'm trying to use the API and got stuck on Item.setExtendedProperty when the property type (1st argument) is LongArray.
The value (2nd argument) is Object, but no value I set passes internal validaton. arrays, collections, arraylists etc.

What is the expected value type?

jgmandar wrote  Dec 29 2010 at 9:05 AM  
Hi,

Can you please help us on using EWS Java API for Exchange 2007 SP1 related queries :

http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/c6684b26-92f3-4381-9862-6187859b8d1b
http://social.technet.microsoft.com/Forums/en-us/exchangesvrdevelopment/thread/9e20cc54-ca13-4bed-ac92-0a17d6ae3377

Urgent Help would be appreciated.

Mandar

rpzatkoff wrote  Jan 1 2011 at 11:23 PM  
what happened to this? why is there no release?

MrHaller wrote  Jan 4 2011 at 1:24 PM  
I also would love to try this out. When does the download come back?

MichaelMainer wrote  Jan 4 2011 at 6:14 PM  
I'm looking into this.

XCHMAN wrote  Jan 5 2011 at 2:09 PM  
I'm also very interested into using the EWS Java API please publish it again.

rpzatkoff wrote  Jan 5 2011 at 9:25 PM  
Does anybody have another link to this, or any idea why it was taken down or when it will be back?

paulwim wrote  Jan 7 2011 at 9:09 PM  
Hello EWS Java experts. We recently had to remove the EWS Java API from Code Gallery (http://code.msdn.microsoft.com/ewsjavaapi) in order to do some additional testing. We will be reposting an updated package as soon as we can. For those who have already downloaded it, please refrain from using in a production environment until additional testing is complete. Once we’ve reposted the package you can use it in your production environment. Until then, continue to use it in your development environments and provide feedback with any issues you encounter. We’ve seen a good response so far, and we’ll work as quickly as we can to get an updated package posted.

rpzatkoff wrote  Jan 8 2011 at 9:57 PM  
Thank you for your response paul. I am wondering if you could give me a link to the API regardless of us not being able to use it in any production environment. I have been putting off starting development on a project for a long time that I hope to use this in. I realize there are bugs of some sort but I am only in the beginning stages of development and don't need it to be perfect, I just would like the code in place so that it will compile and I can move past this part of my project.

regularfry wrote  Jan 10 2011 at 11:39 AM  
Can we have a little more detail, please? I've got a copy of 1.1 here, but right now I don't know if I'm likely to hit the problem you've found in development, how long a fix is likely to take (weeks? Months?), whether it applies to Exchange 2007 or not, whether the fix might invalidate the work I've already done, or whether I should just go back to slogging away with Exchange's WSDL. A little more guidance would be most appreciated.

aadvani wrote  Jan 14 2011 at 7:52 AM  
Cant imagine, its been a week and the guys at Microsoft have not been able to provide a new update.Shame!!

SimonBMB wrote  Jan 14 2011 at 9:27 AM  
I have found pure Java API for different versions of Exchange servers.

Check out http://www.independentsoft.de/jwebservices/index.html

paulwim wrote  Jan 14 2011 at 10:46 PM  
Hi everyone, I apoplogize for the delay in responding. Unfortunately, I am unable to provide more details at this time. Please know that there is a group of folks working very hard to address this and we'll repost as soon as we can. We take issues we do find seriously and ensure that there isn't a broad impact. I'll provide another update next week on progress, and possibly an eta.

vijaishanker wrote  Jan 18 2011 at 11:01 AM  
hi paul, any news yet of this library? Please keep us updated.

VenkatAy wrote  Jan 19 2011 at 4:39 AM  
Hi Vijayshankar, we are still working on this and will post an updated library as soon as we have it. We know this is important to resolve and are giving it our highest priority. But the issue is a tricky one and taking some time to workaround. Sorry again for the delay.

mweiss wrote  Jan 31 2011 at 2:33 PM  
Hi, I just wanted to as if the testing is still in progress and if you can tell an approximate release date?

jl wrote  Feb 3 2011 at 12:15 AM  
Also curious, will this be available again any time soon?

vieuxpelican wrote  Feb 4 2011 at 5:46 AM  
Hi, Is any body able to share a previous downloaded version? I am on a project wich needs it, and i have to achieve the goal in a few hours... Bests regard's

cedric_fr wrote  Feb 4 2011 at 9:14 AM  
Hi, I also have a project to use this API. Can you make available the previous version in order to advance?

borgar wrote  Feb 4 2011 at 10:52 AM  
Hi. I'm on the same boat as you guys. If anyone is willing to share the previous version... that would be awesome.

Fussspilz wrote  Feb 6 2011 at 11:24 PM  
yes, me too. A previous version would be fine!

meebster wrote  Feb 7 2011 at 9:55 AM  
Hi, has anyone managed to get hold of the previous API version. Looks like I'm in the same boat as a few of you. Any possibility of sharing would be REALLY helpful. Thanks in advance...

cedric_fr wrote  Feb 7 2011 at 4:52 PM  
A nice person sent me the API in version 1.1, I share:
http://uploading.com/files/17bca29b/EWSJavaAPI1.1.zip/

borgar wrote  Feb 7 2011 at 5:40 PM  
Awesome. Thanks a bunch :)

tippex wrote  Feb 7 2011 at 7:23 PM  
Thx :)

jl wrote  Feb 9 2011 at 3:39 AM  
TY!

duhuuu wrote  Feb 14 2011 at 10:41 PM  
Two months and still no update, you haven't even told us what this "issue" and its impact is. (It mostly seems to work fine for us, though.)

Very, very disappointing that this is so badly supported.

paulwim, "tak[ing] issues [...] seriously" is different, and leaving your users in the dark for such a long time is downright unprofessional. "unable to provide more details"? seriously??
VenkatAy: what happened to "highest priority"?

RussellSouza wrote  Feb 15 2011 at 1:05 PM  
I also have a project requiring the use of EWS for Java. Is there any update?

VenkatAy wrote  Feb 22 2011 at 9:13 PM  
Sorry again for the delay. I understand your frustration and regret the inconvenience this has caused you. The good news is that we have made significant progress and plan to make an updated API package available by March 1st. Thanks for your patience.

drousseau wrote  Feb 24 2011 at 2:14 AM  
If I understand correctly, an updated version of EWS Java api v1.1 would available next week? Great news!

paulwim wrote  Feb 25 2011 at 3:36 PM  
Hello EWS Java experts. We have posted an updated EWS Java API package. Please note that this package has new list of pre-requisities: Apache Commons HttpClient 3.1, Apache Commons Codec 1.4, Apache Commons Logging 1.1.1 and JCIFS 1.3.15. We made these changes to address issues with incorrect credential caching for some types of multi-threaded client implementations caused by a bug (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6626700) with java.net.HttpURLConnection (http://download.oracle.com/javase/6/docs/api/java/net/HttpURLConnection.html). Thanks for your patience and please let us know if you run into any problems.

yoxel wrote  Feb 27 2011 at 10:03 AM  
Where do I file bugs or enhancement requests for this API?
I am wondering if the message:flagStatus property could be exposed to us?
And would it be possible to do search based on this property?
I tried to add it as an ExtendedProperty but ran into an NPE when using it:

ExtendedPropertyDefinition ccc = new ExtendedPropertyDefinition(UUID.fromString("00062008-0000-0000-C000-000000000046"), 0x10900003, MapiPropertyType.Short);

Exception in thread "main" java.lang.NullPointerException
at microsoft.exchange.webservices.data.ExtendedPropertyDefinition.isEqualTo(Unknown Source)
at microsoft.exchange.webservices.data.ExtendedPropertyDefinition.equals(Unknown Source)
at java.util.ArrayList.indexOf(ArrayList.java:216)
at java.util.ArrayList.contains(ArrayList.java:199)
at microsoft.exchange.webservices.data.PropertySet.add(Unknown Source)

btonmicha wrote  Mar 1 2011 at 4:42 PM  
Error: microsoft.exchange.webservices.data.ServiceRequestException: The request failed. An element node 'soap:Envelope' of the type START_ELEMENT was expected, but node 'head' of type START_ELEMENT was found.

User authentication seems to be ok... web service methods calls throw the exception above... whats wrong? any suggestions? thx

nestoru wrote  Mar 3 2011 at 5:41 PM  
Hi,

Here are some suggestions:

1. Opening an official project with bug tracking etc. This is the second file that I see with the same version number. Version tracking is important.
2. Fixing the ant script so it actually works. People can then generate a jar file and then later include it in their projects no matter if they use Eclipse, Netbeans etc.
3. Mavenizing the project should be the best to do in my opinion. That will keep installation instructions straightforward and seamless integration in existing projects === more agile.

For those looking for a free open source alternative (and already tested Java API) you can checkout the code based on JAX-WS from http://nestorurquiza.googlecode.com/svn/trunk/ews/ A discussion about the EWS SOAP API including the history about why I picked JAX-WS can be reached at http://thinkinginsoftware.blogspot.com/2011/02/exchange-web-services-ews-from-java.html

Thanks for the work on this managed API
-Nestor

VenkatAy wrote  Mar 3 2011 at 9:20 PM  
Hi yoxel, btonmicha, and Nestor - Thanks for reporting the issues you are seeing, feature requests, and suggestions for improving this. We will review the issues you are seeing and get back to you. We have added your feature requests and suggestions to the list we evaluate for subsequent releases.

Catalin wrote  Mar 16 2011 at 10:43 AM  
Hello, I am trying to use ews java api to get my exchange emails... I have installed exchange server 2010 installed and when I am running the following code I get this error:
Mar 16, 2011 12:27:10 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected
Mar 16, 2011 12:27:10 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected
microsoft.exchange.webservices.data.AutodiscoverLocalException: The Autodiscover service couldn't be located.

Code:

ExchangeService service = new ExchangeService();

ExchangeCredentials credentials = new WebCredentials("cata@domain.com",
"pass.");
service.setCredentials(credentials);


try {
service.autodiscoverUrl("cata@domain.com");
} catch (Exception e) {
e.printStackTrace();
}
What is wrong?
Thank you!

eduardroccatello wrote  Mar 18 2011 at 11:00 AM  
How can we create a TimeZoneDefinition needed to create appointments?
It is a major issue for me :-(

Eduard

RichardB wrote  Mar 20 2011 at 8:33 AM  

Hi,

First off, thanks for making this library available.

There appears to be a bug when updating contacts. The xml that is generated is as follows:

<t:IndexedFieldURI FieldURI="contacts:EmailAddress" FieldIndex="EmailAddress1"></t:IndexedFieldURI>
<t:Contact>
<t:FieldURI>
<t:Entry Key="EmailAddress1">changedemail@example.com</t:Entry>
</t:FieldURI>
</t:Contact>

When I think it should be:

<t:IndexedFieldURI FieldURI="contacts:EmailAddress" FieldIndex="EmailAddress1"/>
<t:Contact>
<t:EmailAddresses>
<t:Entry Key="EmailAddress1">changedemail@example.com</t:Entry>
</t:EmailAddresses>
</t:Contact>

FieldURI is being written instead of EmailAddresses and causes an error.
Can this be fixed? Is there any work around?

Thanks,

Richie

RichardB wrote  Mar 20 2011 at 8:39 AM  
@Catalin on your IIS server try disabling all authentication types except basic authentication. That worked for me.

richieb wrote  Mar 21 2011 at 12:36 PM  
@eduardroccatello I am now facing the same problem. Did you manage to find how to do this?

I am unable to create any appointments with exchange 2007, this is a major blow to my development.

paulnibin wrote  Mar 23 2011 at 4:46 AM  
Getting effectiveRights from the folder causes ClassCastException.

ExchangeService service = TestUtils.getExchangeService();
Folder folder = Folder.bind( service, WellKnownFolderName.Inbox );
System.out.println( folder.getDisplayName() );
System.out.println( folder.getEffectiveRights() );

It is causing the following ClassCastException.

Exception in thread "main" java.lang.ClassCastException: java.util.RegularEnumSet cannot be cast to microsoft.exchange.webservices.data.EffectiveRights
at microsoft.exchange.webservices.data.Folder.getEffectiveRights(Folder.java:802)
at test.FolderTest.main(FolderTest.java:14)

paulnibin wrote  Mar 23 2011 at 4:56 AM  
I have posted some issues in the forum.

If anyone could, please help me.

http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/484bb22d-1c40-4a5d-ad8e-564fdf8f568e
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/bc99587b-08ea-435c-91de-7e02da2c11a3
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/55507eb2-7f5b-4f13-b5bd-9a4d057b20b1
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/c7f04dc1-3c46-4617-8db7-8f023f60dcc1
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/431d6ca0-0701-4474-a354-4257070a6801
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/0f577585-a4d0-4539-9fde-f2fa5c5f20e5
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/352c2699-9915-4726-bed8-0449c0cff5d2
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/6a3b187a-e16c-44c0-8349-7136e9607298
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/fa8cb203-e06e-4dc5-9d5b-f069ef9d6555
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/6022b432-e943-40d9-95cc-21d6c95f8e3d
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/68d30268-79f4-45dd-8d4f-ebc9aaba30f7
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/88fb1fc4-dc1c-407a-a0dd-7afcc675171a
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/d6ff7e02-3205-4cae-b3ca-64a08246faf0

Thanks in advance,
Paul

paulnibin wrote  Mar 23 2011 at 5:12 AM  
@eduardroccatello I am also facing some some problem with time zones when creating the appointments.

When I create appointment, I set the start and end dates. But when I check in the out look to verify whether the appointment is created, it is actually created 5 and half hours after the time specified in the start and end dates. i.e, if i specify 12:00 PM as my start time, the appointment is created at 5:30 PM.

For fixing this issue, I think I need to specify the startTimeZone. Did you find a way to create the TimeZoneDefinition?

If found the classes GetServerTimeZonesRequset and Response. But it is not used anywhere and I cannot use them directly in my code.

Did you manage to find a solution?

Thanks,
Paul

frankberlanga wrote  Mar 23 2011 at 8:37 PM  
The "setResources()" method from the Appointment class appears to be missing from the api. For instance, I can "getResources()" for an appointment object, but there is no method to set them. How can you set resources for an appointment?

paulnibin wrote  Mar 24 2011 at 6:15 AM  
@frankberlanga

AttendeeCollection resources = appointment.getResources();
resources.add("resource1");
resources.add("resource2");
...

paulnibin wrote  Mar 24 2011 at 6:21 AM  
@eduardroccatello
@richieb
@frankberlanga

If you are working on appointments, could you take a look into the forum post
http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/d6ff7e02-3205-4cae-b3ca-64a08246faf0

Did you have faced this issue and managed to find a solution?

eduardroccatello wrote  Mar 24 2011 at 8:12 AM  
Still nothing :-(
I'm trying to manage some hacks but still no results...

An update from Microsoft would be appreciated...

prentice wrote  Mar 29 2011 at 5:13 PM  
@eduardroccatello
@richieb

I am seeing the same issue you are with creating an appointment in Exchange 2007 SP1. The strange thing is that looking at the schema for 2007 (http://msdn.microsoft.com/en-us/library/aa580675%28v=EXCHG.80%29.aspx, make sure it says 2007), there is no element called startTimeZone. This only exists in 2010.

What I did to get this working is to comment out the lines that's doing the validation and setting in the API. They are line 249, 250, and 256 in Appointment.java. It worked for me once I did that.

sourabh2182 wrote  Mar 30 2011 at 5:32 AM  
Can we use this API in our application product which is commercial and we are selling it as our base product.

dbcoder wrote  Apr 1 2011 at 12:11 AM  
@paulnibin
@eduardroccatello
@richieb
@frankberlanga

I think I found problem to the date/time formatting issue (for appointments). The convertDateTimeToUniversalDateTimeString function in ExchangeServiceBase.java file is coded incorrectly. It does not convert to UTC as required. It just uses your local time and formats the *string* to look like it is UTC so you are off by a number of hours (depending on your location).

The solutions to modify the code to look like this:

protected String convertDateTimeToUniversalDateTimeString(Date dt) {

DateFormat utcFormatter = null;
String utcPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
utcFormatter = new SimpleDateFormat(utcPattern);
--- INSERT ----> utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
return utcFormatter.format(dt);
}

You will need to import "import java.util.TimeZone;" as well to make it work.

Tell me how it goes...

jcustovic wrote  Apr 8 2011 at 11:38 AM  
A fix for this (http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/c53f76f3-4241-42ad-89e2-29f9450f0ca5) in the future will also be appreciated.

SlowStrider wrote  Apr 14 2011 at 3:12 PM  
We are currently using the exchange webservices directly through JAX-WS and wish to evaluate using this API. Instead of autodiscovery I am trying to connect to the URL "https://ourServerHost/EWS/Services.wsdl".
When I try to acces the inbox I get:

14-apr-2011 16:51:53 org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected
Exception in thread "main" microsoft.exchange.webservices.data.ServiceRequestException: The request failed. The remote server returned an error: (405)Method Not Allowed

With JAX-WS we solved this by setting System.setProperty("http.auth.preference", "basic") which is picked up by the java.net libraries. But this API uses apache commons HttpClient. I can find how to set this preference on HttpClient, but unfortunately this is used internally by microsoft.exchange.webservices.data.ExchangeService. Is there a way to set this preference without having to hack ExchangeService code..?

SlowStrider wrote  Apr 15 2011 at 8:29 AM  
Solved my problem by using the URL "https://ourServerHost/EWS/Exchange.asmx", still uses NTLM authentication but seems to connect fine!

DMI wrote  Apr 22 2011 at 5:26 PM  
slowStrider - what do you set for credentials? I cannot connect with NTLM, getting unauthorized.

nondescriptive wrote  May 2 2011 at 5:45 PM  
Other operations such as creating folders, retrieving information about the existing items, folders seem working but sending message to an email address is not working. Can you figure out why? I appreciate your reply.

ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("validuser","validpass");
service.setCredentials(credentials);

service.setUrl(new URI("https://valid_server/ews/Exchange.asmx"));

EmailMessage msg= new EmailMessage(service);
msg.setSubject("Hello world!");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS Managed API."));
msg.getToRecipients().add("validname@hotmail.com");

msg.sendAndSaveCopy();
System.out.println("done");


sawzeb wrote  May 6 2011 at 3:19 PM  
Hi everybody,

Could you give me some help about EWS Exchange Managed API 1.1, in fact I have two questions

1 I would like to know how to create a Exchange 2010 mailbox using java ? could I have a sample code

2 On the msdn's web site, i find that we can use Exchange 2010 EWS to create user configuration (this is the link http://msdn.microsoft.com/fr-fr/library/gg274402%28v=EXCHG.80%29.aspx ), for the example, what do xmldata and binarydata mean ? could i have a sample code



thanks in advance

AnandMSFT wrote  May 12 2011 at 1:31 PM  
Hi nondescriptive, thanks for reporting this issue. We tried this and we were unable to repro the issue . To continue the investigation, we will contact you in private to get more details.

AnandMSFT wrote  May 12 2011 at 2:03 PM  
Hi paulnibin , this is regarding the issue "Parse error comes when getting the tasks". thanks for reporting this issue. We tried this and we were unable to repro the issue . To continue the investigation, we will contact you in private to get more details."

AnandMSFT wrote  May 12 2011 at 2:11 PM  
Hi paulnibin , this is regarding the issue "Randomly getting CloneNotSupportedException while getting the DisplayPermissionLevel from the Folder object". Thanks for reporting this issue. We tried this and we were unable to repro the issue . To continue the investigation, we will contact you in private to get more details."

AnandMSFT wrote  May 13 2011 at 1:23 PM  
As per my private conversation with nondescriptive , The issue "Other operations such as creating folders, retrieving information about the existing items, folders seem working but sending message to an email address is not working ....".
is not ews java api issue and was a exchange configuration issue that prevented sending emails. This issue is resolved.

y0da22 wrote  May 20 2011 at 8:05 PM  
Hello, I know this issue has been discussed here, but I am still unable to set time time zone on a newly created appointment. I can create the appointment by commenting out the validate code in the appointment class, but what happens is that the start time is wrong when looking at the calendar. I set the time to 115, but in the month view it says 915. Funny thing is is that when I open the actual entry that was created, I see the correct time, but the wrong time zone. I am in EST, but it displays Monrovia, Reykjavik...I am guessing that is the default UTC timezone.

Also I am using exchange 2007 sp1.

Any help would be appreciated as this api is great, and will allow me to do what I have to do for one of my clients. All I need is this time zone issue to be resolved.

Let me know. Thanks.

prentice wrote  May 23 2011 at 8:10 AM  
@y0da22

This was harder to do, and you should really test this more thoroughly than I in what impact this has on other parts of the system. But so far, it has worked fine for me to get the correct time zone to appear.

First thing I did is to create a new method called setMeetingTimeZone somewhere in the EWS package (Appointment.java is a good place for this). This method must reside within the package because the class and methods you are invoking are protected.

public void setMeetingTimeZone( String timeZoneId, String timeZoneName) throws Exception {
TimeZoneDefinition tzd = new TimeZoneDefinition();
tzd.setId(timeZoneId);
MeetingTimeZone mt = new MeetingTimeZone(tzd);
mt.setName(timeZoneName);

this.getPropertyBag().setObjectFromPropertyDefinition(
AppointmentSchema.MeetingTimeZone, mt);
}

In AppointmentSchema.java, I changed

this.registerInternalProperty(MeetingTimeZone);

to

this.registerProperty(MeetingTimeZone);

That should be it. When you create the calendar item, pass in a time zone ID and time zone name with the new method. For example, if you are in PST, you can try "America/Los_Angeles" as the ID, and "Pacific Standard Time" as the name.

Once you have gone that far, you can even define your zone with the TimeZoneDefinition class and TimeChange class. If you do go that route, note that there's a bug in the MeetingTimeZone.java, and also the format generated by the method toXSTime in Time.java doesn't seem to work for 2007. It's fairly easy to fix if you look at example XML files and what files the format should be sent in.

Hope that helps.

AnandMSFT wrote  May 23 2011 at 12:38 PM  
Hi All, I wanted to let you know that we have an updated version (1.1.2) available. This version contains several bug fixes based on your feedback and are detailed in the release notes. Thank you for using EWS Java API and for your feedback!

y0da22 wrote  May 23 2011 at 1:45 PM  
@prentice

Thank you very much. I will give that a shot and report back in the next couple of days.

y0da22 wrote  May 23 2011 at 4:18 PM  
@prentice

Ok I tried that and it is working well. It is not setting the time zone correctly.

The only thing is now, is that when I set the appt for 1:15pm, it shows up as 9:15 in the calendar.

Any ideas how to handle that? I know I can add 4 hours to the time, but maybe you know something else?

Thanks again

y0da22 wrote  May 23 2011 at 5:58 PM  
@prentice

Sorry, correction. It is setting the time zone correctly. The time is now the problem. I just tried again, so for example I set time 17:15 and it is creating as 13:15.

Any ideas?

prentice wrote  May 23 2011 at 6:33 PM  
@y0da22

Sounds like a timezone offset issue. You need to have your code use UTC as the timezone. I set it as default at the start of my code:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

y0da22 wrote  May 23 2011 at 7:51 PM  
@prentice

That worked perfectly!

Thank you so much.

rbaban wrote  May 24 2011 at 3:00 PM  
Hi, is there a version of EWS Java API that will work with java 1.5 ?

Thank you !

yongheeHan wrote  Jun 2 2011 at 2:31 AM  
Hi, everyone. I'm using this API on Exchange Server 2007 SP3.
I have difficult to create Appointment.
There are error message "StartTimeZone must be required".
How can define StartTimeZone? It is need to TimeZoneDefinition but I don't know How can define TimeZoneDefinition.
Please help me~

goggy wrote  Jun 7 2011 at 7:39 AM  
Hello!
I'm having problems reaching other mailboxes that i've got access to. I have no problem accessing my own Inbox folder, but I don't know, how to obtain mails from Inbox on the other two mailboxes. Can anyboy help me please. I've been trying for some time now, but with no success.
Thank you!

AnandMSFT wrote  Jun 17 2011 at 10:35 AM  
Hi All, I wanted to let you know that we have an updated version (1.1.3) available. This version contains several bug fixes based on your feedback and are detailed in the release notes. Thank you for using EWS Java API and for your feedback!

AnandMSFT wrote  Jun 17 2011 at 11:03 AM  
Hi Sawzeb,thanks for using ewsjava api. EWS SOAP API does not support creating a new mailbox. You need to use PowerShell to do that. Regarding user configuration , Please find the sample code to create user configuration.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.setTraceEnabled(true);
service.setUrl(<URL>);
ExchangeCredentials credentials = new WebCredentials(USERNAME,PASSWORD, DOMAIN);
service.setCredentials(credentials);
String name = "test configuration";
UserConfiguration config1 = new UserConfiguration(service);
byte[] data_value = new byte[4];
data_value[0] = 'd';
data_value[1] = 'a';
data_value[2] = 't';
data_value[3] = 'a';
//set binary data
config1.setBinaryData(data_value);
//set xml data
config1.setXmlData(data_value);
config1.save(name, WellKnownFolderName.Calendar);
UserConfiguration config = UserConfiguration.bind(service, name,
WellKnownFolderName.Calendar, UserConfigurationProperties.All);
//read binary data from user configuration
byte[] bData=config.getBinaryData();
System.out.print("config.getBinaryData() value :");
for(int i=0;i<bData.length;i++)
{
System.out.print((char)bData[i]);
}
System.out.println();
//read xml data from user configuration
byte[] xData=config.getXmlData();
System.out.print("config.getXmlData() value :");
for(int i=0;i<xData.length;i++)
{
System.out.print((char)xData[i]);
}

AnandMSFT wrote  Jun 17 2011 at 11:15 AM  
Hi Googy,Thanks for using EWS Java Api.To obtain the mails from other’s inbox, the permissions are to be checked first. Once the User gets the permissions to access other user’s mail box ,the mails from other user’s mail box can be retrieved using the folder id of the other user’s Inbox folder. Please find the sample code below and let us know if you are not successful.


ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.setTraceEnabled(true);
service.setUrl(<URL>);
ExchangeCredentials credentials = new WebCredentials(USERNAME,PASSWORD, DOMAIN);
service.setCredentials(credentials);
//folder id is the id of the other user’s inbox
FindItemsResults < Item > results = service.findItems( new FolderId("AAMkADRjZmViNzc5LWM2NTE
7TRPEQJzcSt6i9q+UAAAAu0+lAAA="), new ItemView( 100 ) );
Iterator itr = results.iterator();
while(itr.hasNext()){
EmailMessage em = (EmailMessage)itr.next();
System.out.println("Message Subject From other's Inbox"+em.getSubject());
}

buckett wrote  Jun 20 2011 at 9:09 PM  
I've wrapped this code up in a Maven project and stuck it up on github at:

https://github.com/buckett/ews-java

ewsuser wrote  Jun 28 2011 at 1:18 PM  
Hi All:
Is there a way to create a meeting with no "delete" options. I want the participants not able to delete from their calendar. Is this possible?
Thanks

techbrowser wrote  Jul 5 2011 at 4:24 PM  
Hi,
Is there a way to download attachments of an email using this API. I have tried below code without any success.

FolderId folderId = new FolderId(WellKnownFolderName.INBOX, "mailbox@example.com");
findResults = this.svc.findItems(folderId, view);

for(Item item : findResults.getItems()) {
if (item.getHasAttachments()) {
AttachmentCollection attachmentsCol = item.getAttachments();
System.out.println(attachmentsCol.getCount()); // This is printing zero all the time. My message has one attachment.
for (int i = 0; i < attachmentsCol.getCount(); i++) {
FileAttachment attachment = (FileAttachment)attachmentsCol.getPropertyAtIndex(i);
String name = attachment.getFileName();
int size = attachment.getContent().length;
}
}
}

FredW wrote  Jul 13 2011 at 4:54 PM  
The getCompleteName method on the Contact object always throws a ClassCastException - it is trying to cast a CompleteName object to a String. It can easily be fixed to return the complete name string by first casting the property to a CompleteName object and then getting the name as follows:

public String getCompleteName() throws ServiceLocalException {
CompleteName cn = (CompleteName) this.getPropertyBag().getObjectFromPropertyDefinition(
ContactSchema.CompleteName);
return (cn == null) ? null : cn.getFullName();
}

I have two questions:
1) Does the license agreement allow one to make changes to the source code, compile it and use it in an application?
2) Are any updates to the library planned that would fix this bug?

This library really made my task easier but to finish it properly I need to be able to access the Complete Name property.

Thanks.

AnandMSFT wrote  Jul 14 2011 at 8:02 AM  
Hi ewsuser , Thanks for using EWS Java API. For your query on "Is there a way to create a meeting with no "delete" options." , Unfortunately, this functionality is not supported using EWS SOAP API or EWS Java API. This is by design as a user has the freedom to make updates to their calendar as they desire – including deleting calendar items such as meetings.

linuxlewis wrote  Jul 18 2011 at 2:30 PM  
Does the 1.1.3 version of this API work with Exchange Server 2007? The release notes state that the 'EWS Java API can be used to access information on computers that are running Exchange Server 2010'.

Can you confirm this?

AnandMSFT wrote  Jul 22 2011 at 12:47 PM  
Hi All, I wanted to let you know that we have an updated version (1.1.4) available. This version contains several bug fixes based on your feedback and are detailed in the release notes. Thank you for using EWS Java API and for your feedback!

egeschwinde wrote  Jul 28 2011 at 11:08 AM  
Hi all - I need to get a Calender from the public folder - Is there a code sample available ? thanks

AnandMSFT wrote  Jul 29 2011 at 1:16 PM  
Hi FredW,Thanks for using EwsJavaAPI and reporting the issue. This issue is resolved in the release EwsJavaAPI 1.1.4. Please let us know if you are not successful.

eschreiber wrote  Jul 29 2011 at 11:31 PM  
Hi all,
I am wondering how to get properties such as the AssociatedAppointmentId and ResponseType from a MeetingResponse.I see the values listed in the xml in the trace but I can't determine how to get them from the object.

ItemView view = new ItemView (10);
FindItemsResults<Item> findResults = this.exchangeService.findItems(WellKnownFolderName.Inbox,view);
for(Item item : findResults.getItems()) {
if (item instanceof MeetingResponse) {
PropertySet propSet = new PropertySet(
BasePropertySet.FirstClassProperties,
MeetingMessageSchema.Sender,
MeetingMessageSchema.AssociatedAppointmentId, MeetingMessageSchema.ResponseType);
MeetingResponse resp = MeetingResponse.bind(this.exchangeService, item.getId(), propSet);
String sender = resp.getSender().getAddress();
System.out.println("sender: " + sender);
System.out.println("subject: " + resp.getSubject());
System.out.println("body:" + resp.getBody());
OutParam<Object> appointmentId = new OutParam<Object>();
resp.tryGetProperty(MeetingMessageSchema.AssociatedAppointmentId, appointmentId);
System.out.println("appointmentId: " + appointmentId.getParam());
}
}

gaelle wrote  Aug 2 2011 at 11:21 AM  
Hi all,
I am trying to use ews java api to get my exchange emails... but when I am running the following code I get this error:

microsoft.exchange.webservices.data.AutodiscoverLocalException: The Autodiscover service couldn't be located.
microsoft.exchange.webservices.data.ServiceRequestException: The request failed. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Code:
ExchangeService service = new ExchangeService();

ExchangeCredentials credentials = new WebCredentials("prova@domain.com",
"password");
service.setCredentials(credentials);


try {
service.autodiscoverUrl("prova@domain.com");
} catch (Exception e) {
e.printStackTrace();
try{
service.setUrl(new URI("https://server_url/"));
}catch (Exception e1) {
e1.printStackTrace();
}

}

Thanks!

JavaInsel wrote  Aug 5 2011 at 1:30 PM  
Hi all,
I am creating a Java Server-to-Server application, which sets holiday as Appointments on the exchange server. I want to set a holiday as an All-Day event:

appointment.setIsAllDayEvent(true);

but when i look at a test Outlook Account the Appointment is set from 2:00 till 2:00 next Day. This 2 hours are my Timezone Offset.

I think the ExchangeServer save the AlldayEvent from 00:00:00 UTC to 00:00:00 UTC next day.

Has someone ideas to set it right?

banks wrote  Aug 17 2011 at 1:54 PM  
Hi..This works great however I have one problem how can I save email message (.msg) to the hard drive. Dont see any such method available on an item or a message objects. There used to be SaveAs method but the current API seems to have have no such method available.

banks wrote  Aug 17 2011 at 8:14 PM  
Figured out the way to save the email to the harddrive it has to be saved in .eml format

String sFileName = "c:\\aa.eml";
oMessage.load(new PropertySet(ItemSchema.MimeContent));
MimeContent oMimeContent = oMessage.getMimeContent();
File oFile = new File(sFileName);
FileOutputStream oFOS = new FileOutputStream(oFile);
oFOS.write(oMimeContent.getContent(), 0, oMimeContent.getContent().length);

AnandMSFT wrote  Aug 24 2011 at 1:43 PM  
Hi egeschwinde,Thanks for using ewsjavaapi and reporting the issue. We are working on this issue and we’ll get back to you soon.

AnandMSFT wrote  Aug 24 2011 at 1:45 PM  
Hi eschreiber, Thanks for using ewsjavaapi reporting the issue. We are working on this issue and we’ll get back to you soon.

mweiss wrote  Aug 26 2011 at 6:27 AM  
Is it possible to send signed mails (provided with certificate) via EWS?

mweiss wrote  Aug 26 2011 at 6:32 AM  
NTLM V2 is not longer working since you implemented commons-httpclient!

Dennie wrote  Aug 27 2011 at 3:22 PM  
@TimeZoneDefintion problems; When I created a new appointment, I ran into similar problems, but discovered that the enumeration of TimeZoneDefinitions returned from the ExchangeService is a simple local Java TimeZone enumeration. This format is not compatible with the TimeZone format used by Exchange. Mark Matthews made a timezone conversion util to use http://www.java2s.com/Code/Java/Development-Class/Timezoneconversionroutines.htm, so passing in something like
appointment.setStartTimeZone(new TimeZoneDefinition(){{
setId("W. Europe Standard Time");
}}); works perfectly.

Kailas wrote  Aug 29 2011 at 2:35 PM  
How to assign task to other user using EWSJavaAPI_1.1.4?

Let me know if there is any alternative method.

Thanks, Kailas

natkot wrote  Aug 29 2011 at 9:17 PM  
Guys , we are using EWSJavaAPI_1.1.4, when trying to retrieve appointment with " " white spaces values it is crashed in EwsXmlReader.java with ServiceXmlDeserializationException , i believe there is a bug in read() and readValue() function when you checking characters.isIgnorableWhiteSpace() and characters.isWhiteSpace() - i guess logic should be if ignoreWhiteSpace= true && isWhiteSpace = true - continue . Can you please fix it for the next release? Currenly we will use local fix to overcome this issue. Please advise, thanks

AnandMSFT wrote  Sep 5 2011 at 5:14 AM  
Hi egeschwinde,Thank you for using ewsjavaapi.please find the steps for accessing calendar from public folder below:
1. Create exchange service object.
2. Create calendar item in public Folder - Using
"CalendarFolder folder = new CalendarFolder(service);
folder.setDisplayName ( "Test");
folder.save(WellKnownFolderName.PublicFoldersRoot);"
3.Get the folder id of the public calendar and bind the FolderId to CalendarFolder using
"CalendarFolder calendar = CalendarFolder.bind(service, <Folderid>);"
4.Create an Appointment in the public calendar and save the appointment using
"appointment.save(calendar.getId(), SendInvitationsMode.SendToNone);"
5.Check the appointment details created in the step 4, by passing folder id identified in step 3.

AnandMSFT wrote  Sep 5 2011 at 5:15 AM  
Hi Mweiss,Thanks for reporting the issue. We will review the issue you are seeing and get back to you. We have added your feature requests and suggestions to the list we evaluate for subsequent releases.

AnandMSFT wrote  Sep 5 2011 at 5:16 AM  
Hi Dennie,
Thanks for using EwsJavaAPI. We will review the issue and get back to you with updates.

AnandMSFT wrote  Sep 5 2011 at 5:17 AM  
Hi Kailas, Thanks for using EWS Java Api.To obtain the tasks from other user/assign task to other user , the permissions to the task folder are to be checked first. Once the User gets the permissions to access other user’s task folder ,the tasks from other user’s mail box can be retrieved using the folder id of the other user’s task folder.

AnandMSFT wrote  Sep 5 2011 at 5:17 AM  
Hi Natkot,
Thanks for using EwsJava API and reporting the issue.we are working this issue and we’ll fix this issue in subsequent release.

happypeppi wrote  Sep 5 2011 at 10:06 AM  
Hi,
How do i move an item to another Folder? i found the MoveItemRequest class, but the constructor needs an ErrorhandlingMode, which isn't public. Is there another way to do this? (EWSJavaAPI_1.1.4)

Kailas wrote  Sep 6 2011 at 5:19 AM  
Hi,

I am still facing TimeZoneDefintion problem, while creating new appointment

Error: The time zone definition is invalid or unsupported.

Code:

appointment.setStartTimeZone(new TimeZoneDefinition(){
{setId("Asia/Calcutta");}});

I have also tried setId("GMT+5.30"), setId("IST"), setId("UTC")

--Kailas

Kailas wrote  Sep 6 2011 at 11:10 AM  
Hi,
I am able to create new appointment by commenting-out lines 249, 250 and 256 in class Appointment.java. But time zone is UTC.
Thanks prentice.
--Kailas

Kailas wrote  Sep 6 2011 at 11:20 AM  
Hi AnandMSFT,
Please send me some sample code, how to assign task to other user using EWSJavaAPI_1.1.4.
--Kailas

Nalinkumar wrote  Sep 7 2011 at 11:55 AM  
Hi EwsJavaTeam,

I need to integrate the functionality of create calendar meeting and view meeting onto a portal.
For this requirement I have downloaded EWSJavaApi1.1.4 jar file. But I need help regarding the initial setup for starting this POC.
I have normal user credentials which I login through outlook. But here do we need any particular certificates or any other settings to be enabled for the users to get connected to MSExchange to create meetings through EWSJavaAPI?
Is this the URL (https://myexchangeserver/EWS/exchange.asmx) I need to pass to get the ExchangeService?
Using my email id I could not get the url through autodiscoverUrl method which is provided in the API.
Please I request you to provide initial setup to start a POC.
Thanks and Regards,
Nalinkumar

egeschwinde wrote  Sep 9 2011 at 11:48 AM  
HI
Thanks for the help before.
I have another problem.
I want to read the entries from the calender.
My problem is that when I have a series entry eg for each day from 2011-09-05 until 2011-09-16 from 3:00 to 4:00. I get one entry.
But I want to have the calendar entries split up exactly which one can see in the outlook calendara.
Is there a setting for this recurring appoinjtments to fetch it splitted up?
Regards Ewald Geschwinde

AnandMSFT wrote  Sep 14 2011 at 6:50 AM  
“Hi Natkot, thanks for reporting this issue. We tried this and we were unable to repro the issue . To continue the investigation, we will contact you in private to get more details.”

AnandMSFT wrote  Sep 16 2011 at 5:40 AM  
Hi happypeppi,
Thanks for using EwsJavaAPi.To move an item to another folder “move() “ API of Item class is used. Please find the sample code which moves an email message from “WellKnownFolderName.Drafts” to “WellKnownFolderName.Notes”.

Item item =new EmailMessage(service);
item.setSubject("testing move item to another folder");
item.setBody(MessageBody.getMessageBodyFromText("Item moved"));
item.setSensitivity(Sensitivity.Confidential);
item.save(new FolderId(WellKnownFolderName.Drafts));
Item item1 = Item.bind(service, item.getId());
item1.move(new FolderId(WellKnownFolderName.Notes));

AnandMSFT wrote  Sep 16 2011 at 5:51 AM  
Hi Kailas,
Thanks for using EwsJavaApi,we are working on this issue and we’ll get back to you soon with sample code.

AnandMSFT wrote  Sep 16 2011 at 5:51 AM  
Hi NalinKumar,
Thanks for downloading EwsJavaApi.Please refer to the documents “Compiling the EWS Java API” and “Getting started with EWS Java API” for more details on setup and sample code.Please let us know if you are not successful.

AnandMSFT wrote  Sep 16 2011 at 5:52 AM  
Hi Ewald,
Thanks for using EwsJavaApi. we are working on this issue and we’ll get back to you soon.

Nalinkumar wrote  Sep 19 2011 at 6:35 AM  
Hi Anand,
Thanks for your response. I was testing with the EWS url by giving the user credentials.
But it was giving NTLM authentication error. so can you help here to resolve the issue.

Thanks and Regards,
Nalin.

king_miriam wrote  Sep 19 2011 at 9:09 AM  
Is there a restriction to use the EWS Java API on a client application when trying to connect Exchange server 2010 that is installed on Windows 2008 R2?
I dont want to change the securiy configuration on the server manually.
Thanks.

BenLeeImp wrote  Sep 20 2011 at 9:57 PM  
I believe I have found a bug in the ExtendedPropertyDefinition isEqualTo static method. It appears vulnerable to quite a few NullPointerExceptions, as it assumes certain fields are populated. I discovered this bug while attempting to fetch the "Referred By" field on a contact vial the extended properties. ie:

PropertySet properties = new PropertySet(BasePropertySet.FirstClassProperties);
ExtendedPropertyDefinition referredByName = new ExtendedPropertyDefinition(0x3A47, MapiPropertyType.String);
properties.add(referredByName);

I have a fix working locally, as I now have the method checking for nulls before calling methods on any particular property of the two extended property definitions. It treats a null on both sides as equal. Not sure this is the completely correct way to do it, but it works for now, and I can get my field. I've included the new code below, if you want to incorporate it into the next build. Is there a bug tracker or some such thing I can post this to? We really would like to use this library at my company, but we are somewhat concerned over how "in the shadows" this seems to be.

protected static boolean isEqualTo(ExtendedPropertyDefinition extPropDef1,
ExtendedPropertyDefinition extPropDef2) {
return
(extPropDef1 == extPropDef2)
||
(
(Object)extPropDef1 != null
&&
(Object)extPropDef2 != null
&&
(
(extPropDef1.getId() == extPropDef2.getId())
||
(extPropDef1.getId() != null && extPropDef1.getId().equals(extPropDef2.getId()))
)
&&
extPropDef1.getMapiType() == extPropDef2.getMapiType()
&&
(
(extPropDef1.getTag() == extPropDef2.getTag())
||
(extPropDef1.getTag() != null && extPropDef1.getTag().equals(extPropDef2.getTag()))
)
&&
(
(extPropDef1.getName() == extPropDef2.getName())
||
(extPropDef1.getName() != null && extPropDef1.getName().equals(extPropDef2.getName()))
)
&&
extPropDef1.getPropertySet() == extPropDef2.getPropertySet()
&&
(
(extPropDef1.propertySetId == extPropDef2.propertySetId)
||
(extPropDef1.propertySetId != null && extPropDef1.propertySetId.equals(extPropDef2.propertySetId))
)
);
}

aadvani wrote  Sep 23 2011 at 12:11 PM  
I am not able to connect to my exchange server with the latest EWS API. Tried connecting via wsdl, asmx and auto discover.
WSDL way gives below error
org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected

autoDiscover gives below error
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect

This is my code:
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("myemail","mypassword");
service.setCredentials(credentials);
//URI uri = new URI("https://mycomp/ews/Services.wsdl");
//URI uri = new URI("https://mycomp/ews/exchange.asmx");
//service.setUrl(uri);
service.autodiscoverUrl("myemail");
EmailMessage msg= new EmailMessage(service);
msg.setSubject("Hello world!");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS Managed API."));
msg.getToRecipients().add("myemail@mycomp.com");
msg.sendAndSaveCopy();

Are there any settings on the Exchange Server that need to be done?

egeschwinde wrote  Sep 26 2011 at 12:54 PM  
Hi aadvani

I had the same problem you have to enter a version here
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
....

aadvani wrote  Sep 26 2011 at 1:48 PM  
Thanks egeschwinde, but this did not work either. I still get the same message.Is there some setting on the server or client that one needs to take care of, inaddition to parameterizing the ExchangeVersion?

aadvani wrote  Sep 27 2011 at 7:11 AM  
Is there a specific "authentication type" that one needs to have on their Exchange Server? For eg, will this work with only Basic Authentication on the Exchange Server.The api docs also suggest to Run Secpol.msc and choose 'Send LM & NTLM – use NTLMv2 session security if negotiated' option as LAN Manager Authentication Level.Any tips welcome. Microsoft, can I get some help please?

aadvani wrote  Sep 27 2011 at 8:06 AM  
Got it!! I was supplying email address instead of userId to WebCredentials.ALso,it only worked with asmx.

banks wrote  Oct 12 2011 at 6:57 PM  
Hi, I have been able to access emails from the Inbox folder using EWSJavaAPI in my dev environment however when I set it up on the server I get NullPointerException when it tries to bind to a folder. oExchangeService object is fine and not null.
Folder oInbox = Folder.bind(oExchangeService, WellKnownFolderName.Inbox);

All the required jars are available on the server
commons-codec-1.4.jar
commons-httpclient-3.1.jar
commons-logging-1.1.1.jar
jcifs-1.3.16.jar
stax-1.2.0.jar
EwsJavaApi.jar

Can someone tell if anything else needs to be setup on the server?

thanks.
HG

Abu wrote  Oct 13 2011 at 12:00 PM  
Hi,
I have written the basics of handling ews java api in java and sample programs in my blog.
Here is the link http://abuinjavafamily.blogspot.com/2011/10/java-exchange-connector-exchange-web.html

greg2406 wrote  Oct 13 2011 at 4:24 PM  
Hello,
We are using EWSJavaAPI with Exchange Server 2010.
We face an issue to set up All Day Event. It seems that event is created at Exchange server at 00:00 AM - 00:00 AM (next day) based on UTC timezone, but when we review this item on Outlook, the event is span over two days with shift of 4 hours 08:00PM (previous day)-08:00pm(today)
We are located at America/Eastern timezone.
Tried to set startTimeZone - does not help.
Please advise. Thanks

Ybuche wrote  Oct 13 2011 at 7:21 PM  
Sorry for my english, not my first language...

----

I got similar problem than greg2406. All returned start date of an Appointment are wrong.

We are also located in America/Eastern timezone.

Considering this trace fragment (setTraceEnabled(true)) :
<Trace Tag="EwsRequestHttpHeaders" Tid="1" Time="2011-10-13 19:00:14Z">&#13;
POST /ews/exchange.asmx HTTP/1.1
Connection : Keep-Alive
User-Agent : ExchangeServicesClient/0.0.0.0
Accept-Encoding : gzip,deflate
Keep-Alive : 300
Content-type : text/xml; charset=utf-8
Accept : text/xml

Take a look at the time (2011-10-13 19:00:14Z)... But when i ran the test, it was 15:00 on my local machine.
So i guessed it was a TimeZone issue. Then i tried different TimeZone initializations of ExchangeService like :
ExchangeService lServiceExchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1, TimeZone.getDefault());
ExchangeService lServiceExchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1, TimeZone.getTimeZone("GMT-5"));
ExchangeService lServiceExchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1, TimeZone.getTimeZone("GMT-5:00"));

Whatever the Timezone i set, the result is the same : 4 hours are added to my local time. Looks like the API always use the defaut GMT time...

Hope someone has the answer !

Thanks.

Ybuche wrote  Oct 14 2011 at 2:07 PM  
I looked in source code and i found that the time in trace is because the API is using getTimeZone("UTC"). It's not coming from Exchange Server...

But i'm still facing the problem with the appointment dates... My doubts are that the TimeZone parameter of ExchangeService is not working at all.

Does anybody, especially the API developpers, have a clue ? I'm sure someone faced the same problem and found a solution...

Thanks in advance !

Ybuche wrote  Oct 17 2011 at 1:25 PM  
I use resolveName method to find the nickname of a user in ActiveDirectory. All i need is to get the contact nickname. The problem is that the nickname property of the contact is always null and i dont know why... In outlook, i can see the the nickname...

The code :
NameResolutionCollection lNameResolutionCollection = exchangeService.resolveName(
"name of contact", ResolveNameSearchLocation.DirectoryOnly, true);

Returns 1 contact.

lNameResolutionCollection.iterator().next().getContact().getNickName() is null
lNameResolutionCollection.iterator().next().getContact().getSurname() is not null

I need to know if i'm wrong with it or if it is a bug.

Thanks !

banks wrote  Oct 19 2011 at 9:37 PM  
Hi,

I keep getting java.lang.NullPointerException when trying to use SearchFilter in FindItemResults. After putting some debug I found out that propertyDefination in SearchFilter:ContainsSubstring method is being set as null. I am doing exactly as mentioned in the EWS Java API document. Any ideas?

It works fine when I debug the code on my machine the probelm is when I place the API jar on the server. Another difference is I had to build EWSJavaAPI using Java 1.5 complier instead of 1.6

ItemView oView = new ItemView(20); //new ItemView(iCount);
oView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
oView.setPropertySet(new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject,
ItemSchema.DateTimeReceived));

SearchFilter oSearchFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "JJJ");
FindItemsResults<Item> oFindResults = oExchangeService.findItems(WellKnownFolderName.Inbox,
oSearchFilter, oView);

paulnibin wrote  Oct 20 2011 at 11:45 AM  
Please check the forum post.

http://social.technet.microsoft.com/Forums/en-US/exchangesvrdevelopment/thread/303916f3-fb57-425a-9eba-55417c43c84a

This is about the ParseException when getting all the tasks from the server. Has any one come across this issue?

I have added the code to reproduce the issue also.

Thanks,
Paul

Ybuche wrote  Oct 21 2011 at 1:46 PM  
Is there a better place to post questions about this API ? Nobody is answering and a new version has come few weeks ago.

Anyway.

I found something interesting about my problem with dates (see post Oct. 14).

An mentionned in a doc file coming with the API :

Date & TimeZone
java.util.Date class where ever is being used as an input for any of the methods in this API must be considered as UTC time.

Time or the date details which are set to java.util.Date class is considered to be given as UTC. So when ever data is set to Date class make sure that it is in a UTC time.
For example: Lets us consider creating an Appointment from 10:00 am to 11:00 am on 20-09-2010 as per IST Indian Standard Time(which is +5:30 hours from UTC). So as per the format mentioned Time should be given in UTC as shown below.


Appointment appointment = new Appointment(service);
appointment.setSubject("Appointment TEST for TimeZone Check");
appointment.setBody(MessageBody.getMessageBodyFromText("Test Body Msg"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = formatter.parse("2012-09-20 04:30:00");
Date endDate = formatter.parse("2012-09-20 05:30:00");
appointment.setStart(startDate);
appointment.setEnd(endDate);
appointment.save();

------
The above is when we create an item. But if i want to read it, i guess i have to do the same kind of conversion. In my case (i live in Québec, Canada), i have to substract 5 hours to the date returned by the API. I dont like it but this is the way the API works.

This said, i suggest to remove (or make it work) the TimeZone parameter of the ExchangeService constructor.

Thanks !

greg2406 wrote  Oct 21 2011 at 4:09 PM  
Hi Ybuche,
Your approach is good for "regular" appointments, but still any time manipulation does not help in case of All Day Event item.
It seems that API ignores time sent and always creates ADE item with 00:00-00:00 time in UTC timezone, therefore when you look at this ADE through outlook in your timezone, it is shifted and usually appears in more than one day banner.
We could not find any workaround and I don't see that we get any response from MS team, which is very frustrating

Thanks

Ybuche wrote  Oct 21 2011 at 5:15 PM  
Hi greg,

I'm happy to see that at least someone answer the bell here !

Yup this is frustrating. But i didn't expect much from Microsoft. Free stuff, open source. Not the kind of Microsoft. Probably not a priority for them to support this API.

I can see that your problem is more complicated than mine.

Have you tried to do like the example above ? I mean that if you want to set the event from Today 10 AM to tomorrow 4 PM you should substract 4 hours to Start and End date.
See the code i would like to try if i were you :

today is 2011-10-21 :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = formatter.parse("2011-10-21 05:00:00");
Date endDate = formatter.parse("2011-10-21 11:00:00");

But i think the base of the problem here is because the TimeZone parameter of ExchangeService is not working at all. Not as mentionned in the documentation... Maybe it will be fixed in the next version of the API ?

Hope this will help you ;)

myasic wrote  Nov 8 2011 at 10:16 AM  
Hi all,

Is there any way to mock ews request for unit test ?

Thanks

myasic wrote  Nov 8 2011 at 12:40 PM  
An other question : is it plan to change to commons-httpclient 4 ?

brus wrote  Dec 7 2011 at 10:05 PM  
I had to change the source code in order to make it work:

File: EwsXmlReader.java
line 111:

if ((!this.getLocalName().equals(localName)) ||
(this.getNamespaceUri() != EwsUtilities
.getNamespaceUri(xmlNamespace))) {

replace with:


if ((!this.getLocalName().equals(localName)) ||
!this.getNamespaceUri().equals(EwsUtilities
.getNamespaceUri(xmlNamespace))) {

line: 718:


&& ((this.getNamespacePrefix() == EwsUtilities
.getNamespacePrefix(xmlNamespace)) || (this
.getNamespaceUri() == EwsUtilities
.getNamespaceUri(xmlNamespace)));

replace with:


&& (this.getNamespacePrefix().equals(EwsUtilities
.getNamespacePrefix(xmlNamespace)) || this
.getNamespaceUri().equals(EwsUtilities
.getNamespaceUri(xmlNamespace)));

haidd106 wrote  Dec 13 2011 at 3:16 AM  

Release problems when setting timezone for appointment. My solution is modified source code of ESWJava and built it again
In TimeZoneDefinition.java file, i added
private Item parent;


protected Item getParent(){
return this.parent;
}

protected void setParent(Item _item){
this.parent = _item;
}
Add
if(getParent() instanceof Appointment)return;
in the first line of validate() method
Build EWSJava againt. Each one get a new TimeZoneDefinition

TimeZoneDefinition rtn = null;
rtn = new TimeZoneDefinition() {
{
setId("GMT");
setName("UTC Standard Time");
setParent(app);
}
};
:D. It's ok

jbourey wrote  Dec 14 2011 at 12:24 AM  
Could the EWS jar be added to the central Maven repository? Having this library available there would greatly improve our ability to use the library in our projects. While we could of course manually add this jar to a custom repository, our projects are currently heavily discouraged from doing so.

riverg wrote  Dec 16 2011 at 7:04 AM  
hi
there is appear a problem i using outlook sent an email .the body content following
??
????????????......
????
2011?12?5?
then i using the "HttpMethodBase.getResponseBodyAsStream" method reecived this email. the email body'content is following:
??
????????????......
????
2011?12?5?
2011?12?5? style="" /span>
why i get the emails'conten is wrong.?




riverg wrote  Dec 16 2011 at 7:07 AM  
hi
there is appear a problem i using outlook sent an email .the body content following
hi
this is email's body
2011.12.5(sign date)
then i using the "HttpMethodBase.getResponseBodyAsStream" method reecived this email. but the email body'content is following:
hi
this is email's body.
2011.12.5.(sign date)
2011.12.5. style="" /span> (sign date repeate)
why i get the emails'conten is wrong.?

riverg wrote  Dec 16 2011 at 7:09 AM  
the email's body appered two sign date

riverg wrote  Dec 17 2011 at 12:20 PM  
who can help me ?

Hstive wrote  Dec 23 2011 at 12:43 PM  
final Appointment appointment = new Appointment(service);
appointment.setSubject("Terminnnn!!!!!");
appointment.setBody(MessageBody.getMessageBodyFromText("Superrrrrr!!!!!! "));

DateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");

Date startDate = formatter.parse("2011-12-23 10:30:00");
Date endDate = formatter.parse("2011-12-23 12:30:00");

appointment.setStartTimeZone( new TimeZoneDefinition() {
{
setId("GMT");
setName("UTC Standard Time");
setParent(appointment);


}});

appointment.setStart(startDate);
appointment.setEnd(endDate);

appointment.save();

but he give me an error ( The time zone definition is invalid or unsupported.)
can someone help me please !

haidd106 wrote  Dec 29 2011 at 9:12 AM  
Hi Hstive!
Are you sure to modify TimeZoneDefinition.java file with add
private Item parent;


protected Item getParent(){
return this.parent;
}

protected void setParent(Item _item){
this.parent = _item;
}

ShaunPowell wrote  Jan 11 2012 at 5:04 PM  
I'm having an issue getting recurrence appointment data and I've found a technet forum post with no solution (http://social.technet.microsoft.com/Forums/nl-NL/exchangesvrdevelopment/thread/c6f60e25-a604-48b4-a0a7-65c691b8f40b). It looks like the "StartDate" value for the Recurrence>NoEndRecurrence xml node is being returned as an invalid date (2012-01-10-05:00). I am getting the following error: The request failed. Unparseable date: "2012-01-10-05:00".

It is returning just the date value but appends the TZ offset (-05:00) value to the end with no time value. I would think either removing the -5:00 time zone information completely or adding 0 based time "2012-01-10T00:00:00-05:00" would correct this but this has to do with how Exchange is returning the data, not how the EWS API is parsing the date I believe but not sure how to get past this.

From my EWS trace:

<t:Recurrence>
<t:WeeklyRecurrence>
<t:Interval>1</t:Interval>
<t:DaysOfWeek>Monday Tuesday Wednesday Thursday Friday</t:DaysOfWeek>
<t:FirstDayOfWeek>Sunday</t:FirstDayOfWeek>
</t:WeeklyRecurrence>
<t:NoEndRecurrence>
<t:StartDate>2012-01-10-05:00</t:StartDate>
</t:NoEndRecurrence>
</t:Recurrence>

LucaVix wrote  Jan 12 2012 at 1:48 PM  
The weird behavior about time zones is due to a problem in EwsUtilities.java, 'Z' that means UTC is appended to the date ignoring which is the real TimeZone. Here the patch to EwsUtilities.java:

35a36,49
> private static DateFormat utcDateTimeFormatter;
> static {
> utcDateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
> utcDateTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
> }
>
>
>
> private static DateFormat utcDateFormatter;
> static {
> utcDateFormatter = new SimpleDateFormat("yyyy-MM-dd'Z'");
> utcDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
> }
>
448,451c462,464
< Date d = new Date();
< DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
< df.setTimeZone(TimeZone.getTimeZone("UTC"));
< String formattedString = df.format(d);
---
> Date d = new Date();
> String formattedString = utcDateTimeFormatter.format(d);
>
706,707c719
< DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
< return (T) df.parse(value);
---
> return (T) utcDateTimeFormatter.parse(value);
801,803c813
< String format = "yyyy-MM-dd'Z'";
< DateFormat utcFormatter = new SimpleDateFormat(format);
< return utcFormatter.format(date);
---
> return utcDateFormatter.format(date);
814,816c824
< String format = "yyyy-MM-dd'T'HH:mm:ss'Z'";
< DateFormat utcFormatter = new SimpleDateFormat(format);
< return utcFormatter.format(date);
---
> return utcDateTimeFormatter.format(date);

docbrownboy wrote  Jan 12 2012 at 11:38 PM  
I am still having issues with the appointment.setIsAllDayEvent(true); It sets the Time to 4PM which is Midnight - TimeZone offset. It ignores the time all together when you use setIsAllDayEvent method. When you open up Outlook the All Day Event Flag is not set. Any ideas on how to fix this? I have read through all the previous posts and none of them fixed this issue.

docbrownboy wrote  Jan 13 2012 at 12:03 AM  
Is there a way to create categories using EWS

ulfbeh wrote  Jan 20 2012 at 12:52 AM  
hey guys!

first of all: THANK YOU!

really, i appreciate your effort and the API has been really helpful for me, so far.

what bothers me is the fact, that somehow i'm not able to set exceptions to recurrences.
is that a bug or a feature?! :D

thanks in an advance for the answer!

raulagrait wrote  Feb 8 2012 at 11:28 PM  
I am having issues integrating the EWS Java API into an Android application. I suspect that this is because the dependency of HttpClient 3.1 conflicts with Android's usage of HttpClient 4.0. An update to the library to be Android compliant would be great. I've outlined my problem in more detail here: http://stackoverflow.com/questions/9203073/problems-using-the-ews-java-api-on-android

tigre wrote  Feb 17 2012 at 8:49 AM  
With EWS Java API 1.1.5 I can delete phone numbers but can not delete email addresses from a contact by using the following code:
ItemId id = ItemId.getItemIdFromString(itemId);
Iterator<GetItemResponse> i = service.bindToItems(Collections.singletonList(id), PropertySet.FirstClassProperties).iterator();
if (i.hasNext()) {
Contact contact = (Contact) i.next().getItem();
contact.getEmailAddresses().setEmailAddress(EmailAddressKey.EmailAddress1, null);
contact.update(ConflictResolutionMode.AlwaysOverwrite);
}
Does anyone have a solution for this problem?

Cherian_85 wrote  Mar 2 2012 at 1:25 PM  
Hi

I tried using the API to connect to a trial exchange account provided by microsoft. I was able to read the mail and delete it using my java code. For the same code i tried the URL and credentials for the exchange server setup on client machine. But getting null pointer exception when the code tries to read the inbox. We checked the logs and found that the code is not even hitting the target server. Wehn we used http instead of https, the code hit the server but threw the "Not authorized" exception.Even tried the autodiscover code and that too returns the same

Paralallely, we generated jax-ws classes from the wsdl and used that to connect to the client machine. It succesfully connected and read the mail subjects..

Can someone please suggest what is the issue with the API jar? Below is the code i used




public static void main(String args[])
{
try
{
setSSLConfig();
Authenticator.setDefault(new RetrieveWSDLAuthenticator("domain\\uid", "pwd"));

new InboxSummaryExample().testGetMail();
}
catch (Exception e)
{
System.out.println(e);
}
}

public void testGetMail() throws Exception
{

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
URI url = new URI("https://10.12.12.37/ews/Exchange.asmx");
service.setUrl(url);
service.setCredentials(new WebCredentials("uid@domainmail.com", "pwd", "domain"));
System.out.println("Created ExchangeService");
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
ItemView view = new ItemView(50);
FindItemsResults<Item> findResults;
int i = 0;
do
{
findResults = service.findItems(WellKnownFolderName.Inbox, view);
int cntr = 1;
for (Item item : findResults.getItems())
{
System.out.println("Subject of emails in inbox (" + cntr + " ) " + item.getSubject());
item.move(WellKnownFolderName.DeletedItems);
System.out.println("Email moved to deleted items folder");
System.out.println("------------------------");
cntr++;
i++;
}
view.setOffset(view.getOffset() + 50);
}
while (findResults.isMoreAvailable());
if (i == 0)
{
System.out.println("no emails in inbox");
}
}

static class RetrieveWSDLAuthenticator extends Authenticator
{
private String username, password;

public RetrieveWSDLAuthenticator(String user, String pass)
{
username = user;
password = pass;
}

@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password.toCharArray());
}
}

// The trust all certs.
private static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager()
{

public void checkClientTrusted(X509Certificate[] arg0, String arg1)
{
// TODO Auto-generated method stub

}

public void checkServerTrusted(X509Certificate[] arg0, String arg1)
{
// TODO Auto-generated method stub

}

public X509Certificate[] getAcceptedIssuers()
{
// TODO Auto-generated method stub
return null;
}

} };

// Java Secure Socket Connection
private static HostnameVerifier hv = new HostnameVerifier()
{

public boolean verify(String hostname, SSLSession session)
{
// TODO Auto-generated method stub
return false;
}
};

// Sets the ssl config.
private static void setSSLConfig() throws Exception
{
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

al_shopov wrote  Mar 5 2012 at 1:44 PM  
Hello,

I am having issue with EWSAPI latest version (1.1.5). Since I have read all the comments in the thread -
my problem is similar if not same to the problems outlined above. Since I am proposing a fix for
my situation, I am adding my comment.

There is an issue with parsing dates of Recurrence Master Events when one adds AppointmentSchema.Recurrence
to the property set in the call: Appointment.bindToRecurringMaster(eService, itemId, ps);
This stems from a bug in the following method:

protected Date convertStartDateToUnspecifiedDateTime(String value)
throws ParseException {
if (value == null || value.isEmpty()) {
return null;
} else {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'Z'");
- return df.parse(value);
}
}

The method is in the class microsoft.exchange.webservices.data.ExchangeServiceBase
That method is inherited by microsoft.exchange.webservices.data.ExchangeService which gets used

The main problem is that the Exchange servers returns Strings in the format:
"2012-02-15+06:00"; The part after the '+' is dependent on the time zone of the Exchange server we query.

The parse string: "yyyy-MM-dd'Z'" does not correspond to what we get from server
1st: The quoted 'Z' means it is a literal and not a timezone place holder
2nd: Even if we unquote it - timezone representations in Java have no ":" in them.


A simple patch for the problem is using the follwoing code:

protected Date convertStartDateToUnspecifiedDateTime(String value)
throws ParseException {
if (value == null || value.isEmpty()) {
return null;
} else {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.parse(value.substring(0, 10));
}
}

Please note that Microsoft's licence does not allow changing their libray and
thus you should check whether patching like this is allowed.

Still I am providing the patch freely (Public Domain) to be used by everybody
(and anyway - it is way too trivial to be really copyrightable).

As final words:

May I point that the single String argument constructor of SimpleDateFormat uses
the system time zone which is definately not optimal. Please use
public SimpleDateFormat(String pattern, Locale locale)

And really - I kindly urge that Microsoft publish the library under a more permissive
and dare I say even Open Source license (Apache/MIT will be fantastic, but even
Microsoft's own Public License and Reciprocal License will be equally great).
This will definately foster cooperation and wider reach of Exchange server.
Kind regards:
al_shopov

MatthewD wrote  Mar 6 2012 at 12:27 PM  
Hello,

Is there any way to share a calendar using this API? I've been looking for such option for 3 days by now,
and inspected all calendar related classes ;( can anyone help out?

MatthewD wrote  Mar 29 2012 at 10:43 AM  
Also, can anyone provide me with some working example on how to override the urlvalidate method of autodiscover? I've tried every approach i could have think of, even the one suggested in "Getting started..." doc didn't work out.

static boolean ValidateRedirectionUrlCallback(String redirectionUrl)
{
// The default for the validation callback is to reject the URL.
boolean result = false;

try{
URI redirectionUri = new URI(redirectionUrl);
if (redirectionUri.getScheme() == "https")
{
result = true;
}
}catch(URISyntaxException e){e.printStackTrace(); }
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
return result;
}

eservice = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
eservice.setCredentials(credentials);
try
{
// URI url = new URI( adres );
eservice.autodiscoverUrl(login, ValidateRedirectionUrlCallback);
// eservice.setUrl( url );

}catch(Exception e){System.out.println("Something didnt work out..");
e.printStackTrace();
};

bobmanc wrote  Mar 29 2012 at 2:04 PM  
I too am getting "The request failed. An element node 'soap:Envelope' of the type START_ELEMENT was expected, but node 'head' of type START_ELEMENT was found."

Just trying what is in the Getting Started doc.


ExchangeService service = new ExchangeService();
service.setUrl(new URI(url));
ExchangeCredentials credentials = new WebCredentials(username, password);
service.setCredentials(credentials);
EmailMessage msg = new EmailMessage(service);
msg.setSubject("Hello world!");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS Managed API."));
msg.getToRecipients().add("bobmanc@example.com");
msg.send();

MatthewD wrote  Mar 30 2012 at 1:43 PM  
Okay,

Here is a tip for anyone that may have problem with defining autodiscover:

public class AutoRule implements IAutodiscoverRedirectionUrl {

@Override
public boolean autodiscoverRedirectionUrlValidationCallback(String string) throws AutodiscoverLocalException{
boolean result = false;

try{
URI redirectionUri = new URI(string);
if (redirectionUri.getScheme().contains("https"))
{
result = true;

}
}catch(URISyntaxException e){e.printStackTrace(); }
System.out.println(result);
System.out.println(string);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
return result;
};

And then in your main code it would look something like this:
eservice = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
eservice.setCredentials(credentials);
try
{
// URI url = new URI( adres );
AutoRule valid = new AutoRule();
eservice.autodiscoverUrl(login , valid);
// eservice.setUrl( url );
}catch(Exception e){System.out.println("Something didnt work out..");
e.printStackTrace();
};

Hope that would help in future ;)

Baz1nga wrote  Apr 4 2012 at 2:38 PM  
When I call ExchangeService.getDelegates() methods it returns 'None' for all permissions, but there are permissions for that user.
The methods addDelegates(), updateDelegates(), removeDelegates() work fine. Is it a bug? Im using Exchange Server 2007 and Ews Java Api 1.1.5.
Thanks in advance

mitchlindsay wrote  Apr 5 2012 at 6:56 PM  
I just want to call out that if you run into the "The specified server version is invalid" error, the fix is to specify the right version of Exchange to connect too.
val service = new ExchangeService(ExchangeVersion.Exchange2007_SP1)
And it appears that this sets your compatibility level so you can call against other versions (Exchange 2010, Exchange 2010 SP1) but new features are not available.

lannt2710 wrote  Apr 20 2012 at 9:03 AM  
Now, I have a problem when i try to getFirstOccurrence() of a RecurringAppointment.

Source:

FindItemsResults<Appointment> findResults = cf.findAppointments(new CalendarView(startDate, endDate));
PropertySet ps = new PropertySet();
ps.add(AppointmentSchema.FirstOccurrence);
service.loadPropertiesForItems(findResults, ps.FirstClassProperties);
for (Appointment appt : findResults.getItems())
{
if (appt.getIsRecurring()){
System.out.println("getFirstOccurrence:" + appt.getFirstOccurrence().getItemId());
}

Error: java.lang.NullPointerException
at ExchangeServerTest.getOriginalAppointment(ExchangeServerTest.java:439)
at ExchangeServerTest.main(ExchangeServerTest.java:470)


#### Please help me !!!!

lannt2710 wrote  Apr 23 2012 at 5:45 AM  
I created an recurring appointment using outlook(2007 SP1).

Then I try to get the FirstOccurrence but not work. alway return null.

------------------------------------------------------------------------------------------------------

Source:

CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
FindItemsResults<Appointment> findResults = cf.findAppointments(new CalendarView(startDate, endDate));
PropertySet ps = new PropertySet();
ps.add(AppointmentSchema.FirstOccurrence);
service.loadPropertiesForItems(findResults, ps);
for (Appointment appt : findResults.getItems())
{
if (appt.getIsRecurring()){
System.out.println("getFirstOccurrence:" + appt.getFirstOccurrence());
}
}

And this is the result:

getFirstOccurrence:null

-----------------------------------------------------------------------------------------------------

How to get ID of the FirstOccurrence of a recurring appointment ????

truezjz wrote  May 15 2012 at 5:01 PM  
Hi Guys,

I'm using the java EWS API, get mimecontent from Office 365, I'm getting these error for some messages, any suggestions will be highly appreciated:

The request failed. Illegal character entity: expansion character (code 0xb) not
a valid XML character
at [row,col {unknown-source}]: [179,364]
microsoft.exchange.webservices.data.ServiceRequestException: The request failed.
Illegal character entity: expansion character (code 0xb) not a valid XML charac
ter
at [row,col {unknown-source}]: [179,364]
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internal
Execute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execu
te(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.internalBindToIte
ms(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.bindToItem(Unknow
n Source)
at microsoft.exchange.webservices.data.ExchangeService.bindToItem(Unknow
n Source)
at microsoft.exchange.webservices.data.EmailMessage.bind(Unknown Source)

at microsoft.exchange.webservices.data.EmailMessage.bind(Unknown Source)

at test.EWSTest.getMessagesFromInbox(EWSTest.java:1636)
at test.EWSTest.main(EWSTest.java:1718)
Caused by: com.ctc.wstx.exc.WstxParsingException: Illegal character entity: expa
nsion character (code 0xb) not a valid XML character
at [row,col {unknown-source}]: [179,364]
at com.ctc.wstx.sr.StreamScanner.constructWfcException(StreamScanner.jav
a:605)
at com.ctc.wstx.sr.StreamScanner.throwParseError(StreamScanner.java:461)

at com.ctc.wstx.sr.StreamScanner.reportIllegalChar(StreamScanner.java:23
75)
at com.ctc.wstx.sr.StreamScanner.checkAndExpandChar(StreamScanner.java:2
321)
at com.ctc.wstx.sr.StreamScanner.resolveSimpleEntity(StreamScanner.java:
1180)
at com.ctc.wstx.sr.BasicStreamReader.readTextSecondary(BasicStreamReader
.java:4675)
at com.ctc.wstx.sr.BasicStreamReader.readCoalescedText(BasicStreamReader
.java:4124)
at com.ctc.wstx.sr.BasicStreamReader.finishToken(BasicStreamReader.java:
3699)
at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1023)
at com.ctc.wstx.evt.WstxEventReader.peek(WstxEventReader.java:306)
at microsoft.exchange.webservices.data.EwsXmlReader.isEmptyElement(Unkno
wn Source)
at microsoft.exchange.webservices.data.ComplexPropertyDefinitionBase.loa
dPropertyValueFromXml(Unknown Source)
at microsoft.exchange.webservices.data.PropertyBag.loadFromXml(Unknown S
ource)
at microsoft.exchange.webservices.data.ServiceObject.loadFromXml(Unknown
Source)
at microsoft.exchange.webservices.data.EwsServiceXmlReader.readServiceOb
jectsCollectionFromXml(Unknown Source)
at microsoft.exchange.webservices.data.GetItemResponse.readElementsFromX
ml(Unknown Source)
at microsoft.exchange.webservices.data.ServiceResponse.loadFromXml(Unkno
wn Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.parse
Response(Unknown Source)
at microsoft.exchange.webservices.data.ServiceRequestBase.readResponse(U
nknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.readResp
onse(Unknown Source)
... 9 more

James

BerndGreiner wrote  May 16 2012 at 6:21 AM  
Hi.
I'm using EWSJavaAPI_1.1.5 and get always 401 Unauthorized.
We have Exchange 2010 SP1 with loadbalancer and four server CAS-role.
The username and password are correct.
We can request the wsdl definition with "https://SERVER/ews/exchange.asmx" where SERVER is the loadbalancer or one of the server with CAS-Role.
We are using ony Windows Authentication - Basic Authentication is diabled.
My test program looks like:
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(
user,
pwd,
domain);

service.setCredentials(credentials);
service.setUrl(new URI(url));

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = formatter.parse("2012-05-01 12:00:00");
Date endDate = formatter.parse("2012-05-30 13:00:00");
CalendarFolder cf=CalendarFolder.bind(service, WellKnownFolderName.Calendar);
FindItemsResults<Appointment> findResults = cf.findAppointments(new CalendarView(startDate, endDate));
for (Appointment appt : findResults.getItems()) {
System.out.println("ID====="+appt.getId().getUniqueId());
System.out.println("SUBJECT====="+appt.getSubject());
System.out.println("START====="+appt.getStart().toString());
System.out.println("END====="+appt.getEnd().toString());
System.out.println();
}

Has anybody an idea?
I would be very grateful for any help

kumarjit wrote  Jun 13 2012 at 1:26 PM  
Hi,

Greetings of the day.

I am very new to JAVA and Exchange Web Services. I need to use client certificate for authentication in exchange server using ClientCertificateCredentials class. But I am not able to understand how to implement it. I have tried with the following code:

public static TrustManager getTrustManager () {

try {
File f = new File("ctest.pfx");
FileInputStream is = new FileInputStream(f);
KeyStore ks = KeyStore.getInstance("PKCS12");
String p = "password";
ks.load(is, p.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
return tms[0];
} catch (Exception ex) {
ex.printStackTrace();
return null;
}

}

And then initializing it like:

ClientCertificateCredentials credentials = new ClientCertificateCredentials(TMImpl.getTrustManager());

But everytime it throws an error:

NTLM authentication scheme selected
No credentials available for NTLM @MyIP:MyPort

When I tried logging in from browser it asks me for a certificate and allows me to access the mailbox.

Can you please help me understanding what I am doing wrong here. I would appreciate if you can send me a code sample for the above.

Thanks in Advance,
Kumarjit

jairamrb wrote  Jun 15 2012 at 1:10 PM  
Hi.
I'm using EWSJavaAPI_1.1.5 and I have Exchange 2010 SP1. When i call the method "ExchangeService.getRoomLists()" always returns zero elements and this is false. Example:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
service.setTraceEnabled(true);
WebCredentials webCredentials = new WebCredentials(username, password, dominio);
URI url = new URI(host);
service.setCredentials(webCredentials);
service.setUrl(url);

EmailAddressCollection myRoomLists = service.getRoomLists();
System.out.println(" - myRoomLists: " + myRoomLists.getCount());

Does anyone have a solution for this problem?

Regards.

nestoru wrote  Jun 29 2012 at 7:05 PM  
Hello MS team,

Thanks again for this API. I had several problems trying to compile version 1.1.5 but I have created a Plain Old Bash recipe ( http://thinkinginsoftware.blogspot.com/2012/06/microsoft-ews-managed-java-api.html ) to build the project from command line. It automatically downloads dependencies, adject the build.xml file to account for the classpath lib inclusion, builds the jar and renames it using the proper version. I would recommend incorporating those corrections in the original package.

Finally I would like to recommend to put this project in github or any other public versioned repository including perhaps its mavenization like others have proposed already.

Thanks again,
-Nestor

StefanLindner wrote  Jul 6 2012 at 5:31 PM  
Is it possible to create an Appointment that is not a meeting?

1. I create an Appointment with Outlook (in another calendar that is shared to me)
2. I create an Appointment in that other calendar with this API
3. I fetch both Appointmens with this API through a query.

Appointment1 is NOT a meeting
Appointment2 IS a meeting

There is no way to set the property "AppointmentSchema.IsMeeting" becaus the propertyBag is private and even the PropertyBag class is a local class. So it is impossible to extend the Appointment class and set this property.

StefanLindner wrote  Jul 6 2012 at 5:32 PM  
Is this API still supported and will there be new releases in the near future?

StefanLindner wrote  Jul 6 2012 at 6:52 PM  
I found a solution by modifying the API code an recompile the API. But this is not what I want to do when I use this API. Is there a chance to hav my patch integrated into source?

bernal wrote  Jul 17 2012 at 11:05 AM  
There is a problem of memory comsumption, related with a bad implementation of the commons-http-client.

In the class HttpWebRequest, there are two calls to the static method AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, EwsJCIFSNTLMScheme.class); in every connection, this method puts values into a static hashmap, this is not a problem because it inserts always in the same three id's, and insert values into a list that causes a memory leak, after two weeks the server has a list that takes 700mb.

One method to solve this problem is by adding this code to the class:

static{
Protocol.registerProtocol("https",
new Protocol("https", new EwsSSLProtocolSocketFactory(), 443));
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, EwsJCIFSNTLMScheme.class);
}

And delete the lines 84,85,86,87 and 143,144,145,146.

With this change, the configuration methods of the http-commons-client will be called just one time, on the class instantiation.

Best regards!

MickeyMSDN wrote  Jul 23 2012 at 5:27 AM  

Looking for Android API to work with Exchange 2007/2010 and found one from Independentsoft http://www.independentsoft.de

Do you have also build for Android or is it possible to build one from the source code?


Thanks
- Mickey

atlauren wrote  Aug 20 2012 at 7:27 PM  
Is this Java/EWS API project still alive? It's been nearly a year since the last release (v1.1.5), and the EWS Managed API is now at 1.2.1, with 2.0 in beta.

Thanks,
Andrew

JoeTanker67 wrote  Sep 6 2012 at 2:19 PM  
First of all, thank you for providing this (it seems that Microsoft wants EWS development to be done via C# and/or VB, which would be fine if Windows was the only platform in existence).

Anyway, I am have a problem with this running on USS (that is, Unix System Services on z/OS, aka on the mainframe). I have a test application that performs an (1) address book look-up, (2) sends a text message, (3) and sends a text message with an attachment. This runs fine from Windows and Linux (SUSE 11 on Intel processor).

However, on USS, tests (1) and (2) work but not (3) -- the attachment test case. I've seen two different instances of this message...

javax.xml.stream.XMLStreamException: Character reference "&#x16;" is an invalid XML character.

One flagging "&#x16;" and the other flagging "&#x7;".

I've tried enabling tracing via service.setTraceEnabled(true); where service is my ExchangeService object. On Windows, this gives me trace messages as well as the SOAP statements (in plain text ASCII). On USS, the trace is also in ASCII EXCEPT for, what I assume is, the SOAP statements. I do not recognize the data - it is not ASCII (although I do see a few &gt;, &lt; and &amp; strings in it) nor EBCDIC. Perhaps it is encoded in some way but I have no idea.

Has anyone else tried EWS Java on USS (the mainframe)?

Any suggestions?


FYI:

Java version on USS
--------------------------------------------------------------------------------
java version "1.6.0"
Java(TM) SE Runtime Environment (build pmz6460sr10fp1-20120321_01(SR10 FP1))
IBM J9 VM (build 2.4, JRE 1.6.0 IBM J9 2.4 z/OS s390x-64 jvmmz6460sr10fp1-20120202_101568 (JIT enabled, AOT enabled)
J9VM - 20120202_101568
JIT - r9_20111107_21307ifx1
GC - 20120202_AA)
JCL - 20120320_01


StackTrace
--------------------------------------------------------------------------------
javax.xml.stream.XMLStreamException: Character reference "&#x16;" is an invalid XML character.
.at com.ibm.xml.xlxp.api.stax.msg.StAXMessageProvider.throwWrappedXMLStreamException(StAXMessageProvider.java:73)
.at com.ibm.xml.xlxp.api.stax.XMLStreamReaderImpl.produceFatalErrorEvent(XMLStreamReaderImpl.java:2103)
.at com.ibm.xml.xlxp.api.stax.XMLStreamReaderImpl.reportFatalError(XMLStreamReaderImpl.java:2109)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.reportFatalError(DocumentEntityScanner.java:479)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.scanCharacterReference(DocumentEntityScanner.java:4254)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.checkReferenceInContent(DocumentEntityScanner.java:4395)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.scanContentUnbuffered2(DocumentEntityScanner.java:2914)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.scanContentUnbuffered(DocumentEntityScanner.java:2755)
.at com.ibm.xml.xlxp.api.util.SimpleScannerHelper.scanContentUnbuffered(SimpleScannerHelper.java:1242)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.stateUnbufferedContent(DocumentEntityScanner.java:551)
.at com.ibm.xml.xlxp.scan.DocumentEntityScanner.produceEvent(DocumentEntityScanner.java:644)
.at com.ibm.xml.xlxp.api.stax.XMLStreamReaderImpl.getNextScannerEvent(XMLStreamReaderImpl.java:1645)
.at com.ibm.xml.xlxp.api.stax.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:536)
.at com.ibm.xml.xlxp.api.stax.XMLInputFactoryImpl$XMLStreamReaderProxy.next(XMLInputFactoryImpl.java:180)
.at com.ibm.xml.xlxp.api.stax.XMLEventReaderImpl.createNextEvent(XMLEventReaderImpl.java:361)
.at com.ibm.xml.xlxp.api.stax.XMLEventReaderImpl.peek(XMLEventReaderImpl.java:159)
.at microsoft.exchange.webservices.data.EwsXmlReader.isEmptyElement(Unknown Source)
.at microsoft.exchange.webservices.data.EwsXmlReader.readElementValue(Unknown Source)
.at microsoft.exchange.webservices.data.EwsXmlReader.readElementValue(Unknown Source)
.at microsoft.exchange.webservices.data.SoapFaultDetails.parse(Unknown Source)
.at microsoft.exchange.webservices.data.ServiceRequestBase.readSoapFault(Unknown Source)
.at microsoft.exchange.webservices.data.ServiceRequestBase.processWebException(Unknown Source)
.at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(Unknown Source)
.at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
.at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
.at microsoft.exchange.webservices.data.ExchangeService.createAttachments(Unknown Source)
.at microsoft.exchange.webservices.data.AttachmentCollection.internalCreateAttachments(Unknown Source)
.at microsoft.exchange.webservices.data.AttachmentCollection.save(Unknown Source)
.at microsoft.exchange.webservices.data.Item.internalCreate(Unknown Source)
.at microsoft.exchange.webservices.data.EmailMessage.internalSend(Unknown Source)
.at microsoft.exchange.webservices.data.EmailMessage.send(Unknown Source)
.at ca.com.EwsTest.testCAExchange(EwsTest.java:147)
.at ca.com.HelloEWS.main(HelloEWS.java:21)


Presumed SOAP statement on USS (from trace), displayed with HEX data
--------------------------------------------------------------------------------
<Trace Tag="EwsRequest" Tid="1" Time="2012-09-05 17:35:55Z">
1357666256632477567767722566323225666323333233233233333333523222222222222222222222222222222222222222222222222222222222222222
5C421350417D2573251553420494D212049D5D22012D09D05017A35A55A2E000000000000000000000000000000000000000000000000000000000000000
---------------------------------------------------------------------------------------------------------------------------
à _% à à à à à ?&gt;      à &gt;à ?à à &gt;à  à à à    à ?/ø á&gt;à à %?øà  à _%&gt;à  à ?/ø  à à Ã
11C852C8C8C8C8C8C9326731C8C90C9C8C8C82673C83C8C92673C81C8C8C8C80C9C81C91C832CBC9CA2673C8C823CBC8C8C8522673C8C9C832CB1C8C8C8C
4A3CF5203E313A3B31F674B52221620222031674B34F3031674B355223D383352822A2E43BFF382A31674B3E315F3831203CF5674B3B2A3BFF3852237383
---------------------------------------------------------------------------------------------------------------------------
</Trace>
3257666322222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222
CF42135E00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
---------------------------------------------------------------------------------------------------------------------------

Corresponding SOAP statement on Windows (from trace)
--------------------------------------------------------------------------------
<Trace Tag="EwsRequest" Tid="1" Time="2012-09-04 18:37:02Z">
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"

Lio250 wrote  Sep 12 2012 at 6:06 AM  
Hi
I am looking for Exchange EWS simulator, i need to simulate an Exchange server with 50K mail boxes any one maybe familier with a tool that can do this ?
Thanks
lior.nudelman@rsa.com

JoeTanker67 wrote  Sep 25 2012 at 6:00 PM  
@TOPIC: EWS JAVA API on the Mainframe

=== Overview ===

This is a follow-up to my 06-Sep-2012 posting regarding using the EWS Java API on the mainframe (specifically USS, Unix System Services, on z/OS).

I had discovered that the API failed when attempting to send messages with attachments. Note: I only tested (1) address book look-up, (2) send a text message, (3) and send a text message with an attachment. The API failed (exception) on the third case.

I have discovered the cause of the problem - the Base64 class (Base64.java) method encode() does not take into account the default charset may not be ASCII. The problem occurs because the encode function uses a byte array to construct the encoded string (ASCII characters); when the byte array converted to a Java String, the String constructor assumes the byte array is in the native charset (it is not); the resulting String value is garbage. The actual exception occurs much later in the process, probably when the garbage data is being used to construct the XML.

I have modified the Base64.java file to solve the problem, at least for method encode. The solution was to override the charset on the new String that is returned from Base64.encode().

NOTE: I did not test decode. But a cursory review would seem to indicate it may be OK. It uses String->charAt() which, as far as I can tell, does not take into account the current charset and does not return a String (it returned a byte array which should be treated as bytes in all cases). But as I did not test this, I cannot be sure it is OK.

=== Questions to Microsoft ===

(1) Can you (someone from Microsoft associated with this component/project) acknowledge this? I.e. that you've read my post and understand what I am talking about.

(2) Can you fix this and publish a new JAR? I will provide the updated source file if asked; I would have uploaded if I knew how, instead I've described the code changes below. If so, do you have an ETA?

(3) If you are unable (unwilling) to fix this, is it permissible to me to ship the EWS Java API JAR that I've build with the fix? This would be with a commercial (for profit) application. The license agreement leads me to believe this is permissible (I am hoping to get a legal review from my own company per our own third-party software/component rules & requirements).

=== Code Changes ===

Remarks:
a> Indicates added code (line).
d> Indicates delete code (line).

<pre>
Package: microsoft.exchange.webservices.data
Source: Base64.java

(1) Added new class variable

/** The data. */
static byte[] dataArry;
a> static boolean bNotAscii = false;

(2) Added code to set new class variable

static {
dataArry = new byte[64];
for (int i = 0; i < 64; i++) {
byte s = (byte)strSet.charAt(i);
dataArry[i] = s;
}
a> /* Determine if platform is not using ASCII. */
a> try
a> {
a> String strNotAscii = System.getProperty("platform.notASCII");
a> if ( (strNotAscii != null) && !strNotAscii.isEmpty() && (strNotAscii.equalsIgnoreCase("true")))
a> {
a> bNotAscii = true;
a> }
a> }
a> catch(Exception e)
a> {
a> // No action.
a> }
}

3) Modified method encode()

public static String encode(byte[] byteArry, int startIndex, int length) {
...
d> return new String(resArry);

a> if (!bNotAscii)
a> {
a> return new String(resArry);
a> }
a> else
a> {
a> try
a> {
a> return new String(resArry, "windows-1252"); /* TODO: Is this guaranteed to exist for all Java? */
a> }
a> catch (Exception e)
a> {
a> return new String(resArry);
a> }
a> }

</pre>

=== Action Items ===

1) Test on z/Linux (Linux on the mainframe). I plan to do this once I get access to a system.

2) Determine if charset "windows-1252" is supported on all potential non-ASCII systems. If not, what alternative charset may be used.

3) Determine if the decode method is also flawed on non-ASCII systems.

devmsaleh wrote  Oct 14 2012 at 3:31 PM  
i am using **EWS Java API 1.1.5** to send emails on **Exchange 2010**
as follows:

ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(email, password);
service.setCredentials(credentials);
service.setUrl(new java.net.URI("https://" + host
+ "/EWS/Exchange.asmx"));
service.setTraceEnabled(true);

EmailMessage msg = new EmailMessage(service);
msg.setSubject("Hello world!");
msg.setBody(MessageBody
.getMessageBodyFromText("Sent using the EWS Managed API."));
msg.getToRecipients().add("email");
msg.send();

the message is not delivered to the inbox, and i don't know what is the problem.
after i enabled tracing, i get the following :


<Trace Tag="EwsRequestHttpHeaders" Tid="1" Time="2012-10-14 11:13:46Z">
POST /EWS/Exchange.asmx HTTP/1.1
Content-type : text/xml; charset=utf-8
Accept-Encoding : gzip,deflate
Keep-Alive : 300
User-Agent : ExchangeServicesClient/0.0.0.0
Connection : Keep-Alive
Accept : text/xml


</Trace>

<Trace Tag="EwsRequest" Tid="1" Time="2012-10-14 11:13:47Z">
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><soap:Header><t:RequestServerVersion Version="Exchange2010_SP1"></t:RequestServerVersion></soap:Header><soap:Body><m:CreateItem MessageDisposition="SendOnly"><m:Items><t:Message><t:Subject>Hello world!</t:Subject><t:Body BodyType="HTML">Sent using the EWS Managed API.</t:Body><t:ToRecipients><t:Mailbox><t:EmailAddress>adamb@fabrikam.com</t:EmailAddress></t:Mailbox></t:ToRecipients></t:Message></m:Items></m:CreateItem></soap:Body></soap:Envelope>
</Trace>

14/10/2012 01:13:48 ? org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected
<Trace Tag="EwsResponseHttpHeaders" Tid="1" Time="2012-10-14 11:13:48Z">
200 text/xml; charset=utf-8
X-AspNet-Version : 2.0.50727
X-EwsPerformanceData : RpcC=3;RpcL=15;LdapC=0;LdapL=0;
Persistent-Auth : true
Date : Sun, 14 Oct 2012 11:13:48 GMT
Vary : Accept-Encoding
Transfer-Encoding : chunked
Content-Encoding : gzip
Content-Type : text/xml; charset=utf-8
X-Powered-By : ASP.NET
Server : Microsoft-IIS/7.5
Cache-Control : private


</Trace>

<Trace Tag="EwsResponse" Tid="1" Time="2012-10-14 11:13:48Z">
<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header><h:ServerVersionInfo MajorVersion="14" MinorVersion="1" MajorBuildNumber="218" MinorBuildNumber="14" Version="Exchange2010_SP1" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/></s:Header><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><m:CreateItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><m:ResponseMessages><m:CreateItemResponseMessage ResponseClass="Success"><m:ResponseCode>NoError</m:ResponseCode><m:Items/></m:CreateItemResponseMessage></m:ResponseMessages></m:CreateItemResponse></s:Body></s:Envelope>
</Trace>

please advise how to solve this issue.

JoeTanker67 wrote  Oct 22 2012 at 1:36 PM  
@TOPIC: EWS JAVA API on the Mainframe

Hello Microsoft EWS Java API Team:

Has anyone had a chance to review the problem I first reported via a comment on "Sep 6 at 10:19 AM" then again on "Sep 25 at 2:00 PM" in a follow-up where I found the cause of the problem and a suggested solution?

To summarize the problem: When using the EWS Java API from a mainframe system (in this case, Unix System Services aka USS), sending messages with attachments fail. This is due to a flaw in the Base64.java encode() method not taking into account the platform's default charset -- USS is EBCDIC, the method assumes ASCII.

We (my product) would like to go forward with using the EWS Java API in our next release (replacing our current SMTP interface) but may not be able to do so if this problem is not fixed. The reason being that we expect a large percentage of our customers to run our application on the mainframe. NOTE: My company's legal department has given conditional approval to use the EWS Java API BUT they state I cannot alter your functionality (which I take to include bug fixes).

Please acknowledge this message. You may contact me directly via email to further discuss this -- I can provide my "fix" so that you may incorporate it into your distribution.

Regards,
JoeTanker67

maymard wrote  Oct 26 2012 at 1:31 AM  
Hi,

I am getting a 401(Unauthorized), but can access the site manually with the same credentials. I've tried specifying the domain separately and together with the user name, but no luck. The server is using NLTM to authenticate and I'm wondering if that's the problem. I turned on debugging and am including it below. Any help would be greatly appreciated!

Here's the code:

ExchangeService exchSvc = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("domain\\user", "password");
exchSvc.setCredentials(credentials);
exchSvc.setUrl("https://validserver/ews/Exchange.asmx");
exchSvc.setTraceEnabled(true);
EmailAddressCollection rooms = exchSvc.getRoomLists();

Here's the output from debug:

<Trace Tag="EwsRequestHttpHeaders" Tid="1" Time="2012-10-26 01:28:50Z">&#xd;
POST /ews/Exchange.asmx HTTP/1.1
Content-type : text/xml; charset=utf-8
Accept-Encoding : gzip,deflate
Keep-Alive : 300
User-Agent : ExchangeServicesClient/0.0.0.0
Connection : Keep-Alive
Accept : text/xml

&#xd;
</Trace>

<Trace Tag="EwsRequest" Tid="1" Time="2012-10-26 01:28:50Z">&#xd;
<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><soap:Header><t:RequestServerVersion Version="Exchange2010_SP1" /></soap:Header><soap:Body><m:GetRoomLists /></soap:Body></soap:Envelope>&#xd;
</Trace>

<Trace Tag="EwsResponseHttpHeaders" Tid="1" Time="2012-10-26 01:28:50Z">&#xd;
401 null
WWW-Authenticate : NTLM
Date : Fri, 26 Oct 2012 01:27:57 GMT
Content-Length : 0
X-DiagInfo : 029-sn1mmr1-003
Set-Cookie : exchangecookie=ae16c4f6f4aa4c8a9ec7868342023d12; expires=Sat, 26-Oct-2013 01:27:58 GMT; path=/; HttpOnly
X-Powered-By : ASP.NET
Server : Microsoft-IIS/7.5

&#xd;
</Trace>

Exception in thread "main" microsoft.exchange.webservices.data.HttpErrorException: The remote server returned an error: (401)Unauthorized
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.GetRoomListsRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.getRoomLists(Unknown Source)
at com.gap.gid.services.gapresources.service.impl.TestEWS.main(TestEWS.java:33)

Thanks!
Mike

tommix000 wrote  Nov 23 2012 at 3:51 PM  
XML output from Exchange is often not valid, since it uses a XML header version="1.0" but delivers XML containing control characters, which is only allowed in XML >= 1.1.
I got a hack for anyone using EWSApi 1.1.5 who encounters errors like "The request failed. Illegal character entity: expansion character (code 0xb) not
a valid XML character".
Workaround is quite ugly, since it loads stream in memory and replaces the version text with "1.1".
If you are not afraif of that, you can replace the method "readResponse(HttpWebRequest response)" in
SimpleServiceRequestBase.java with

private Object readResponse(HttpWebRequest response) throws Exception {
InputStream responseStream = ServiceRequestBase.getResponseStream(response);
ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();

while (true) {
int data = responseStream.read();
if (-1 == data) {
break;
} else {
memoryStream.write(data);
}
}
if (this.getService().isTraceEnabledFor(TraceFlags.EwsResponse)) {
this.traceResponse(response, memoryStream);
}
String temporaryXmlString = memoryStream.toString();
temporaryXmlString = temporaryXmlString.replaceAll("version=\"1.0\"", "version=\"1.1\"");
ByteArrayInputStream memoryStreamIn =
new ByteArrayInputStream(
temporaryXmlString.getBytes());
EwsServiceXmlReader ewsXmlReader =
new EwsServiceXmlReader(memoryStreamIn,
this.getService());
Object serviceResponse = this.readResponse(ewsXmlReader);
try {
responseStream.close();
} catch (IOException iOException) {
}
try {
memoryStream.flush();
} catch (IOException iOException) {
}
return serviceResponse;
}

Regards,
Tommix000

yoxel wrote  Nov 27 2012 at 4:55 AM  
Hello MS/EWS team. Could you please explain the situation with the changing ItemId's?
Seems like they are not exactly primary keys for items and may change overtime.
Under what circumstances do they change exactly? Do those ids get re-cycled?
It seems to me I see cases where different emails in SentItems folder get the same ItemId now and then.
Please explain.
Thank you very much.

patilmr wrote  Dec 7 2012 at 10:57 AM  
Hello,
I am getting following error when I try to find the folder. I am able to see wsdl file in IE any idea what could be the problem...

java.lang.NullPointerException
at microsoft.exchange.webservices.data.Strings.<clinit>(Strings.java:223)
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(ServiceRequestBase.java:945)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:825)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:46)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:928)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:982)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:1053)
at com.test.ews.EWSEmail.main(EWSEmail.java:39)
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
at java.util.regex.Matcher.reset(Matcher.java:291)
at java.util.regex.Matcher.<init>(Matcher.java:211)
at java.util.regex.Pattern.matcher(Pattern.java:888)
at java.util.Formatter.parse(Formatter.java:2458)
at java.util.Formatter.format(Formatter.java:2414)
at java.util.Formatter.format(Formatter.java:2367)
at java.lang.String.format(String.java:2769)
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(ServiceRequestBase.java:944)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:825)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:46)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:928)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:982)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:1053)
at com.test.ews.EWSEmail.main(EWSEmail.java:39)

gludington wrote  Dec 9 2012 at 4:46 PM  
Thank you for this library. Two issue we have had to work around:

1) IM Address changes do not get updated on Exchange Server. To fix, in ImAddressEntry.java, the setImAddress(Object value) method should read:

public void setImAddress(Object value) {
//a change from stock version of library, still trying to figure out how to post bug report to them
if (this.canSetFieldValue((String)this.imAddress, value)) {
this.imAddress = (String)value;
this.changed();
}
}

2) HttpClientWebRequest.java registers its own socket factory as a JVM-wide default for the https protocol in both prepareConnection() and prepareAsyncConnection(). If using this library in an environment which already has a custom protocol registered, this will cause problems. We removed the default registration; please consider removing the default registration and/or making it a configurable runtime option.

patilmr wrote  Dec 10 2012 at 8:26 AM  
Hello I'm getting null pointer error in exchange library with following code at service.findItems method.
I check wsdl file is showing properly. Also I tried with .net C# and it is working. But failing with java api. Any thing missing...

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
ExchangeCredentials credentials = new WebCredentials("email address","password", "domain");
service.setCredentials(credentials);
URI uri = new URI("https://hostname/ews/Exchange.asmx");
service.setUrl(uri);
ItemView view = new ItemView(10);
FindItemsResults<Item> results = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), view);

tomi wrote  Dec 10 2012 at 12:34 PM  
Can anybody catch up a idea to deal with the all day event bug...
When I set the appointment IsAllDayEvent true. It will return the correct result when loading by EWS
but On OWA is the wrong start/end time with an unchecked checkbox.
the start/end time seems is the timezone offset.

plz help if anybody have fix this bug
Thank you

gloo wrote  Dec 11 2012 at 3:19 PM  
I found a bug where recurrence getEndDate() and numberOfOccurrences() always return null when accessing the master recurring item through the API. I've provided steps to fix it along with an explanation here: http://stackoverflow.com/questions/11200822/cant-get-recurrence-end-date-using-ews-java-api

patilmr wrote  Dec 12 2012 at 10:42 AM  
Any idea how to connect using NT credentials? as in .net it allows NetworkCredential but in java it does not allow NTCredential to login..

wcwilson wrote  Jan 2 2013 at 6:58 PM  
Hi, is a version 2.0 of the Java in the works or does this end at 1.2?

rafata wrote  Jan 6 2013 at 11:05 AM  
Hi.... I have downloaded EWS Java api 1.2 and added all the jars required. When i run the code in Java, i get the error message "microsoft.exchange.webservices.data.EWSHttpException: Connection not established" ... Please help me to fix this.

LarsD wrote  Jan 6 2013 at 12:14 PM  
Hi.

I am interested in using EWS to work with tasks. Actually I can find and access the properties of my tasks, change them, create new ones, get TaskRequest Mails etc..

But I can not find any classes and methods for delegating and accepting a task. If I create a new task, the property "owner" becomes empty.

How can I respond to a IPM.TaskRequest and accept it?

How can I set the owner and send him a request for taking the task?

jme wrote  Jan 11 2013 at 10:13 PM  
I'm attempting to use EWS to update my companies employee calendar in outlook whenever an update is made to one of our products used for time and attendance tracking. I do not know what url I should be connecting with though and I have tried a couple different onces that I have seen people use with no luck. I recieve errors when attempting to connect manually or through autodiscover.

AutoDiscover error:

INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Jan 11, 2013 5:05:57 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
microsoft.exchange.webservices.data.AutodiscoverLocalException: The Autodiscover service couldn't be located.


All of our employee emails are set up through AutoDiscover so there is no way that the autodiscover feature isn't enabled. When trying to connect I am using the following code:

emailaddress="jlapine@lbisoftware.com";
password="***********";

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials(emailaddress, password);
service.setCredentials(credentials);
service.autodiscoverUrl(emailaddress);


After this I attempted to connect to the company server directly and recieved the following error:

Jan 10, 2013 11:52:59 AM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected
Jan 10, 2013 11:52:59 AM org.apache.commons.httpclient.HttpMethodDirector processWWWAuthChallenge
INFO: Failure authenticating with NTLM <any realm>@owa.********.com:443


This was caused by the following code:

emailaddress="jlapine@lbisoftware.com";
password="***********";
serverURL = "owa.*****.com/EWS/Exchange.asmx";

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials(emailaddress, password);
service.setCredentials(credentials);
URI uri = new URI(serverURL);
service.setUrl(uri);




If anybody can tell me what I'm doing wrong that would be great. My email is above but please contact me at jlapine@lbisoftware.com if you can help.

Thankyou.

deniser wrote  Feb 6 2013 at 3:28 PM  
Hi,
Does anyone know why a contact created through Java EWS in msexchange web is corrupted and can not be deleted?

KingTom wrote  Feb 13 2013 at 1:54 PM  
NTLM authentication works with JWebServices http://www.independentsoft.de/jwebservices/index.html

//Tom

nruzan wrote  Feb 14 2013 at 7:39 AM  
Hi, I'm using EWS 1.2 to send and receive mails with android app. Sending mails with attachment works fine, but when i want to get the attachment, the load of the attachment fails.

message.load(new PropertySet(BasePropertySet.FirstClassProperties,
EmailMessageSchema.Attachments));
FileAttachment attachment = (FileAttachment)message.getAttachments().getPropertyAtIndex(0);
FileOutputStream fos = openFileOutput(attachment.getName(), Context.MODE_PRIVATE);

attachment.load(fos);

After load an exception is thrown, saying connection not established. But I debug the api code and it fails while parsing the response.
Can you please give me an answer. Thanks in advance.

FredLin wrote  Mar 8 2013 at 5:50 PM  
In Exchange2007_SP1 mode, the EWS API expects a ConflictResults element in the UpdateItemResponse, but Office365 does not include it, which causes an exception which closes the connection, so subsequent actions fail. Either, the EWS Java API should not expect this element in Exchange2007_SP1 responses, or Office365 should include it in Exchange2007_SP1 responses.

Thank you for the API! It is very helpful!

I'm using the 1.2 API to retrieve emails from Exchange servers. They may be Exchange 2007_SP1 or later. Works fine, except when I try to update emails (to mark them read). Testing with Office365, that fails when connecting with ExchangeVersion.Exchange2007_SP1 (EWSHttpException: Connection not established), but succeeds with ExchangeVersion.Exchange2010 and above. I've traced that to an element (<m:ConflictResults><t:Count>0</t:Count></m:ConflictResults>) in UpdateItemResponseMessage, that is present in the response when connection as Exchange2010, but missing when connecting as Exchange2007_SP1. ExchangeService has Exchange2007CompatibilityMode. Per comment, it is there to cause Exchange2007-compatibility when the request version is set to Exchange2007_SP1. Also, the accessors are protected, so can't be accessed from the outside. Work-around: 1. use only Exchange2010 and above; or 2. set Exchange2007CompatibilityMode (required modification of the EWS API code).

UpdateItemResponse.java indicates that the Exchange2007 response may not have the ConflictResults element, but in my testing, that element is also missing in the response from Office365 when accessed in Exchange2007_SP1 mode.
protected void readElementsFromXml(EwsServiceXmlReader reader)
[...]
if(!reader.getService().getExchange2007CompatibilityMode())
{
reader.readStartElement(XmlNamespace.Messages,
XmlElementNames.ConflictResults);
this.conflictCount = reader.readElementValue(Integer.class,
XmlNamespace.Types, XmlElementNames.Count);
reader.readEndElement(XmlNamespace.Messages,
XmlElementNames.ConflictResults);
}
[...]

Exchange2007CompatibilityMode affects also:
Appointment.validate()
ResolveNamesRequest.writeAttributesToXml(EwsServiceXmlWriter)
StartTimeZonePropertyDefinition.writePropertyValueToXml(EwsServiceXmlWriter, PropertyBag, boolean)

The failure is after the first updateItem request, so it's parsing the "success" "NoError" response. I've tried this with a series of single update requests (the first message is marked read, the second update fails with exception above, because the connection is closed) or with a bulk update request (the bulk request sets all messages read, then any subsequent request fails with the exception above).

Thanks!
Fred

peterdmello wrote  Mar 10 2013 at 11:22 PM  
I'm trying to connect to my work Exchange server which by default tries to use NTLM. After fiddling around the authentication params, i had to provide the domain and the username without the @...
Anyway, i started getting this exception next:
Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(HttpClientWebRequest.java:394)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseHeaders(HttpClientWebRequest.java:280)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(ExchangeServiceBase.java:1045)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:59)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(ExchangeService.java:350)
at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(ExchangeService.java:374)
at microsoft.exchange.webservices.data.Folder.bind(Folder.java:50)
at microsoft.exchange.webservices.data.Folder.bind(Folder.java:109)
at FirstTest.main(FirstTest.java:34)

On modifying the source code to make it spit out the exact error, i noticed that the WSDL response is not a valid XML. Here's the output i received: i've removed the actual for privacy reasons. The response is between the dashed lines:
-------------------------------
b17
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header><h:ServerVersionInfo MajorVersion="14" MinorVersion="2" MajorBuildNumber="309" MinorBuildNumber="2" Version="Exchange2010_SP2" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/></s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>...</m:GetFolderResponse>
16
</s:Body></s:Envelope>
0
-------------------------------
As can be seen, there are these weird numbers and characters in the response which causes problems. This seems to be a problem on the Exchange server side right? On modifying the output by hardcoding the output of the response without the bad characters, everything works fine.

Bartok wrote  Mar 15 2013 at 12:33 PM  
I've found a problem with methods of Items that return Date, specifically with the TimeZone: when parsing the UTC string of the time from the xml, the SimpleDateFormat set the local TimeZone.
So i've fixed this behaviour inserting this code in the convertUniversalDateTimeStringToDate method of the ExchangeServiceBase class, after line 499 (for the 1.2 version)

utcFormatter.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));

Hope that this can help anyone

mblahay wrote  Mar 15 2013 at 1:46 PM  
Does anyone have a copy of 1.1.4 that they can send me? I am currently limited to Java 1.5 and cannot run any of the EWS version from 1.1.5 on up because they require Java 1.6.

wilsonwu1981 wrote  Mar 20 2013 at 11:35 AM  
For those encounter NTLM authentication problem, for my case it turns out the flags used to generate Type 1 & Type 3 messages are wrong.
Modify NTLM class in EwsJCIFSNTLMScheme.java to change the flags used to generate message:

private static final int TYPE_1_FLAGS =
NtlmFlags.NTLMSSP_NEGOTIATE_NTLM |
NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE |
NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2;

private String generateType1Msg(String host, String domain) {
jcifs.ntlmssp.Type1Message t1m = new jcifs.ntlmssp.Type1Message(TYPE_1_FLAGS,
domain, host);
return jcifs.util.Base64.encode(t1m.toByteArray());
}

private String generateType3Msg(String username, String password, String host,
String domain, String challenge) {
jcifs.ntlmssp.Type2Message t2m;
try {
t2m = new jcifs.ntlmssp.Type2Message(jcifs.util.Base64.decode(challenge));
} catch (IOException e) {
throw new RuntimeException("Invalid Type2 message", e);
}

final int type2Flags = t2m.getFlags();
final int type3Flags = type2Flags
& (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));

jcifs.ntlmssp.Type3Message t3m = new jcifs.ntlmssp.Type3Message(t2m, password, domain,
username, host, type3Flags);
return jcifs.util.Base64.encode(t3m.toByteArray());
}

buckett wrote  Mar 31 2013 at 9:34 AM  
It's a shame that with the newer releases the license has changed from a reasonably standard Microsoft Open Source license to a custom one. Could I ask what the reason for the change is?

leventgo wrote  Apr 5 2013 at 5:56 PM  
Hi, we are using EWS Java API to use the outlook calendar on our Java application. I am having authentication issues on EWS. I tried the application on the cloud outlook account that's supplied by rockspace and everything worked just fine.

Here is the code:

import java.net.URI;
import java.net.URISyntaxException;

import microsoft.exchange.webservices.data.*;;

public class TestClass {

public static void main(String[] args) {
TestClass obj = new TestClass();
obj.testMethod();
}

public void testMethod(){
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
ExchangeCredentials credentials = new WebCredentials("username", "password");


service.setCredentials(credentials);

try {
service.setUrl(new URI("https://domain/EWS/Exchange.asmx"));
} catch (URISyntaxException e) {
e.printStackTrace();
}


EmailMessage msg;
try {
msg = new EmailMessage(service);
msg.setSubject("hello world");
msg.setBody(MessageBody.getMessageBodyFromText("Sent using the EWS API"));
msg.getToRecipients().add("test@test.com");
msg.send();
} catch (Exception e) {
e.printStackTrace();
}

}

}


The url for rockspace is:https://connect.emailsrvr.com/EWS/Exchange.asmx
When I put the username and password for this account and it works, I see the console spitting out this one:

Apr 05, 2013 1:40:28 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: NTLM authentication scheme selected

Our client is using ExchangeVersion.Exchange2007_SP1 whereas Rockspace is using ExchangeVersion.Exchange2010 But when I use the credentials(username, password and url) that our client provided, I am getting this error:

Apr 05, 2013 1:49:13 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme
INFO: Basic authentication scheme selected
Apr 05, 2013 1:49:13 PM org.apache.commons.httpclient.HttpMethodDirector processAuthenticationResponse
SEVERE: Invalid challenge: Basic
org.apache.commons.httpclient.auth.MalformedChallengeException: Invalid challenge: Basic
at org.apache.commons.httpclient.auth.AuthChallengeParser.extractParams(AuthChallengeParser.java:98)
at org.apache.commons.httpclient.auth.RFC2617Scheme.processChallenge(RFC2617Scheme.java:94)
at org.apache.commons.httpclient.auth.BasicScheme.processChallenge(BasicScheme.java:112)
at org.apache.commons.httpclient.auth.AuthChallengeProcessor.processChallenge(AuthChallengeProcessor.java:162)
at org.apache.commons.httpclient.HttpMethodDirector.processWWWAuthChallenge(HttpMethodDirector.java:694)
at org.apache.commons.httpclient.HttpMethodDirector.processAuthenticationResponse(HttpMethodDirector.java:668)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:193)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at microsoft.exchange.webservices.data.HttpClientWebRequest.executeRequest(HttpClientWebRequest.java:358)
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(ServiceRequestBase.java:930)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:825)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:46)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(ExchangeService.java:464)
at microsoft.exchange.webservices.data.ExchangeService.createItem(ExchangeService.java:535)
at microsoft.exchange.webservices.data.Item.internalCreate(Item.java:215)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(EmailMessage.java:125)
at microsoft.exchange.webservices.data.EmailMessage.send(EmailMessage.java:253)
at com.aurora.trials.TestClass.testMethod(TestClass.java:43)
at com.aurora.trials.TestClass.main(TestClass.java:17)

microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(HttpClientWebRequest.java:394)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseHeaders(HttpClientWebRequest.java:280)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(ExchangeServiceBase.java:1045)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:58)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(ExchangeService.java:464)
at microsoft.exchange.webservices.data.ExchangeService.createItem(ExchangeService.java:535)
at microsoft.exchange.webservices.data.Item.internalCreate(Item.java:215)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(EmailMessage.java:125)
at microsoft.exchange.webservices.data.EmailMessage.send(EmailMessage.java:253)
at com.aurora.trials.TestClass.testMethod(TestClass.java:43)
at com.aurora.trials.TestClass.main(TestClass.java:17)

It's urgent and I couldn't find any solution for this issue. Please provide any info that you think I can get authenticated for EWS.

leventgo wrote  Apr 5 2013 at 6:04 PM  
I know the credentials that our client provided works because I can log in by using them on web interface.

SAN3 wrote  Apr 15 2013 at 6:30 AM  
When will you release java api for Exchange 2013 ?

Dreamer23 wrote  Apr 17 2013 at 10:46 AM  
Hi everyone,

I'm currently trying to connect to our company's exchange server using EWS.
Unfortunately when try to execute anything (either autodiscover or some other action after using setUrl manually) I receive the following error:

Apr 17, 2013 7:57:10 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
Apr 17, 2013 7:57:10 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Apr 17, 2013 7:57:11 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
Apr 17, 2013 7:57:11 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Apr 17, 2013 7:57:12 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection refused: connect
Apr 17, 2013 7:57:12 AM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Exception in thread "main" microsoft.exchange.webservices.data.ServiceRequestException: The request failed. Connection refused: connect
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(Unknown Source)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.bindToFolder(Unknown Source)
at microsoft.exchange.webservices.data.CalendarFolder.bind(Unknown Source)
at microsoft.exchange.webservices.data.CalendarFolder.bind(Unknown Source)
at er.dream.tgif.outlook.OutlookTest.findAppointments(OutlookTest.java:59)
at er.dream.tgif.outlook.OutlookTest.main(OutlookTest.java:45)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:618)
at microsoft.exchange.webservices.data.EwsSSLProtocolSocketFactory.createSocket(Unknown Source)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.open(MultiThreadedHttpConnectionManager.java:1361)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at microsoft.exchange.webservices.data.HttpClientWebRequest.executeRequest(Unknown Source)
... 10 more

I tried logging in using my credentials to the exchange servers web interface and this is working fine.
Assuming it might be related to SSL issues, I also tried implementing a dummy TrustManager and setting it as default for HttpsUrlConnections

Unfortunately this didn't help and the error still persists.
One notable fact: In my Outlook I can see that the Exchange server is configured to use a proxy server and a specific SSL URL to connect to it. (Proxy authentication is set to NTLM)
I'm not quite sure how to reflect this in my coding.
Might this be causing the exception or am I looking at a different issue here?

Any help would be much appreciated!

Thanks.

RRaja wrote  Apr 18 2013 at 8:00 AM  
Hi everyone,
I am using EWS Java API1.2. I need to retrieve more than one extended property from an Appointment. I am set the extendedpropertydefinition in Propertyset and then bind to Item.
When I try to get the ExtendedPropertyCollection, it is always returning the last extendedproperty which I added in PropertySet. In EWSResponse, it is showing the values for all the ExtendedProperty. But it is not inside a collection.

In below code snippet, always it is returning collection with size as "1".

Code Snippet
============
PropertyDefinitionBase extPropDef = new ExtendedPropertyDefinition(
DefaultExtendedPropertySet.PublicStrings,
"Prop1", MapiPropertyType.String);

PropertyDefinitionBase extPropDef1 = new ExtendedPropertyDefinition(
DefaultExtendedPropertySet.PublicStrings,
"Prop2", MapiPropertyType.String);

//Create Property Set with Attachment set as parameter
PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties,ItemSchema.Attachments,extPropDef,extPropDef1);
Appointment appObj = Appointment.bind(service, new ItemId(itemId),psPropSet);
//Iterate the collection
ExtendedPropertyCollection coll = appObj.getExtendedProperties();
System.out.println("coll sizxe"+coll.getCount());
for(int i=0;i<coll.getCount();i++){
ExtendedProperty extPro = coll.getPropertyAtIndex(i);
System.out.println("PropertyName::"+extPro.getPropertyDefinition().getName());
if(extPro.getValue()!=null){
System.out.println("PropertyValue::"+extPro.getValue().toString());
}else{
System.out.println("PropertyValue::null");
}
}

REQUEST
======
<Trace Tag="EwsRequest" Tid="37" Time="2013-04-17 12:33:09Z">
<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<soap:Header><t:RequestServerVersion Version="Exchange2010_SP2">
</t:RequestServerVersion></soap:Header>
<soap:Body>
<m:GetItem><m:ItemShape><t:BaseShape>AllProperties</t:BaseShape>
<t:AdditionalProperties>
<t:FieldURI FieldURI="item:Attachments"></t:FieldURI>
<t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Prop1" PropertyType="String"></t:ExtendedFieldURI>
<t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Prop2" PropertyType="String"></t:ExtendedFieldURI>
</t:AdditionalProperties>
</m:ItemShape><m:ItemIds><t:ItemId Id="ItemID1"></t:ItemId></m:ItemIds></m:GetItem></soap:Body></soap:Envelope>
</Trace>

RESPONSE
=========
<Trace Tag="EwsResponse" Tid="37" Time="2013-04-17 12:33:15Z">
<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Header><h:ServerVersionInfo MajorVersion="14" MinorVersion="2" MajorBuildNumber="309" MinorBuildNumber="3" Version="Exchange2010_SP2" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/></s:Header><s:Body><m:GetItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:GetItemResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:Items>
<t:CalendarItem>
<t:ItemClass>IPM.Appointment</t:ItemClass>
<t:Subject>Test Meeting 04/09</t:Subject>
<t:Sensitivity>Normal</t:Sensitivity>
<t:Attachments>
<t:FileAttachment><t:AttachmentId Id="attid"/><t:Name>Sample.txt</t:Name><t:Size>7262</t:Size><t:LastModifiedTime>2013-04-09T06:57:50</t:LastModifiedTime><t:IsInline>false</t:IsInline><t:IsContactPhoto>false</t:IsContactPhoto><t:ContentId></t:ContentId></t:FileAttachment></t:Attachments>
<t:HasAttachments>true</t:HasAttachments>
<t:ExtendedProperty>
<t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Prop1" PropertyType="String"/>
<t:Value>ABCD</t:Value>
</t:ExtendedProperty>
<t:ExtendedProperty><t:ExtendedFieldURI DistinguishedPropertySetId="PublicStrings" PropertyName="Prop2" PropertyType="String"/>
<t:Value>EFGH</t:Value>
</t:ExtendedProperty>
<t:Culture>en-US</t:Culture>
<t:/CalendarItem>
</m:Items>
</m:GetItemResponseMessage>
</m:ResponseMessages>
</m:GetItemResponse>
</s:Body>
</s:Envelope>
</Trace>

SeKyuKim wrote  Apr 24 2013 at 10:30 AM  
EWS JAVA API
Make Task Date Problem...

From client data = "2012-04-23-11-00-00-UTC"(due_date)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-Z");
Date dueDate = formatter.parse(due_date);
task.setDuedate(dueDate)

result..
<due_date>
<![CDATA[ Wed Apr 24 00:00:00 UTC 2013 ]]>
</due_date>


What is problem??

casimirenslip wrote  Apr 29 2013 at 1:34 PM  
Hello everyone,

I forked on my Eclipse an EWS 1.2 to update httpClient to 4.2.x (it adds NTLM v2)...

It works well (I can connect and retrieve mail from Exchange 2010SP1...) but where can I share the code ? Is there a repository for Java EWS Api ? I have not found anything to share...

I think we can't open a repository on it (like git / googlecode etc)

Thanks.

jkiddo wrote  May 4 2013 at 10:17 PM  
Hi casimirenslip.

buckett created a project on github a long time ago
------
buckett wrote Jun 20 2011 at 11:09 PM
I've wrapped this code up in a Maven project and stuck it up on github at:

https://github.com/buckett/ews-java
------
But I don't think he maintains it anymore. I don't see why you shouldn't be able to create a new repository at github containing your changes?

casimirenslip wrote  May 30 2013 at 9:45 AM  
Hi,

I forked this API with my updated version (GitHub).

It is updated with httpclient 4.2.5 and httpcore 4.2.4, but I only tested few functions, maybe functions are buggy...

https://github.com/casimirenslip/EWS-Java-API


EWJDeveloper wrote  Jun 13 2013 at 11:44 AM  
The issue with NTLM Authentication has been successfully resolved and solution was posted at StackOverflow:

In the Microsft EWS API, the class NTLM was wrong. So we re-built the JAR with the following code for the class:

private class NTLM {
/** Character encoding */
public static final String DEFAULT_CHARSET = "ASCII";

/**
* The character was used by 3.x's NTLM to encode the username and
* password. Apparently, this is not needed in when passing username,
* password from NTCredentials to the JCIFS library
*/
private String credentialCharset = DEFAULT_CHARSET;

void setCredentialCharset(String credentialCharset) {
this.credentialCharset = credentialCharset;
}

private static final int TYPE_1_FLAGS = NtlmFlags.NTLMSSP_NEGOTIATE_NTLM
| NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE
| NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2;

private String generateType1Msg(String host, String domain) {
jcifs.ntlmssp.Type1Message t1m = new jcifs.ntlmssp.Type1Message(
TYPE_1_FLAGS, domain, host);
return jcifs.util.Base64.encode(t1m.toByteArray());
}

private String generateType3Msg(String username, String password,
String host, String domain, String challenge) {
jcifs.ntlmssp.Type2Message t2m;
try {
t2m = new jcifs.ntlmssp.Type2Message(
jcifs.util.Base64.decode(challenge));
} catch (IOException e) {
throw new RuntimeException("Invalid Type2 message", e);
}

final int type2Flags = t2m.getFlags();
final int type3Flags = type2Flags
& (0xffffffff ^ (NtlmFlags.NTLMSSP_TARGET_TYPE_DOMAIN | NtlmFlags.NTLMSSP_TARGET_TYPE_SERVER));

jcifs.ntlmssp.Type3Message t3m = new jcifs.ntlmssp.Type3Message(
t2m, password, domain, username, host, type3Flags);
return jcifs.util.Base64.encode(t3m.toByteArray());
}
}

shnapsi wrote  Jul 16 2013 at 3:11 PM  
Hello,
did someone managed to solve the TimeZone problem?
i can't manage to add TimeZone or meetingTimeZone tags...
i tried all the workaround suggested here, nothing works.

Thanks,

apohl wrote  Aug 2 2013 at 6:28 AM  
Hello everyone,

I had the same problem as RRaja; I can't get more than one ExtendedProperty from contacts.
He is my bugfix/workaround (surely nor really complete right):

diff --git a/src/microsoft/exchange/webservices/data/PropertyBag.java b/src/microsoft/exchange/webservices/data/PropertyBag.java
index 1fe2e4d..f642891 100644
--- a/src/microsoft/exchange/webservices/data/PropertyBag.java
+++ b/src/microsoft/exchange/webservices/data/PropertyBag.java
@@ -872,7 +872,14 @@ class PropertyBag implements IComplexPropertyChanged,
if (object instanceof ComplexProperty) {
this.initComplexProperty((ComplexProperty) object);
}
- this.properties.put(propertyDefinition, object);
+ Object oldobj = this.properties.put(propertyDefinition, object);
+ if (oldobj instanceof ExtendedPropertyCollection) {
+ ExtendedPropertyCollection newObj = (ExtendedPropertyCollection) object;
+ ExtendedPropertyCollection oldObj = (ExtendedPropertyCollection) oldobj;
+
+ newObj.getAddedItems().addAll(oldObj.getAddedItems());
+ newObj.getItems().addAll(oldObj.getItems());
+ }
this.changed();
}


alongo wrote  Aug 12 2013 at 7:59 AM  

To create a TimeZoneDefinition object without modifying the ESWJava source code and re-building it, you can simply extend the TimeZoneDefinition class, and use it instead of the original TimeZoneDefinition:

public class ExchangeTimeZone extends TimeZoneDefinition{

public ExchangeTimeZone() {
super();
}

public ExchangeTimeZone(String id) {
super();
setId(id);
}

public ExchangeTimeZone(String id, String name) {
super();
setId(id);
setName(name);
}


public void setId(String id) {
super.setId(id);
}

public void setName(String name) {
super.setName(name);
}

}

PeteThompson wrote  Aug 13 2013 at 9:00 AM  
Hi.
Due to other software constraints I am stuck on an older version of Java. Can someone tell me wheer to find the EWS Java API 1.1 version please.
Thanks

dalmooria wrote  Sep 25 2013 at 11:06 AM  
I got a simple code to send email.
but it gives NullPointerException.

exchange server 2013 and uri... it works.
there's no problem programmed by C#.


=================================================================================================================================
package com.jo.ews.email;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import microsoft.exchange.webservices.data.BodyType;
import microsoft.exchange.webservices.data.EmailAddress;
import microsoft.exchange.webservices.data.EmailMessage;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.ExchangeVersion;
import microsoft.exchange.webservices.data.MessageBody;
import microsoft.exchange.webservices.data.WebCredentials;

public class SendEmail {

public ExchangeService connectToService() {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials("dalmooria@score.com","password"); //email, password
service.setCredentials(credentials);

try {
service.setUrl(new URI("https://msserver2012.cloudapp.net/ews/exchange.asmx"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return service;
}

public boolean sendEmail(ExchangeService service) {
try {
EmailMessage message = new EmailMessage(service);

message.getToRecipients().add("test@score.com");
message.setSubject("JAVA Test Subject");

message.setBody(MessageBody.getMessageBodyFromText("JAVA Test Body"));

EmailAddress emailAddress = new EmailAddress("dalmooria@score.com");
message.setSender(emailAddress);
message.send();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}

public static void main(String[] args) {
SendEmail send = new SendEmail();
ExchangeService service = send.connectToService();

service.setTraceEnabled(true);
send.sendEmail(service);
}
}
=================================================================================================================================

dalmooria wrote  Sep 25 2013 at 11:06 AM  

this is output.
================================================================================
<Trace Tag="EwsRequestHttpHeaders" Tid="1" Time="2013-09-25 10:53:48Z">
POST /ews/exchange.asmx HTTP/1.1
Content-type : text/xml; charset=utf-8
Accept-Encoding : gzip,deflate
Keep-Alive : 300
User-Agent : ExchangeServicesClient/0.0.0.0
Connection : Keep-Alive
Accept : text/xml


</Trace>

<Trace Tag="EwsRequest" Tid="1" Time="2013-09-25 10:53:48Z">
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><soap:Header><t:RequestServerVersion Version="Exchange2010_SP2"></t:RequestServerVersion></soap:Header><soap:Body><m:CreateItem MessageDisposition="SendOnly"><m:Items><t:Message><t:Subject>JAVA Test Subject</t:Subject><t:Body BodyType="HTML">JAVA Test Body</t:Body><t:Sender><t:Mailbox><t:EmailAddress>dalmooria@score.com</t:EmailAddress></t:Mailbox></t:Sender><t:ToRecipients><t:Mailbox><t:EmailAddress>test@score.com</t:EmailAddress></t:Mailbox></t:ToRecipients></t:Message></m:Items></m:CreateItem></soap:Body></soap:Envelope>
</Trace>

java.lang.NullPointerException
at microsoft.exchange.webservices.data.Strings.<clinit>(Strings.java:223)
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(ServiceRequestBase.java:943)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:831)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:44)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:146)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(ExchangeService.java:469)
at microsoft.exchange.webservices.data.ExchangeService.createItem(ExchangeService.java:540)
at microsoft.exchange.webservices.data.Item.internalCreate(Item.java:219)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(EmailMessage.java:127)
at microsoft.exchange.webservices.data.EmailMessage.send(EmailMessage.java:255)
at com.jo.ews.email.SendEmail.sendEmail(SendEmail.java:83)
at com.jo.ews.email.SendEmail.main(SendEmail.java:98)
java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
at java.util.regex.Matcher.reset(Matcher.java:291)
at java.util.regex.Matcher.<init>(Matcher.java:211)
at java.util.regex.Pattern.matcher(Pattern.java:888)
at java.util.Formatter.parse(Formatter.java:2458)
at java.util.Formatter.format(Formatter.java:2414)
at java.util.Formatter.format(Formatter.java:2367)
at java.lang.String.format(String.java:2769)
at microsoft.exchange.webservices.data.ServiceRequestBase.getEwsHttpWebResponse(ServiceRequestBase.java:942)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:831)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:44)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:146)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(ExchangeService.java:469)
at microsoft.exchange.webservices.data.ExchangeService.createItem(ExchangeService.java:540)
at microsoft.exchange.webservices.data.Item.internalCreate(Item.java:219)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(EmailMessage.java:127)
at microsoft.exchange.webservices.data.EmailMessage.send(EmailMessage.java:255)
at com.jo.ews.email.SendEmail.sendEmail(SendEmail.java:83)
at com.jo.ews.email.SendEmail.main(SendEmail.java:98)
================================================================================


please any help~!

poorna wrote  Oct 2 2013 at 6:38 AM  
Hi,

I am trying to access the ExtendedProperty ms-Exch-Extension-Attribute-1 (http://msdn.microsoft.com/en-us/library/exchange/ms980473(v=exchg.65).aspx) when doing name resolution for a contact in GAL.

Here is the code below. I always get 0 extended properties. What am I missing? Please help.


PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties);


// Try 1:
// ExtendedPropertyDefinition extendedPropertyDefinition =
// new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, 32813, MapiPropertyType.String);
// Try 2:
// ExtendedPropertyDefinition extendedPropertyDefinition =
// new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "<GUID>", MapiPropertyType.String);
// Try 3:
// UUID MyPropertySetId = UUID.fromString("<GUID>");
// ExtendedPropertyDefinition extendedPropertyDefinition =
// new ExtendedPropertyDefinition(MyPropertySetId, "ms-Exch-Extension-Attribute-1", MapiPropertyType.Object);
// Try 4:
// UUID MyPropertySetId = UUID.fromString("<GUID>");
// ExtendedPropertyDefinition extendedPropertyDefinition =
// new ExtendedPropertyDefinition(MyPropertySetId, 32813, MapiPropertyType.String);
// Try 5(using tag):
ExtendedPropertyDefinition extendedPropertyDefinition =
new ExtendedPropertyDefinition(32813, MapiPropertyType.String);

propertySet.add(extendedPropertyDefinition);

ExchangeService exchangeService = getExchangeService(...);
NameResolutionCollection nameResolutionCollection = exchangeService.resolveName(
searchStr,
ResolveNameSearchLocation.DirectoryThenContacts,
true,
propertySet);

...
Contact contact = nameResolution.getContact();

ExtendedPropertyCollection extendedProperties = contact.getExtendedProperties();
if (null != extendedProperties
&& 0 < extendedProperties.getCount()) {
Iterator<ExtendedProperty> iterator = extendedProperties.iterator();
while (iterator.hasNext()) {
ExtendedProperty extendedProperty = iterator.next();
if (null != extendedProperty) {
ExtendedPropertyDefinition propertyDefinition = extendedProperty.getPropertyDefinition();
String name = propertyDefinition.getName();
Object value = extendedProperty.getValue();
logger.info("Extended Property name: " + name + "\tvalue: " + value);
}
}
}

kb009 wrote  Oct 4 2013 at 7:35 AM  
i'm trying to use this library in an android project.
i'm getting the following error in runtime:

***
10-04 09:54:53.970: E/dalvikvm(4626): Could not find class 'microsoft.exchange.webservices.data.XMLNodeType', referenced from method microsoft.exchange.webservices.data.AutodiscoverService.getLegacyUserSettingsAtUrl
10-04 09:54:54.000: E/AndroidRuntime(4626): FATAL EXCEPTION: main
10-04 09:54:54.000: E/AndroidRuntime(4626): java.lang.VerifyError: microsoft/exchange/webservices/data/AutodiscoverService
10-04 09:54:54.000: E/AndroidRuntime(4626): at microsoft.exchange.webservices.data.ExchangeService.getAutodiscoverUrl(ExchangeService.java:4064)
***

i tried every combination of the library references, classpath etc.
can anyone help?

Testuser wrote  Oct 9 2013 at 9:09 AM  
Hello Everyone


We are trying to fetch some fields of Outlook Contacts through EWS JAVA Api jar version 1.15 and 1.2 to our application, but we are getting null pointer exception for the empty field i.e if user has not add that particular value corresponding to that field.

We have downloaded the jar api from the following link: http://archive.msdn.microsoft.com/ewsjavaapi/Release/ProjectReleases.aspx?ReleaseId=5754

Please confirm whether we are using correct jar or not.

Besides this we want to know several information about this API like:

whether this API required any Licence or it is free.

Is future support is available for these API's.

As source code of API version 1.15 is available so can we change that code directly and if we change it will going to impact any other functionality in future (Currently we are just putting null pointer check in source code of API).



perlausten wrote  Nov 18 2013 at 10:54 PM  
I am not able to create an appointment using TimeZoneDefinition on Exchange 2007. I always get "The time zone definition is invalid or unsupported."

What is the correct syntax?

adipose wrote  Dec 31 2013 at 11:59 PM  
The "all day" event bug has been solved! We spent two days tracking this one down and finally figured out the root of the issue. It actually happens server side so it is very hard to identify in the XML.

When saving the appointment, you must add the following flag:

appointment.save(id, SendInvitationsMode.SendToNone);

The default is "SendToAllAndSaveCopy," and it seriously fvcks things up. I don't really understand it, but we tracked down the soap calls and that was the bit that made the difference. If it sends "SendToAllAndCopy," the server turns a single, all-day event into a 24-hour span, (not set to all day), from midnight + (your timezone offset), to midnight + (your timezone offset) today + 24 hours. Even worse, if you figure out how to set the "starttimezone", it will go for 48 hours!

Hopefully someone gets some use out of this. I read the whole forum and there was not one fix for the spanning of days with all day appointments.

If this helped then vote up the solution (vinnyjames) here: http://stackoverflow.com/questions/7828823/exchange-2010-web-services-creation-of-an-all-day-event-appointment

AliKhan wrote  Jan 8 at 6:45 PM  
Hi Guys,

Following is the exception that I am getting quiet often in my server environment, but if I run the same on my local machine it runs fine. I would like to mentioned that on server after every 5 minutes I am trying to search the folders and fetch unread emails which have attachment.I tried to replicate the same scenario on my machine by calling the API to fetch the email indefinitely but no exception occurss Here is the exception I am getting:
java.lang.ClassCastException: microsoft.exchange.webservices.data.$Proxy80 incompatible with microsoft.exchange.webservices.data.EwsEnum
at microsoft.exchange.webservices.data.EwsUtilities.buildEnumToSchemaDict(EwsUtilities.java:1592)
at microsoft.exchange.webservices.data.EwsUtilities.access$2(EwsUtilities.java:1587)
at microsoft.exchange.webservices.data.EwsUtilities$4.createInstance(EwsUtilities.java:260)
at microsoft.exchange.webservices.data.EwsUtilities$4.createInstance(EwsUtilities.java:1)
at microsoft.exchange.webservices.data.LazyMember.getMember(LazyMember.java:42)
at microsoft.exchange.webservices.data.EwsUtilities.serializeEnum(EwsUtilities.java:724)
at microsoft.exchange.webservices.data.EwsServiceXmlWriter.tryConvertObjectToString(EwsServiceXmlWriter.java:88)
at microsoft.exchange.webservices.data.EwsServiceXmlWriter.writeAttributeValue(EwsServiceXmlWriter.java:194)
at microsoft.exchange.webservices.data.EwsServiceXmlWriter.writeAttributeValue(EwsServiceXmlWriter.java:178)
at microsoft.exchange.webservices.data.FolderView.writeAttributesToXml(FolderView.java:48)
at microsoft.exchange.webservices.data.FindRequest.writeAttributesToXml(FindRequest.java:109)
at microsoft.exchange.webservices.data.ServiceRequestBase.writeBodyToXml(ServiceRequestBase.java:146)
at microsoft.exchange.webservices.data.ServiceRequestBase.writeToXml(ServiceRequestBase.java:296)
at microsoft.exchange.webservices.data.ServiceRequestBase.buildEwsHttpWebRequest(ServiceRequestBase.java:867)
at microsoft.exchange.webservices.data.ServiceRequestBase.validateAndEmitRequest(ServiceRequestBase.java:824)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:46)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:144)
at microsoft.exchange.webservices.data.ExchangeService.internalFindFolders(ExchangeService.java:202)
at microsoft.exchange.webservices.data.ExchangeService.findFolders(ExchangeService.java:258)
at microsoft.exchange.webservices.data.ExchangeService.findFolders(ExchangeService.java:300)
at com.riyadbank.email.exchange.MicrosoftExchangeEmail.findFolder(MicrosoftExchangeEmail.java:132)
... 68 more

AliKhan wrote  Jan 8 at 6:46 PM  
One more thing , is there any server disconnect session function that I need to call? Please advice.

nazarhryt wrote  Jan 27 at 10:41 AM  
Hi guys,
I am using Java EWS API 1.2 to connect to my Exchange 2007 SP3, and i am getting ServiceXmlDeserializationException wit message "An element node 'soap:Envelope' of the type START_ELEMENT was expected, but node '{http://www.w3.org/2003/05/soap-envelope}Envelope' of type START_ELEMENT was found.".
While debugging I found that request is sent in SOAP 1.1 and answer in SOAP 1.2(different namespaces - http://schemas.xmlsoap.org/soap/envelope/ vs http://www.w3.org/2003/05/soap-envelope).
Does lib support SOAP 1.2?.
If it possible to reconfigure Exchange to respond in SOAP 1.1?

Thanks for collaboration.

rohini wrote  Jan 27 at 12:13 PM  
where to get answer? all questions are here only.

rohini wrote  Jan 27 at 12:14 PM  

microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(Unknown Source)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(Unknown Source)
at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.internalCreateItems(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.createItem(Unknown Source)
at microsoft.exchange.webservices.data.Item.internalCreate(Unknown Source)
at microsoft.exchange.webservices.data.EmailMessage.internalSend(Unknown Source)
at microsoft.exchange.webservices.data.EmailMessage.sendAndSaveCopy(Unknown Source)
at ExchangeMail.main

kichen wrote  Feb 14 at 3:27 AM  
Hi guys,

How to block a meeting room in Exchange 2007 or above using EWS Java API?

I'm able to send out meeting request but failed to book a room? I've tried setting the RequiredAttendees or Resources property with mail address and alias name.

Is there any way can get this done using EWS Java API?

Thanks

peterkronenberg wrote  Feb 24 at 9:58 PM  
Is EWS Java still being supported?

I am having the same problem as described here:
http://social.technet.microsoft.com/Forums/ja-JP/d4a41b28-6479-483d-8bb7-951e3ecb528f/problem-getting-calendar-event-with-recurring-using-ews-java-client-api-12 (calling Appointment.bindToRecurringMaster())

I'm pretty sure it's a bug. Somehow, HttpClientWebRequest.close() is being called prematurely, which sets httpMethod to null.
It then blows up in the call to EwsUtilities.formatHttpResponseHeaders when calling response.getResponseCode(), which calls throwIfConnNotNull()


thanks
Peter

Updating...
Page view tracker