How to send a mail using ms graph api in laravel

How to Send Emails Using Microsoft Graph API in Laravel


In this post, you will be learning how to send an mail (Outlook Mail) using Microsoft MS Graph API in Laravel step by step.

Before sending any mail using MS Graph API, you have to get the "access token" of Microsoft Graph. (Here is the link - How to get access token using MS Graph API in Laravel)

We will be working on sending mail and also with BCC, CC, Attachments too. 


Step 1: Create a Controller named MsGraphController.php and paste the below code to send mail using ms graph api.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

class MsGraphController extends Controller
{
    public function sendMail(Request $request)
    {
        $user = Auth::user();
        if(!$user->msGraphToken){
            return response()->json([
                'message' => 'Access token not found'
            ], 401);
        }

        $accessToken = $user->msGraphToken->access_token; //Provide your access Token

        $request->validate([
            'to_email' => 'required|email',
            'cc_emails' => 'sometimes|array',
            'bcc_emails' => 'sometimes|array',
            'subject' => 'required|string|max:255',
            'body' => 'required',
        ]);

        // Prepare the request body
        $message = [
            'subject' => $request->subject,
            'body' => [
                'contentType' => 'html', //html,
                'content' => $request->body,
            ],
            'toRecipients' => [
                ['emailAddress' => ['address' => $request->to_email]],
            ],
        ];

        // Include ccRecipients if provided
        if ($request->filled('cc_emails')) {
            $message['ccRecipients'] = [];
            foreach ($request->cc_emails as $ccEmail) {
                $message['ccRecipients'][] = ['emailAddress' => ['address' => $ccEmail]];
            }
        }

        // Include bccRecipients if provided
        if ($request->filled('bcc_emails')) {
            $message['bccRecipients'] = [];
            foreach ($request->bcc_emails as $bccEmail) {
                $message['bccRecipients'][] = ['emailAddress' => ['address' => $bccEmail]];
            }
        }

        // Include attachments if provided
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $attachment) {
                $attachmentContent = base64_encode(file_get_contents($attachment->path()));
                $message['attachments'][] = [
                    "@odata.type" => "#microsoft.graph.fileAttachment",
                    "name" => $attachment->getClientOriginalName(),
                    "contentBytes" => $attachmentContent
                ];
            }
        }

        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $accessToken,
                            'Content-Type' => 'application/json',
                        ])->post('https://graph.microsoft.com/v1.0/me/sendMail', [
                            'message' => $message,
                        ]);

        if ($response->successful()) {

            return response()->json([
                'message' => 'Email sent',
                'status' => 200,
            ]);

        } else {

            $errorMessage = $response->json();
            return response()->json([
                'error' => 'Failed to send message: '.$errorMessage,
                'status' => $response->status()
            ]);
        }
    }
}


Step 2: Create an API in following path: routes/api.php 

use App\Http\Controllers\MsGraphController;

Route::prefix('v1/ms-graph')->group( function () {

    Route::post('/email/send', [MsGraphController::class, 'sendMail']);

});


Step 3: Input fields allowed to send a mail. you can also see these field in controller while validation.

  1. input name: to_email | Validation: Mandatory, Email only, string input. ( Eg: name="to_email" )
  2. input name: cc_emails | Validation: Not Mandatory, array input. ( Eg: name="cc_emails[]" )
  3. input name: bcc_emails | Validation: Not Mandatory, array input. ( Eg: name="bcc_emails[]" ) 
  4. input name: subject | Validation: Mandatory, string value, max 255 words. ( Eg: name="subject" )
  5. input name: body | Validation: Mandatory, string & html value. ( Eg: name="body" )


That's it. you are ready to use this functionality to get send mail using MS Graph API in Laravel with Access Token and use it as per your requirement in the frontend application like Vue Js, React Js, Angular, Nuxt, etc.