如何使用Office365 REST API发送邮件?

时间:2018-12-09 19:37:12

标签: php office365 office365api outlook-restapi

我正在使用Office365 REST API。我在发送电子邮件时遇到问题。我在核心php中找不到任何帮助。

我能够访问邮件和附件,但无法发送邮件。到目前为止,这是我尝试过的。

// SEND MAIL FUNCTION

if(isset($_GET['send_email'])){
$resuu = "okay";
$resuu = SendMail();
echo $resuu;

}
function SendMail(){

$userID = get_user_id();

$headers = array(
                            "User-Agent: php-tutorial/1.0",         
                            "Authorization: Bearer ".token()->access_token, 
                            "Accept: application/json",             
                            "client-request-id: ".makeGuid(), 
                            "return-client-request-id: true", 
                            "X-AnchorMailbox: ". get_user_email()
);
$newmail = '{
"Message": {
  "Subject": "Sending 1st email dont fails plz?",
  "Body": {
  "ContentType": "Text",
  "Content": "The new cafeteria is open."
   },
 "ToRecipients": [
   {
      "EmailAddress": {
         "Address": "chxanu123@gmail.com"
       }
     }
    ]
   },
  "SaveToSentItems": "true"
}';
    $outlookApiUrl = $_SESSION["api_url"] . "/Users('$userID')/sendmail";
    $response = runCurl($outlookApiUrl, $newmail, $headers);
    return $response;
    //Session[api_url] contains $_SESSION["api_url"] = //"https://outlook.office.com/api/v2.0";
    }

 ?>

这是我用来访问邮件的运行curl方法

function runCurl($url, $post = null, $headers = null) {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_POST, $post == null ? 0 : 1);
 if($post != null) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
 }
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  if($headers != null) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 }
 $response = curl_exec($ch);
 $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);
 if($http_code >= 400) {
     echo "Error executing request to Office365 api with error 
 code=$http_code<br/><br/>\n\n";
     //echo "<pre>"; print_r($response); echo "</pre>";
     die();
 }
return $response;
}

1 个答案:

答案 0 :(得分:0)

您得到什么错误响应?您是否有HTTP响应标头,或者它在离开您的包装箱之前就失败了?

使用REST的一件事-不需要X-AnchorMailbox。这是一个EWS概念。目标邮箱始终位于URL中,我们的前端服务器将忽略您在REST API的X-AnchorMailbox标头中输入的内容。但这不是您失败的原因。