Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

php ews Copy Message from inbox to other user's inbox #43

Closed
sklicek opened this issue Jun 8, 2016 · 5 comments
Closed

php ews Copy Message from inbox to other user's inbox #43

sklicek opened this issue Jun 8, 2016 · 5 comments

Comments

@sklicek
Copy link

sklicek commented Jun 8, 2016

With php-ews is there a possibility to copy a message from an inbox to other user's inbox?

The goal is that a message is created by php-ews in a web interface, saved to a shared inbox and after this save a copy of the message to user's inbox.

The problem is in converting message-ID from Exchange 2013 in function convert_id()

My code so far:

function getEmailsBWOtoPublicFolder($db, $link){
    //user with full access to exchange-server
    $host = "xxx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxxxxxx";

        $ews = new ExchangeWebServices($host, $username, $password, ExchangeWebServices::VERSION_2007_SP1);

    //get folders in SENT_ITEMS
    $request = new EWSType_FindItemType();
    $request->ItemShape = new EWSType_ItemResponseShapeType();
    $request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_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 = 1000; // Numer of items to return in total

    // Point to the attendee (shared) outbox.
    $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->FindItem($request);

    // Loop through each item if event(s) were found in the timeframe specified
    $mail_items = array();
    if ($response->ResponseMessages->FindItemResponseMessage->ResponseCode == "NoError") {
        $count=$response->ResponseMessages->FindItemResponseMessage->RootFolder->TotalItemsInView;
        if ($count>0){
            if (!is_array($response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message)) {
                $mail_items[] = $response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message;
            } else {
                $mail_items = $response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message;
            }
        }
    }

    for ($i=0;$i<count($mail_items);$i++){
        $id = $mail_items[$i]->ItemId->Id;
        $change_key = $mail_items[$i]->ItemId->ChangeKey;
        $subject = $mail_items[$i]->Subject;
        $usermail = $mail_items[$i]->From;
             if (stristr($subject,$num_project)!==false){         
                //create folder in user outbox
                create_folder_user_outbox($usermail, $num_project);

               //save Email to User Folder
          $arr_user=find_folder_user_outbox($usermail, $num_project);
              $user_folder_id=$arr_user[0];
              $user_folder_ckey=$arr_user[1];

              //there is my problem: i get 'id is missing' error message
              saveEmailUserFolder($id, $change_key, $user_folder_id, $user_folder_ckey, $usermail);
         }
     }
}
//******************************************
//create folder in user sent items
//******************************************
function create_folder_user_outbox($email_search, $num_project){
    //user with full access to exchange-server
    $host = "xxx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxxxxxxxx";

    //write in this calendar    
    $email_of_attendee=$email_search;

    date_default_timezone_set('Europe/Berlin');

    // Create the service object            
    $ews = new ExchangeWebServices($host, $username, $password);

    //create folder in user outbox
    $request = new EWSType_CreateFolderType();
    $request->Folders = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
    $request->Folders->Folder = new EWSType_FolderType();
    $request->Folders->Folder->DisplayName = $num_project;
    $request->Folders->Folder->FolderClass = 'IPF.Note';

    $request->ParentFolderId = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
    $request->ParentFolderId->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
    $request->ParentFolderId->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::SENT;
    $request->ParentFolderId->DistinguishedFolderId->Mailbox = new StdClass;
    $request->ParentFolderId->DistinguishedFolderId->Mailbox->EmailAddress = $email_of_attendee;
    $response = $ews->CreateFolder($request);
}
//******************************************
//create folder in user sent items
//******************************************
function find_folder_user_outbox($email_search, $num_project){
    //user with full access to exchange-server
    $host = "xxx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxxxxxxx";

    // Create the service object            
    $ews = new ExchangeWebServices($host, $username, $password);    

    //write in this calendar    
    $email_of_attendee=$email_search;

    date_default_timezone_set('Europe/Berlin');

    //get folders in SENT_ITEMS
    $request = new EWSType_FindFolderType();
    $request->Traversal = EWSType_FolderQueryTraversalType::DEEP; 
    $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;

    $request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
    $request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
    $request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::SENT;
    $request->ParentFolderIds->DistinguishedFolderId->Mailbox = new StdClass;
    $request->ParentFolderIds->DistinguishedFolderId->Mailbox->EmailAddress = $email_of_attendee;
    // make the actual call
    $response = $ews->FindFolder($request);

    // Loop through each item if event(s) were found in the timeframe specified
    $folder_items = array();
    if ($response->ResponseMessages->FindFolderResponseMessage->ResponseCode == "NoError") {
        $count=$response->ResponseMessages->FindFolderResponseMessage->RootFolder->TotalItemsInView;
        if ($count>0){
            if (!is_array($response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder)) {
                $folder_items[] = $response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder;
            } else {
                $folder_items = $response->ResponseMessages->FindFolderResponseMessage->RootFolder->Folders->Folder;
            }
        }
    }

    for ($i=0;$i<count($folder_items);$i++){
        $project_folder_id = $folder_items[$i]->FolderId->Id;
        $project_folder_ckey = $folder_items[$i]->FolderId->ChangeKey;
        $displayname=$folder_items[$i]->DisplayName;

        if (stristr($displayname,$num_project)!==false){
            return array($project_folder_id, $project_folder_ckey);
            //echo $project_folder_id.' ';
            break;
        }
    }
}
//***************************************************
//save message to given folder (user folder)
//***************************************************
function saveEmailUserFolder($message_id, $msg_ckey, $project_folder_id, $project_folder_ckey, $usermail){
    require_once('convert_id.php');
    // Define EWS
    //user with full access to exchange-server
    $host = "xxx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxxxxxxxx";

    $ews = new ExchangeWebServices($host, $username, $password, ExchangeWebServices::VERSION_2007_SP1);

     //there is my problem: i get 'id is missing' error message with convertID
    echo "message_id=".$message_id.'<br>';
    $message_id_converted=convert_id($message_id, $msg_ckey, $usermail);
    //echo "$message_id_converted=".$message_id_converted.'<br>';
    $message_id=$message_id_converted;
    /*
    echo "folder_id=".$project_folder_id.'<br>';
    $project_folder_id_converted=convert_id($project_folder_id, $project_folder_ckey, $usermail);
    //echo "$message_id_converted=".$message_id_converted.'<br>';
    $project_folder_id=$project_folder_id_converted;
    */
    $request = new EWSType_CopyItemType();  
    $request->ToFolderId = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
    $request->ToFolderId->FolderId = new EWSType_FolderIdType();
    $request->ToFolderId->FolderId->Id = $project_folder_id;
    $request->ToFolderId->FolderId->ChangeKey = $project_folder_ckey;

    $request->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
    $request->ItemIds->ItemId = new EWSType_ItemIdType();
    $request->ItemIds->ItemId->Id = $message_id;
    $request->ItemIds->ItemId->ChangeKey = $msg_ckey;

    // Generic execution sample code
    $response = $ews->CopyItem($request);
    //echo '<pre>'.print_r($response,1).'</pre>';
}

file convert_id.php contains the converter function:

require_once "vendor/autoload.php";
use garethp\ews\API\Type;
use garethp\ews\API\Enumeration;
use garethp\ews\Mail\MailAPI as API;

function convert_id($ews2007Id, $changeKey, $usermail){
    $host = "xxx.xxx.xxx.xxx";
    $username = "xxx";
    $password = "xxxxxxxxx";

    //Create and build the client
    $api = API::withUsernameAndPassword($host, $username, $password);

    $ews2007ItemId = new Type\ItemIdType($ews2007Id, $changeKey);
    $ews2010ItemId = $api->convertIdFormat(
        $ews2007ItemId,
        Enumeration\IdFormatType::EWS_LEGACY_ID,
        Enumeration\IdFormatType::EWS_ID,
        $usermail
    );

    return $ews2010ItemId;
}
@Garethp
Copy link
Owner

Garethp commented Jun 8, 2016

Try changing return $ews2010ItemId; to return $ews2010ItemId->getItemId()

@sklicek
Copy link
Author

sklicek commented Jun 9, 2016

I get still the error that Id is malformed. Here is the message-ID to convert and the error with stacktrace:

message_id=AAMkAGNkOGRhZTMyLTBiNzAtNDhkNS05ZDhkLTg0Yjg3MDg2NTQ0NABGAAAAAACff7a4yIddSrJmA51rrq6YBwCmngR8iTVkSIs9XxAAR0L0AAAAAAEMAACmngR8iTVkSIs9XxAAR0L0AAAMM6NyAAA=

PHP Fatal error: Uncaught exception 'garethp\ews\API\Exception\ExchangeException' with message 'Id is malformed.' in C:\Bitnami\wampstack-5.5.26-0\apache2\htdocs\best_portal_test\include\vendor\garethp\php-ews\src\API\ExchangeWebServices.php:426
Stack trace:
#0 C:\Bitnami\wampstack-5.5.26-0\apache2\htdocs\best_portal_test\include\vendor
garethp\php-ews\src\API\ExchangeWebServices.php(385): garethp\ews\API\ExchangeWe
bServices->getItemsFromResponse(Object(garethp\ews\API\Message\ConvertIdResponse
MessageType))
#1 C:\Bitnami\wampstack-5.5.26-0\apache2\htdocs\best_portal_test\include\vendor
garethp\php-ews\src\API\ExchangeWebServices.php(393): garethp\ews\API\ExchangeWe
bServices->drillDownResponseLevels(Object(garethp\ews\API\Message\ConvertIdRespo
nseMessageType))
#2 C:\Bitnami\wampstack-5.5.26-0\apache2\htdocs\best_portal_test\include\vendor
garethp\php-ews\src\API\ExchangeWebServices.php(373): garethp\ews\API\ExchangeWe
bServices->drillDownResponseLevels(Object(garethp\ews\API\Message\ArrayOfRespons
eMessagesType))
#3 C:\Bitnami\w in C:\Bitnami\wampstack-5.5.26-0\apache2\htdocs\best_portal_test
\include\vendor\garethp\php-ews\src\API\ExchangeWebServices.php on line 426

@Garethp
Copy link
Owner

Garethp commented Jun 9, 2016

You're fetching the ItemId's straight from the server, instead of storing them in your DB. Why don't you just specify the same Exchange version in every client you create. In some places you do $ews = new ExchangeWebServices($host, $username, $password, ExchangeWebServices::VERSION_2007_SP1);, in other you don't specify the version at all. Try getting them all on the same version, and then you shouldn't need to do any conversion

@sklicek
Copy link
Author

sklicek commented Jun 9, 2016

Ok thanks. Now it works! You've found my problem! My error was, that I had forgotten to give always the exchange version in my clients.

@Garethp
Copy link
Owner

Garethp commented Jun 9, 2016

I would highly recommend you swap all of that to my library by the way. It will cut down your code a lot

@Garethp Garethp closed this as completed Jun 9, 2016
@hehol hehol mentioned this issue Jun 13, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants