【发布时间】:2016-12-21 05:49:25
【问题描述】:
我正在尝试使用 PHP 在https://msdn.microsoft.com/office/office365/APi/mail-rest-operations#SendMessageOnTheFly 上按照带有附件的文档发送电子邮件。到目前为止,我可以发送一封没有附件的普通电子邮件。但是我该如何处理附件呢?
根据文档,响应应该是这样的:
POST https://outlook.office.com/api/v2.0/me/sendmail
{
"Message": {
"Subject": "Meet for lunch?",
"Body": {
"ContentType": "Text",
"Content": "The new cafeteria is open."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "garthf@a830edad9050849NDA1.onmicrosoft.com"
}
}
],
"Attachments": [
{
"@odata.type": "#Microsoft.OutlookServices.FileAttachment",
"Name": "menu.txt",
"ContentBytes": "bWFjIGFuZCBjaGVlc2UgdG9kYXk="
}
]
},
"SaveToSentItems": "false"
}
我拥有的是这样的:
public static function sendMessage($access_token, $user_email, $subject, $Content, $email)
{
$url = "https://example.com/upload.txt";
$base64 = base64_encode(file_get_contents($url));
$arr= array(
"Message" =>array(
'Subject' => $subject,
"Body"=>array(
"ContentType"=>"HTML",
"Content"=>$Content,
),
"ToRecipients"=>array(
array(
"EmailAddress"=>array(
"Address"=>$email,
)
),
),
"Attachments"=> array(
array(
"@odata.type"=> "#Microsoft.OutlookServices.FileAttachment",
"Name" => "upload.txt",
"ContentLocation"=> $url,
"ContentBytes"=> $base64,
"ContentType" => "text/plain"
)
)
));
$json=json_encode($arr, true);
$getMessagesUrl = self::$outlookApiUrl."/me/sendmail";
return self::makeApiCall($access_token, $user_email, "POST",$getMessagesUrl,$json);
}
然后我在外面调用方法:
var_dump(OutlookService::sendMessage($tokens['access_token'], $_SESSION['user_email'], 'subject', 'body', 'abc@gmail.com'));
我对此一无所知。这不起作用,并给我一个 400 错误。我知道 400 错误,但不知道是什么原因造成的。
我应该在这里做什么?正确的格式是什么?
【问题讨论】:
-
在oauthplay.azurewebsites.net 尝试您的请求总是一个好主意,它有助于快速调整并查看有效的方法。我运行了您的 JSON 有效负载生成代码并将生成的 JSON 放入沙箱中,它运行良好,因此可能与您传输数据的方式或有关您的文件的某些内容有关。
-
请注意,400 错误通常具有包含错误信息的响应正文。这可能会提供一个线索。
-
@JasonJohnston 您的第二条评论是我的暗示。 400 错误确实包含有关该错误的信息。出于某种原因,我在真实代码中将
SavetoSentItems放入Json 数组时犯了一个错误,我认为它出于某种原因在正确的位置。非常感谢您的帮助。 -
酷!您应该在此处发布详细信息作为答案以帮助其他人:)
-
@JasonJohnston 是的,我在写这篇文章时就这样做了。
标签: php email outlook-restapi