Search code examples
phplaravelmicrosoft-graph-api

Internal server error when trying to send an email using Microsoft Graph API


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" => "[email protected]" 
                        ] 
                    ] 
                ], 
                "from" => [
                        "emailAddress" => [
                            "address" => "[email protected]" 
                        ] 
                ] 
            ]
        ];
       
        $response = Http::withToken($this->token)
            ->withHeaders(['Content-Type' => 'application/json'])
            ->post("https://graph.microsoft.com/v1.0/users/[email protected]/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!


Solution

  • 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/[email protected]/sendMail",[
    "key-name"=> $emailData ]);
    

    post(..) accept an array of data as their second argument.For detailed information check the official-docs