I’m working on a Laravel project where I need to send scheduled emails using Mailgun’s API. I’ve got the timing part working fine, but I’m having trouble with the HTML content.
The issue is that for complex emails with lots of HTML (like 100+ lines), putting everything directly in the ‘html’ field makes the code messy and hard to maintain. I want to use a separate template file instead.
Is there a way to reference an external Blade template file for the HTML content? Something like:
You need to render the Blade template into HTML first before passing it to Mailgun. Laravel’s view system handles this perfectly. Don’t reference the template file directly - use Laravel’s view() helper to compile it:
The render() method compiles your Blade template into plain HTML that Mailgun can process. Pass variables to the template through view()'s second parameter. This keeps your code clean and lets you use all Blade features like loops, conditionals, and partials in your email templates.
I’ve had good luck creating a dedicated service class for handling Mailgun template rendering. Way better organization and you can reuse it everywhere. php class MailgunTemplateService { public function renderTemplate($templateName, $data = []) { return view($templateName, $data)->render(); } } Then in your scheduling code: php $templateService = new MailgunTemplateService(); $htmlContent = $templateService->renderTemplate('emails.welcome-template', [ 'userName' => $user->name, 'activationLink' => $activationUrl ]); $mailgunClient->messages()->send($domainName, [ 'from' => 'Support <[email protected]>', 'to' => '[email protected]', 'subject' => __('messages.welcome_subject'), 'html' => $htmlContent, 'o:deliverytime' => Carbon::now()->addHours(3)->toRfc2822String() ]); This saves tons of time with multiple email templates and makes debugging way easier. You can throw in error handling and template caching later if you need it.