I am trying to send an email using the Microsoft Graph API through the Laravel app; this is the code
$emailData = [
"message" => [
"subject" => 'Test',
"body" => [
"contentType" => "text",
"content" => "Test Email!"
],
"toRecipients" => [
[
"emailAddress" => [
"address" => "test@gmail.com"
]
]
],
"from" => [
"emailAddress" => [
"address" => "test@hotmail.com"
]
]
]
];
$response = Http::withToken($this->token)
->withHeaders(['Content-Type' => 'application/json'])
->post("https://graph.microsoft.com/v1.0/users/test@hotmail.com/sendMail", json_encode($emailData));
I have already obtained access and refresh tokens.
I only get this from response
{"error":{"code":"ErrorInternalServerError","message":"An internal server error occurred. The operation failed."}}
I assume the problem might be with data structure, but I couldn't find it.
Any help is appreciated!
The problem lies in your HTTP
client. Laravel HTTP
client automatically handles the encoding of the data as JSON
when sending a POST
request. So in your case your $emailData
is being double encoded since you already passed the json_encode($emailData)
to the post(...
.
Correct syntax would be. Try this.
$response = Http::withToken($this->token)
->withHeaders(['Content-Type' => 'application/json'])
->post("https://graph.microsoft.com/v1.0/users/test@hotmail.com/sendMail",[
"key-name"=> $emailData ]);
post(..)
accept an array of data as their second argument.For detailed information check the official-docs