Using MJML Email Templates with CakePHP

This guide walks through a quick setup for using MJML Email templates in a CakePHP project.

Install MJML

Start by installing MJML using npm.

npm install mjml

Now you can start creating your .mjml files in the resources folder. Run the following command to convert them to an HTML file you can view with your browser.

npx mjml -w resources/template.mjml -o resources/template.html

Create a CakPHP command to turn your mjml files into PHP templates.

From the code below you can see it looks for html files, processes some special tags, and puts the templates in the email folder.
There are two special tags to be aware of. The php echo tags should be wrapped in [[]] and the regular php tags should use the mj-raw tag.

namespace App\Command;

use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;

class EmailGenCommand extends Command

public function execute(Arguments $args, ConsoleIo $io): int
    $io->out('Processing email templates');
    $files = glob(APP.'../resources/*.html');
    foreach ($files as $file) {
        $content = file_get_contents($file);
        $content = str_replace(['[[',']]','<mj-raw>','</mj-raw>'], ['<?=','?>','',''], $content);
        $file = str_replace('.html', '.php', $file);
        $file = str_replace(APP.'../resources/', APP.'../templates/email/html/', $file);
        file_put_contents($file, $content);
	return static::CODE_SUCCESS;

Featured Articles
Deploying CakePHP to using Docker
A quick guide on how to create your Docker file for CakePHP when using for deployment
Using Tailwind with CakePHP
A quick guide for setting up Tailwind CSS with CakePHP
Deploying Flowise to
A quick guide on how to deploy a Flowise server to the network
Creating a static HTML template for Tailwind and Alpine JS
A guide for creating a basic HTML template that uses Tailwind for styling and Alpine JS for interactive elements