Skip to content

Instantly share code, notes, and snippets.

@crabmusket
Last active April 12, 2024 11:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crabmusket/1f595e679c8f18d45a138d97be23d3e3 to your computer and use it in GitHub Desktop.
Save crabmusket/1f595e679c8f18d45a138d97be23d3e3 to your computer and use it in GitHub Desktop.
MJML emails in Laravel
<!-- resources/views/emails/mjml-test.blade.php -->
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text>
Hello {{$name}}!
</mj-text>
</mj-column>
</mj-section>
</mj-body>
</mjml>
<?php
namespace App\Mail;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\RuntimeException;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Support\HtmlString;
trait MJML
{
/**
* Provided for semantic clarity, and so that your emails break if you forget
* to use the trait.
*/
public function mjml($view, $data = [])
{
return $this->view($view, $data);
}
protected function buildView()
{
$mjml = app(ViewFactory::class)->make($this->view, $this->viewData)->render();
return [
'html' => new HTMLString($this->mjmlToHtml($mjml)),
];
}
protected function mjmlToHtml($mjml)
{
$exe = config('mjml.path', base_path('node_modules/.bin/mjml'));
$command = "$exe --stdin --stdout --config.minify=true";
$timeout = config('mjml.timeout', 60);
$process = new Process($command);
$process->setInput($mjml);
$process->setTimeout($timeout);
try {
$process->mustRun();
} catch (RuntimeException $e) {
// Process took too long
throw $e;
} catch (ProcessFailedException $e) {
// Process returned an error result
throw $e;
} catch (\Exception $e) {
// Not sure what happened
throw $e;
}
return $process->getOutput();
}
}
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Mail\MJML;
class MJMLTestEmail extends Mailable
{
use Queueable, SerializesModels, MJML;
public function build()
{
return $this
->from('you@example.com')
->subject('Example')
->mjml('emails.mjml-test', [
'name' => 'Joe Public',
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment