EzDevInfo.com

php-ews

PHP Exchange Web Services

PHP-EWS - Subscription / PushNotification - complete example

after two frustrating days I give up. I have one virtual maschine "admx" with Win2012R2 + Exchange 2013 (Trailversion) and one virtual maschine "webserver" with a IIS-Webserver+PHP.

Make a new Subscription - sub.php:

<?PHP
function __autoload($class_name)
{
    // Start from the base path and determine the location from the class name,
    $base_path = 'php-ews';
    $include_file = $base_path . '/' . str_replace('_', '/', $class_name) . '.php';
    //$include_file = str_replace('_', '/', $class_name) . '.php';

    return (file_exists($include_file) ? require_once $include_file : false);
}

$server = "admx";
$host = $server;
$username = "administrator@testdom.local";
$password = "secret123";
$version = "Exchange2013";

$url = "http://webserver/testexchange/log.php";
$keepAliveFrequency = 1;

$ews = new ExchangeWebServices($server, $username, $password, $version);
$subscribe_request = new EWSType_SubscribeType();
$pushSubscription = new EWSType_PushSubscriptionRequestType();
$pushSubscription->StatusFrequency = $keepAliveFrequency;
$pushSubscription->URL = $url;
$folderIDs = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$eventTypes = new EWSType_NonEmptyArrayOfNotificationEventTypesType();
$folderIDs->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$folderIDs->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
$eventTypes->EventType = "NewMailEvent";
$pushSubscription->FolderIds = $folderIDs;
$pushSubscription->EventTypes = $eventTypes;
$subscribe_request->PushSubscriptionRequest = $pushSubscription;
$response = $ews->Subscribe($subscribe_request);

var_dump($response);
?>

Output:

object(stdClass)#10 (1) { ["ResponseMessages"]=> object(stdClass)#11 (1) { ["SubscribeResponseMessage"]=> object(stdClass)#12 (4) { ["ResponseCode"]=> string(7) "NoError" ["ResponseClass"]=> string(7) "Success" ["SubscriptionId"]=> string(64) "EgBhZG14LnRlc3Rkb20ubG9jYWwQAAAA3keYE/U5Mkacz2FAg6DfHKdXyqelf9II" ["Watermark"]=> string(40) "AQAAAF57K7d1ihJLl9odwZ02gVahGgAAAAAAAAA=" } } } 

So, the subscription is successfully registered. Here is the listener - log.php

<?PHP
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://schemas.microsoft.com/exchange/services/2006/messages\">
    <SOAP-ENV:Body>
        <ns1:SendNotificationResult>
            <ns1:SubscriptionStatus>OK</ns1:SubscriptionStatus>
        </ns1:SendNotificationResult>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>";

file_put_contents("C:\\exlog\\only_ok_".time().".txt", print_r($_REQUEST,1));
?>

Now I get every minute (because $keepAliveFrequency = 1;) a new respone / StatusCheck from the Exchange-Server. When I send a eMail to administrator@testdom.local I get a new notification immediately too (because "NewMailEvent" in Inbox). I acknowledge it with OK as XML, to keep-alive the subscription... So far so good.

But in the logfile (only_ok_1435488594.txt) is only...

Array()

Update log.php to get notification-information:

<?PHP
 class ewsService {
    public function SendNotification( $arg ) {
        file_put_contents("C:\\exlog\\logfile2_".time().".txt", print_r($arg,1));
        $result = new EWSType_SendNotificationResultType();
        $result->SubscriptionStatus = 'OK';
        //$result->SubscriptionStatus = 'Unsubscribe';
        return $result;
    }
}


$server = new SoapServer( 'php-ews/wsdl/NotificationService.wsdl', array(    'uri' => 'http://webserver/testexchange/log.php'));
$server->setObject( $service = new ewsService() );
$server->handle();
?>

And now the logfile as more informations as "array()":

stdClass Object
(
    [ResponseMessages] => stdClass Object
        (
            [SendNotificationResponseMessage] => stdClass Object
                (
                    [ResponseCode] => NoError
                    [ResponseClass] => Success
                    [Notification] => stdClass Object
                        (
                            [SubscriptionId] => EgBhZG14LnRlc3Rkb20ubG9jYWwQAAAAvfY+2ehqCEOXroWYNAsn+mD+ZBQYf9II
                            [PreviousWatermark] => AQAAAF57K7d1ihJLl9odwZ02gVZNGAAAAAAAAAA=
                            [MoreEvents] => 
                            [StatusEvent] => stdClass Object
                                (
                                    [Watermark] => AQAAAF57K7d1ihJLl9odwZ02gVZNGAAAAAAAAAA=
                                )

                        )

                )

        )
)

Problem: The Subscriptions gets after 3 more notifications lost. From the MSDN-documentation I know, the Exchangeserver retry 3-times the statusmessage to get a "OK" from the listener.

I has download the NotificationService.wsdl from GoogleSearch.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 Microsoft Corporation. All rights reserved. -->
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
    <wsdl:types>
        <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
            <xs:import namespace="http://schemas.microsoft.com/exchange/services/2006/messages" schemaLocation="messages.xsd"/>
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="SendNotificationSoapIn">
        <wsdl:part name="request" element="tns:SendNotification" />
    </wsdl:message>
    <wsdl:message name="SendNotificationSoapOut">
        <wsdl:part name="SendNotificationResult" element="tns:SendNotificationResult" />
    </wsdl:message>
    <wsdl:portType name="NotificationServicePortType">
        <wsdl:operation name="SendNotification">
            <wsdl:input message="tns:SendNotificationSoapIn" />
            <wsdl:output message="tns:SendNotificationSoapOut" />
        </wsdl:operation>
    </wsdl:portType>


    <wsdl:binding name="NotificationServiceBinding" type="tns:NotificationServicePortType">
        <wsdl:documentation>
            <wsi:Claim conformsTo="http://ws-i.org/profiles/basic/1.0" xmlns:wsi="http://ws-i.org/schemas/conformanceClaim/" />
        </wsdl:documentation>
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />

        <wsdl:operation name="SendNotification">
            <soap:operation soapAction="http://schemas.microsoft.com/exchange/services/2006/messages/SendNotification" />
            <wsdl:input>
                <soap:body use="literal" />
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal" />
            </wsdl:output>
        </wsdl:operation>


    </wsdl:binding>

    <wsdl:binding name="NotificationServiceBinding12" type="tns:NotificationServicePortType">
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />

        <wsdl:operation name="SendNotification">
            <soap12:operation soapAction="http://schemas.microsoft.com/exchange/services/2006/messages/SendNotification" />
            <wsdl:input>
                <soap12:body use="literal" />
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal" />
            </wsdl:output>
        </wsdl:operation>

    </wsdl:binding>

        <wsdl:service name="NotificationServices">
    <wsdl:port name="NotificationServicePort" binding="tns:NotificationServiceBinding">
        <soap:address location="" />
    </wsdl:port>
</wsdl:service>


</wsdl:definitions>

I have also add this, because without it I get a "bind error"

<wsdl:service name="NotificationServices">
    <wsdl:port name="NotificationServicePort" binding="tns:NotificationServiceBinding">
        <soap:address location="" />
    </wsdl:port>
</wsdl:service>

I'm no Pro in SOAP... Whats going wrong here? Thank you Olli


Source: (StackOverflow)

What is DistinguishedFolderId->Mailbox->EmailAddress in php-ews?

I am using a php-ews to access our EWS server. I found an example for creating a calendar event as follows:

$request = new EWSType_CreateItemType();
$request->SavedItemFolderId->DistinguishedFolderId->Id=EWSType_DistinguishedFolderIdNameType::CALENDAR;
$request->SavedItemFolderId->DistinguishedFolderId->Mailbox->EmailAddress = "dude@test.com";
...

My question: what is DistinguishedFolderId->Mailbox->EmailAddress and what does it do? I know this attribute is optional.


Source: (StackOverflow)

Advertisements

Exchange web services (EWS): Send "meeting invitations" for meetings stored in a public folder calendar

It's been discussed already here on stackoverflow ( Appointment.Save and Appointment.Update always set IsMeeting to true ) that EWS has limitations on how meeting invitations can't be sent automatically when creating new calendar items / meetings inside a public folder.

Since I really need to send the meeting to the calendars of the various attendees I was wondering if anybody has ever discovered a workaround for this strange behavior (I can't even find a way to send meeting invitations programmatically).

The only thing that seems to be working is to forward the calendar item to the address of the attendees, but that's really not an option since it only makes the meeting available as an attachment in the email.


Source: (StackOverflow)

How to export Exchange Web Services Item to a *.eml file? (PHP)

I'm developing a web interface for Exchange Web Services which should be able to save a mail item to eml format. I use PHP-EWS (https://github.com/jamesiarmes/php-ews) to establish a connection to the Exchange Server.

I know how such a file looks like, so I could download a mail item and generate an eml template with the data.

But I found this post: Save mail to msg file using EWS API. Colin talks about a mechanism which directly export a mail item into eml file. Is that possible in PHP, too?

Additionally I found another thing: https://github.com/jamesiarmes/php-ews/wiki/Email:-Set-Extended-MAPI-Properties. In this example somebody generates a mime content and set it to a new item. Is it possible to get the mime type (which looks like an eml file to me) for an existing item?

Thanks for any help!


Source: (StackOverflow)

PHPEWS create event on public calendar

I'm attempting to plug a php based calendar management system into exchange 2007 calendars.

I have the below code setup at present.

$subject = 'Appointment with ..';

        $request = new EWSType_CreateItemType();
        $request->Items = new EWSType_NonEmptyArrayOfAllItemsType();
        $request->Items->CalendarItem = new EWSType_CalendarItemType();

        $request->Items->CalendarItem->Subject = $subject;

        $date1 = new DateTime('2015-05-10T15:00:00+03:00');
        $DateStart = $date1->format('Y-m-d H:i:00');
        $date = new DateTime($DateStart);
        $request->Items->CalendarItem->Start = $date->format('c');
        $date1 = new DateTime('2015-05-10T17:00:00+03:00');
        $DateEnd = $date1->format('Y-m-d H:i:00');
        $date = new DateTime($DateEnd);
        $request->Items->CalendarItem->End = $date->format('c');

        $request->Items->CalendarItem->ReminderIsSet = false;

        $request->Items->CalendarItem->ReminderMinutesBeforeStart = 15;

        $request->Items->CalendarItem->Body = new EWSType_BodyType();
        $request->Items->CalendarItem->Body->BodyType = EWSType_BodyTypeType::HTML;

$request->Items->CalendarItem->Body->_ = <<<EOD

    <p><strong>Staff Attending</strong>:bob</p>

EOD;

        $request->Items->CalendarItem->ItemClass = new EWSType_ItemClassType();
        $request->Items->CalendarItem->ItemClass->_ = EWSType_ItemClassType::APPOINTMENT;

        $request->Items->CalendarItem->Sensitivity = new EWSType_SensitivityChoicesType();
        $request->Items->CalendarItem->Sensitivity->_ = EWSType_SensitivityChoicesType::NORMAL;

        $request->Items->CalendarItem->Categories = new EWSType_ArrayOfStringsType();
        $request->Items->CalendarItem->Categories->String = array(
            'Client Meeting (Scheduled)'
        );

        $request->Items->CalendarItem->Location = "Showroom";

        $request->SendMeetingInvitations = EWSType_CalendarItemCreateOrDeleteOperationType::SEND_ONLY_TO_ALL;
        $request->Items->CalendarItem->RequiredAttendees->Attendee[0]->Mailbox->EmailAddress = "user@domain.com";
        $request->Items->CalendarItem->RequiredAttendees->Attendee[0]->Mailbox->RoutingType  = 'SMTP';
        $n = 1;


        $response      = $ews->CreateItem($request);

This will setup an event in the users personal calendar just fine, but what I need to do is to get it to post to a public folder calendar which I have the folderID for.

If anyone could assist it would be greatly appreciated!


Source: (StackOverflow)

PHP-EWS fails on more than one attachment

I use James Armes's PHP-EWS library.

The following code works fine with single attachments, but fails with multiply files.

<?php
$msgRequest->MessageDisposition = 'SaveOnly';

$msgResponse = $ews->CreateItem($msgRequest);
$msgResponseItems = $msgResponse->ResponseMessages->CreateItemResponseMessage->Items;

// Create attachment(s)
$attachments = array();
$i = 0;
foreach ($message_details['attachment'] as $attachment) {
    $attachments[$i] = new EWSType_FileAttachmentType();
    $attachments[$i]->Content = file_get_contents($attachment['path'] . '/' . $attachment['file']);
    $attachments[$i]->Name = $attachment['file'];
    $i++;
}
//
// Attach files to message
$attRequest = new EWSType_CreateAttachmentType();
$attRequest->ParentItemId = $msgResponseItems->Message->ItemId;
$attRequest->Attachments = new EWSType_NonEmptyArrayOfAttachmentsType();
$attRequest->Attachments->FileAttachment = $attachments;

$attResponse = $ews->CreateAttachment($attRequest);
$attResponseId = $attResponse->ResponseMessages->CreateAttachmentResponseMessage->Attachments->FileAttachment->AttachmentId;

// Save message id from create attachment response
$msgItemId = new EWSType_ItemIdType();
$msgItemId->ChangeKey = $attResponseId->RootItemChangeKey;
$msgItemId->Id = $attResponseId->RootItemId;

// Send and save message
$msgSendRequest = new EWSType_SendItemType();
$msgSendRequest->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
$msgSendRequest->ItemIds->ItemId = $msgItemId;
$msgSendRequest->SaveItemToFolder = true;
$msgSendResponse = $ews->SendItem($msgSendRequest);
$response = $msgSendResponse->ResponseMessages->SendItemResponseMessage;
?>

$ews->SendItem() returns this error:

Uncaught SoapFault exception: [a:ErrorSchemaValidation] The request failed schema validation: The required attribute 'Id' is missing.

What do I miss here?


Source: (StackOverflow)

How to catch a calendar item created event using push notifications?

I'm trying to fire an event when I create a calendar item (appointment) in exchange, using PHP-EWS. Currently, I am able to fire an event when an email is sent:

    $subscribe_request = new \EWSType_SubscribeType();
    $pushSubscription = new \EWSType_PushSubscriptionRequestType();
    $pushSubscription->StatusFrequency = 1;
    $pushSubscription->URL = 'http://someserver/log.php';
    $folderIDs = new \EWSType_NonEmptyArrayOfBaseFolderIdsType();
    $eventTypes = new \EWSType_NonEmptyArrayOfNotificationEventTypesType();
    $folderIDs->DistinguishedFolderId = new \EWSType_DistinguishedFolderIdType();
    $folderIDs->DistinguishedFolderId->Id = \EWSType_DistinguishedFolderIdNameType::INBOX;

    $eventTypes->EventType = "NewMailEvent";
    $pushSubscription->FolderIds = $folderIDs;
    $pushSubscription->EventTypes = $eventTypes;
    $subscribe_request->PushSubscriptionRequest = $pushSubscription;

    return $this->ews->Subscribe($subscribe_request);

log.php

class ewsService {
  public function SendNotification($arg) {
    file_put_contents("C:\\exchangelogs\\log_".time().".txt", print_r($arg,1));
    $result = new EWSType_SendNotificationResultType();
    $result->SubscriptionStatus = 'OK';
    //$result->SubscriptionStatus = 'Unsubscribe';
    return $result;
  }
}

$opts = array();
$server = new SoapServer(
  'NotificationService.wsdl', 
  array('uri' => 'http://someserver/log.php'));

$server->setObject($service = new ewsService());
$server->handle();

Every minute a 'Keep alive message' is sent and the SendNotification function is called. The same thing happens when a mail is sent (using outlook or whatever).

This all works fine.

However, now I want to do the same when a calendar item is created, such as an appointment. I tried changing the DistinguishedFolderIdNameType to CALENDAR and the EventType to CreatedEvent, but I receive no message when an appointment is created.

Any help is greatly appreciated.


Source: (StackOverflow)

PHP-EWS Exchange 2010 error on large mailbox

I'm using php-ews to read through a mailbox which has over 1000 on Exchange 2010, I have a function for listing all the emails with the use of EWSType_FindItemType to grab all of the ID keys and store them into an array which I have then used a foreach loop of that array to call another function to grab that email message contents such as body and from email addresses.

I have tested this on a much smaller mailbox and it works perfectly fine with two different tests, one on the same Exchange and one using Exchange 2013 on microsoft 365.

But I keep getting this error when I reach about 300 emails into the array of keys from the last call:

SoapFault exception: [Client] looks like we got no XML document in E:\Development\ExchangeInt\php-ews\ExchangeWebServices.php:17
Stack trace:
#0 E:\Development\ExchangeInt\php-ews\ExchangeWebServices.php(17): SoapClient->__call('GetItem', Array)
#1 E:\Development\ExchangeInt\php-ews\ExchangeWebServices.php(17): NTLMSoapClient_Exchange->GetItem(Object(EWSType_GetItemType))
#2 E:\Development\ExchangeInt\php-ews\ExchangeWebServices.php(694): ExchangeWebServices->__doRequest(Object(EWSType_GetItemType))
#3 E:\Development\ExchangeInt\mail.php(405): ExchangeWebServices->GetItem(Object(EWSType_GetItemType))
#4 E:\Development\ExchangeInt\mail.php(341): Message(Object(Folder), Object(User), 'AAMkAGEzOGJmNjg...')
#5 E:\Development\ExchangeInt\mail.php(800): listFolder(Object(Folder), Object(User))
#6 E:\Development\ExchangeInt\mail.php(99): getFolders(Object(User))
#7 E:\Development\ExchangeInt\exchange.php(38): User->mailboxes()
#8 {main}

I really have no idea what do with this, I keep going round in circles and some help would very helpful. Thanks Guys

My Code: List Emails and grab ID keys -

$request = new EWSType_FindItemType();

$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;

$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;

// Limits the number of items retrieved
$request->IndexedPageItemView = new EWSType_IndexedPageViewType();
$request->IndexedPageItemView->BasePoint = "Beginning";
$request->IndexedPageItemView->Offset = 0; // Item number you want to start at
$request->IndexedPageItemView->MaxEntriesReturned = 500; // Numer of items to return in total

$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;

// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();

// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI = '';
@$order->FieldURI->FieldURI = 'item:DateTimeReceived'; // @ symbol stops the creating default object from empty value error
$order->Order = 'Ascending'; 
$request->SortOrder->FieldOrder[] = $order;

$response = $ews->EX->FindItem($request);

//For Debugging
//die("<pre>" . print_r($arr, 1) . "</pre>");

if(!isset($response->ResponseMessages->FindItemResponseMessage->RootFolder))
{
    $responseMessage = $response->ResponseMessages->FindItemResponseMessage;
    die("<h3 style='text-align: center;'>Email</h3>" . $responseMessage->MessageText . "<br /><br />" . $responseMessage->ResponseCode);
}
else
{
    $totalItems = $response->ResponseMessages->FindItemResponseMessage->RootFolder->TotalItemsInView;
}

$rootFolder = $response->ResponseMessages->FindItemResponseMessage->RootFolder;
$messages = $rootFolder->Items->Message;
$lastItemInRange = $rootFolder->IncludesLastItemInRange;
$i = 1; // Counter to multply the max etries retrurned, to create the offset value

while($lastItemInRange != 1) // While the last item in the inbox is still not in range retrieve the next 1000 messages
{
    $limit = $request->IndexedPageItemView->MaxEntriesReturned;
    $request->IndexedPageItemView->Offset = $limit * $i;
    $response = $ews->EX->FindItem($request);

    $rootFolder = $response->ResponseMessages->FindItemResponseMessage->RootFolder;
    $messages = array_merge($messages, $rootFolder->Items->Message);
    $lastItemInRange = $rootFolder->IncludesLastItemInRange;

    $i++;
}

foreach($messages as $msg)
{
    $arrID;
    $arrID = $msg->ItemId->Id; 
    echo $arrID . "<br>";
    Message($user, $ews, $arrID);
    //echo print_r($msg);
}

die();

Message Function:

function Message($user,$ews,$key) {
    $email = new Email;
    $email->ID = $key;

    // Build the request for the parts.
    $request = new EWSType_GetItemType();
    $request->ItemShape = new EWSType_ItemResponseShapeType();
    $request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;

    // You can get the body as HTML, text or "best".
    $request->ItemShape->BodyType = EWSType_BodyTypeResponseType::TEXT;

    // Add the body property.
    $body_property = new EWSType_PathToUnindexedFieldType();
    $body_property->FieldURI = 'item:Body';
    $request->ItemShape->AdditionalProperties = new EWSType_NonEmptyArrayOfPathsToElementType();
    $request->ItemShape->AdditionalProperties->FieldURI = array($body_property);

    $request->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
    $request->ItemIds->ItemId = array();

    // Add the message to the request.
    $message_item = new EWSType_ItemIdType();
    $message_item->Id = $key;
    $request->ItemIds->ItemId[] = $message_item;

    $response = $ews->EX->GetItem($request);  <-- Breaks Here I Think

    echo print_r($response);

    return;
}

Source: (StackOverflow)

EWS-PHP : get all recurring calendar item

With the EWS-PHP library, I am able to get all events on my Exchange calendar. But I noticed that when there is recurring event, I got only the first occurrence event, and this happens when the CalendarItem has "RecurringMaster" for the "CalendarItemType" property.

My question is how to get all occurrences of a recurring event, in PHP way ?


Source: (StackOverflow)

EWS adresse mail in php

I am using EWS PHP , how to get the email of sender ? I tried this but I got no response.

$item->Organizer->Mailbox->MailAdresse

Source: (StackOverflow)

Unexpected element in result of EWS FindItem with GroupBy

I'm using EWS (Exchange Web Services) to access data from my Exchange 2013 test Server. I'm doing this using PHP with the (somewhat dated) php-ews repository: github-jamesiarmes-php-ews and the newer and composer enabled version: github-deakin-php-ews

I can do the basic calls to my Exchange service as described in the wiki from 'jamesiarmes', but ran in to some troubles when I tried to use the GroupBy method: How to: Perform grouped searches by using EWS in Exchange

As you can see in the XML response from the How-to guide, normally the <Groups> element should contain zero or more <GroupItems> who would then contain the items (in my case CalendarItems). But what I got back from my test server were <Group> elements in stead of <GroupItems> which caused my $response object to be incomplete.

The code I used:

$request = new FindItemType();
$request->Traversal = ItemQueryTraversalType::SHALLOW;
$request->ItemShape = new ItemResponseShapeType();
$request->ItemShape->BaseShape = DefaultShapeNamesType::ALL_PROPERTIES;

// Define the time frame to load calendar items
$request->CalendarView = new CalendarViewType();
$request->CalendarView->StartDate = '2014-01-12T15:18:34+03:00';
$request->CalendarView->EndDate = '2015-01-12T15:18:34+03:00';

// Find events from a certain folders
$request->ParentFolderIds = new NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->FolderId = new FolderIdType();
$request->ParentFolderIds->FolderId->Id = $calendarFolderUID;

// Group the events by date
$request->GroupBy = new GroupByType();
$request->GroupBy->Order = 'Ascending';
$request->GroupBy->FieldURI = new FieldURIOrConstantType();
$request->GroupBy->FieldURI->FieldURI = 'calendar:Start';
$request->GroupBy->AggregateOn = new AggregateOnType();
$request->GroupBy->AggregateOn->Aggregate = 'Minimum';
$request->GroupBy->AggregateOn->FieldURI = new FieldURIOrConstantType();
$request->GroupBy->AggregateOn->FieldURI->FieldURI = 'calendar:End';

$response = $this->soapService->FindItem($request);

This is the var_dump() from $response:

object(stdClass)#685 (1) {
  ["ResponseMessages"]=>
  object(stdClass)#690 (1) {
    ["FindItemResponseMessage"]=>
    object(stdClass)#714 (3) {
      ["ResponseCode"]=>
      string(7) "NoError"
      ["ResponseClass"]=>
      string(7) "Success"
      ["RootFolder"]=>
      object(stdClass)#715 (3) {
        ["Groups"]=>
        object(stdClass)#716 (0) {
        }
        ["IncludesLastItemInRange"]=>
        bool(true)
        ["TotalItemsInView"]=>
        int(4)
      }
    }
  }
}

I managed to collect the XML response using __getLastResponse() (PHP docs) and found it did get all the wanted items, but in the <Group> element instead of the <GroupItems>which cased the SoapClient to return an empty object for the <Groups> element.

Now I'm wondering where the problem lies:

  1. Is the How-to Guide outdated? I didn't find any reference to this <Group> element in the other documentation from EWS, so I don't think that is the issue.
  2. Is my Exchange server using another XML schema or just plain weird?
  3. Are the php-ews schemas outdated? Should I fork the 'deakin' repo with an eventual solution?

I already found a way to make it work by adjusting the php-ews schemas, but if the problem is my test server, I don't need to bother making a fork... I'll post my current solution below also.

I would appreciate any input on this....


Source: (StackOverflow)

php-ews: Access shared calendars?

Using php-ews: https://github.com/jamesiarmes/php-ews

I'm able to list events from my own calendar according to this example: https://github.com/jamesiarmes/php-ews/wiki/Calendar:-Get-List-(Retrieving-Id-and-ChangeKey) But after searching for a solution for a few hours I still haven't been able to find a way to access shared calendars.

This question is similar, but has no answer: EWS: Access shared calendars

From looking at that and various other search results (I've googled many variants of "ews shared calendar") I have to find the location of the shared calendar, get the id and then use that. But I haven't been able to do that. Can anyone help?


Source: (StackOverflow)

Not collected Exception: Wrong Version PHP-EWS

Im trying to connect with the PHP-EWS and my Exchange server. I use the Script from https://github.com/jamesiarmes/php-ews/wiki

But everytime i load my script the browser tells me

Not collected Exception: Wrong Version

Here is my script (The Autoloader is in a extra File so dont worry it works)

$server = "***********";
$username="***********";
$password="*******";
$version= "2010"; // or Exchange 2010; Exchange 2010 SP1

$ews = new ExchangeWebServices($server, $username, $password, $version);


$request = new EWSType_FindFolderType();
$request->Traversal = EWSType_FolderQueryTraversalType::SHALLOW;
$request->FolderShape = new EWSType_FolderResponseShapeType();
$request->FolderShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;

// configure the view
$request->IndexedPageFolderView = new EWSType_IndexedPageViewType();
$request->IndexedPageFolderView->BasePoint = 'Beginning';
$request->IndexedPageFolderView->Offset = 0;

// set the starting folder as the inbox
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;

// make the actual call
$response = $ews->FindFolder($request);

?>

Does anybody know why i keep getting

Not collected Exception: Wrong Version

and knew what to do?


Source: (StackOverflow)

php-ews how to set importance when sending an e-mail

I am using php-ews to send mails and I cannot find a way to set the importance (priority) of a mail. Here is my code:



    $from = $mail['from'];
    $to = $mail['to'];
    $subject = $mail['subject'];
    $body = $mail['body'];

    $msg = new EWSType_MessageType();
    if($to && count($to) > 0){
        $toAddresses = $this->getAddresses($to);
        $msg->ToRecipients = $toAddresses;
    }

    $fromAddress = new EWSType_EmailAddressType();
    $fromAddress->EmailAddress = $from['mail'];
    $fromAddress->Name = $from['name'];

    $msg->From = new EWSType_SingleRecipientType();
    $msg->From->Mailbox = $fromAddress;

    $msg->Subject = $subject;

    $msg->Body = new EWSType_BodyType();
    $msg->Body->BodyType = 'HTML';
    $msg->Body->_ = $body;

    $msgRequest = new EWSType_CreateItemType();
    $msgRequest->Items = new EWSType_NonEmptyArrayOfAllItemsType();

    $msgRequest->Items->Message = $msg;
    $msgRequest->MessageDisposition = 'SendAndSaveCopy';
    $msgRequest->MessageDispositionSpecified = true;

    $response = $this->ews->CreateItem($msgRequest);
    return $response;

Thank you in advance for your response!


Source: (StackOverflow)

Exception handling ExchangeWebServices php-ews

I use https://github.com/jamesiarmes/php-ews library to access my exchange account.

If I used correct credentials to create a ExchangeWebServices object, I get accurate response.

$ews = new ExchangeWebServices("outlook.office365.com", "tes@abc.com", "test123");

$request = new EWSType_FindItemType();

$response = $ews->FindItem($request);

But If the credentials are wrong it breaks the site by throwing an exception as

EWS_Exception: SOAP client returned status of 401 in ExchangeWebServices->processResponse() 

Is there any way to get the response as "failed" or some boolean value instead of the error message?


Source: (StackOverflow)