0
votes

I created a web application that is using the outlook rest api V2.0. I can authenticate the user en get the mail massages en calendar items. Problem is when i want to send a mail i am getting http error 400.

My outlook.php file

<?php



 class OutlookService 
 {
    private static $outlookApiUrl = "https://outlook.office.com/api/v2.0";
    		
	public static function stuurEmail($access_token, $user_email, $data) 
			{
			
			
			$getMessagesUrl = self::$outlookApiUrl."/Me/sendmail?".http_build_query($data);

			return self::makeApiCall($access_token, $user_email, "POST", $getMessagesUrl);
			
			}	
	 
	 
	 
	 
	 public static function sendMail ($access_token,$user_email)
			{
				$sentMessagesParameters = '{"Message":{"Subject":"Meet for lunch?","Body":{"ContentType":"Text","Content":"The new cafeteria is open."},"ToRecipients":[{"EmailAddress":{"Address":"[email protected]"}}]},"SaveToSentItems":"true"}';
			
			
			

			$json=json_encode($sentMessagesParameters, true);

			 $getMessagesUrl = self::$outlookApiUrl."/me/sendmail?".http_build_query($sentMessagesParameters);


			return self::makeApiCall($access_token, $user_email, "POST",$getMessageUrl,$json);

			} 
	 
	 
	 public static function getPhoto($access_token) 
			{
			  $getUserParameters = array (
				// Only return the user's display name and email address
				"\$select" => "Photo"
			  );

			  $getUserUrl = self::$outlookApiUrl."/Me?".http_build_query($getUserParameters);

			  return self::makeApiCall($access_token, "", "GET", $getUserUrl);
		 
		 
		 
			}
	 
	 public static function getUser($access_token) 
			{
			  $getUserParameters = array 
				(
				// Only return the user's display name and email address
				"\$select" => "DisplayName,EmailAddress,Alias"
			  );

			  $getUserUrl = self::$outlookApiUrl."/Me?".http_build_query($getUserParameters);

			  return self::makeApiCall($access_token, "", "GET", $getUserUrl);
			}

    public static function getMessages($access_token, $user_email) 
			{
			  $getMessagesParameters = array (
				// Only return Subject, ReceivedDateTime, and From fields
				"\$select" => "Subject,ReceivedDateTime,From",
				// Sort by ReceivedDateTime, newest first
				"\$orderby" => "ReceivedDateTime DESC",
				// Return at most 10 results
				"\$top" => "10"
			  );

			  $getMessagesUrl = self::$outlookApiUrl."/Me/MailFolders/Inbox/Messages?".http_build_query($getMessagesParameters);

			  return self::makeApiCall($access_token, $user_email, "GET", $getMessagesUrl);
			}
    
    public static function getEvents($access_token, $user_email) 
			{
			  $getEventsParameters = array (
				// Only return Subject, Start, and End fields
				"\$select" => "Subject,Start,End",
				// Sort by Start, oldest first
				"\$orderby" => "Start/DateTime",
				// Return at most 10 results
				"\$top" => "10"
			  );

			  $getEventsUrl = self::$outlookApiUrl."/Me/Events?".http_build_query($getEventsParameters);

			  return self::makeApiCall($access_token, $user_email, "GET", $getEventsUrl);
			}
    
    public static function getContacts($access_token, $user_email) 
			{
			  $getContactsParameters = array (
				// Only return GivenName, Surname, and EmailAddresses fields
				"\$select" => "GivenName,Surname,EmailAddresses",
				// Sort by GivenName, A-Z
				"\$orderby" => "GivenName",
				// Return at most 10 results
				"\$top" => "10"
			  );

			  $getContactsUrl = self::$outlookApiUrl."/Me/Contacts?".http_build_query($getContactsParameters);

			  return self::makeApiCall($access_token, $user_email, "GET", $getContactsUrl);
			}
    
    public static function makeApiCall($access_token, $user_email, $method, $url, $payload = NULL) 
			{
			  // Generate the list of headers to always send.
			  $headers = array(
				"User-Agent: php-tutorial/1.0",         // Sending a User-Agent header is a best practice.
				"Authorization: Bearer ".$access_token, // Always need our auth token!
				"Accept: application/json",             // Always accept JSON response.
				"client-request-id: ".self::makeGuid(), // Stamp each new request with a new GUID.
				"return-client-request-id: true",       // Tell the server to include our request-id GUID in the response.
				"X-AnchorMailbox: ".$user_email         // Provider user's email to optimize routing of API call
			  );

			  $curl = curl_init($url);

			  switch(strtoupper($method)) {
				case "GET":
				  // Nothing to do, GET is the default and needs no
				  // extra headers.
				  error_log("Doing GET");
				  break;
				case "POST":
				  error_log("Doing POST");
				  // Add a Content-Type header (IMPORTANT!)
				  $headers[] = "Content-Type: application/json";
				  curl_setopt($curl, CURLOPT_POST, true);
				  curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
				  break;
				case "PATCH":
				  error_log("Doing PATCH");
				  // Add a Content-Type header (IMPORTANT!)
				  $headers[] = "Content-Type: application/json";
				  curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
				  curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
				  break;
				case "DELETE":
				  error_log("Doing DELETE");
				  curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
				  break;
				default:
				  error_log("INVALID METHOD: ".$method);
				  exit;
			  }

			  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
			  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
			  $response = curl_exec($curl);
			  error_log("curl_exec done.");

			  $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			  error_log("Request returned status ".$httpCode);

			  if ($httpCode >= 400) {
				return array('errorNumber' => $httpCode,
							 'error' => 'Request returned HTTP error '.$httpCode);
			  }

			  $curl_errno = curl_errno($curl);
			  $curl_err = curl_error($curl);

			  if ($curl_errno) {
				$msg = $curl_errno.": ".$curl_err;
				error_log("CURL returned an error: ".$msg);
				curl_close($curl);
				return array('errorNumber' => $curl_errno,
							 'error' => $msg);
			  }
			  else {
				error_log("Response: ".$response);
				curl_close($curl);
				return json_decode($response, true);
			  }
			}
    
    // This function generates a random GUID.
    public static function makeGuid()
			{
				if (function_exists('com_create_guid')) {
				  error_log("Using 'com_create_guid'.");
				  return strtolower(trim(com_create_guid(), '{}'));
				}
				else {
				  error_log("Using custom GUID code.");
				  $charid = strtolower(md5(uniqid(rand(), true)));
				  $hyphen = chr(45);
				  $uuid = substr($charid, 0, 8).$hyphen
						 .substr($charid, 8, 4).$hyphen
						 .substr($charid, 12, 4).$hyphen
						 .substr($charid, 16, 4).$hyphen
						 .substr($charid, 20, 12);

				  return $uuid;
				}
			}
  }
?>

So in my home.php file i have the following code for sending the mail

if(isset($_POST['mailing']))
{				
    @extract($_POST);

      $arr = '{
      "Message": {
      "Subject": "Meet for lunch?",
      "Body": {
        "ContentType": "Text",
        "Content": "The new cafeteria is open."
      },
      "ToRecipients": [
        {
        "EmailAddress": {
          "Address": "[email protected]"
        }
        }
      ]
      },
      "SaveToSentItems": "true"
    }';
    $data=json_encode($arr, true);

    $message = OutlookService::stuurEmail(oAuthService::getAccessToken($redirectUri), $_SESSION['user_email'], $data);

    print_r($message);



    echo"
      <div class='alert alert-success'>
      <a href='#' title='Sluit deze melding'
      class='close' data-dismiss='alert' aria-label='close'>&times;
      </a>

      <br>".$_SESSION['access_token']."<br>".$_SESSION['user_email']."<br>$data<br>


      </div>

      ";

}

When i wont to sent a mail i am getting the following error:

Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given in /var/www/vhosts/rkgvlaande05001/test/outlook.php on line 14 Array ( [errorNumber] => 400 [error] => Request returned HTTP error 400 )

Any idea what not right in the code or has anyone has a working example for the outlook rest api V2.0?

Thx

1

1 Answers

0
votes

I checked you code and the sentMessagesParameters content is correct. However, I found this post mentioned, "you need to 'send mail as a user' permission for O365 Exchange Online in Azure AD if you want to send a mail message with REST API ". Please see the following link:

Outlook Rest Api sending Mail Request returned status 400