Defective Code Logo

Total Downloads Latest Stable Version Latest Stable Version

English | العربية | বাংলা | Bosanski | Deutsch | Español | Français | हिन्दी | Italiano | 日本語 | 한국어 | मराठी | Português | Русский | Kiswahili | தமிழ் | తెలుగు | Türkçe | اردو | Tiếng Việt | 中文

Upgrading

If you are upgrading from a previous version, please see the Upgrade Guide for breaking changes and migration steps.

Introduction

MJML is a markup language specifically designed to simplify the process of coding responsive emails. Its semantic syntax ensures ease and simplicity, while its extensive library of standard components accelerates development and reduces the complexity of your email codebase. The open-source engine of MJML generates high-quality, responsive HTML that adheres to best practices. If you've experienced the frustrations of working with Outlook, this package is tailored for you.

Our MJML implementation serves as a wrapper for the official MJML API. It enables convenient compilation of MJML into HTML directly within PHP, without the need for NodeJS. This package is ideal for PHP applications that wish to incorporate MJML without the hassle of installing NodeJS and the MJML CLI.

It integrates with Laravel and Symfony, including a Twig filter and automatic rendering of .mjml.twig templates.

Example

// Without Laravel
(new MJML)->render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

// Minified HTML
(new MJML)->minify()->render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

// With Laravel
MJML::render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

// With Laravel and minified HTML
MJML::minify()->render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

Installation

  1. First add the following to your composer.json file to instruct our package to pull the correct binaries for your operating system when our package is installed. The binaries will download after you run install, update, or dump-autoload.

    {
        "post-autoload-dump": ["DefectiveCode\\MJML\\PullBinary::all"]
    }
    

    The MJML binary will be obtained from our CDN and saved in the "bin" folder of this package during composer's installation or update. Ensure that you have the necessary binaries loaded for both your local and production environments.

    By default, all will pull all binaries we support. We recommend scoping this down to the operating and architecture systems you need to save on bandwidth and install times. The following are the available binaries.

    Operating System Architecture Composer Post Update Command
    All All DefectiveCode\MJML\PullBinary::all
    Darwin (MacOS) arm64 DefectiveCode\MJML\PullBinary::darwin-arm64
    Linux (glibc) arm64 DefectiveCode\MJML\PullBinary::linux-arm64
    Linux (glibc) x64 DefectiveCode\MJML\PullBinary::linux-x64
    Linux (musl) arm64 DefectiveCode\MJML\PullBinary::linux-arm64-musl
    Linux (musl) x64 DefectiveCode\MJML\PullBinary::linux-x64-musl

    The musl binaries require the libstdc++ and libgcc shared libraries, which minimal musl images such as Alpine don't include. Without them, the binary fails with a loader error such as Error loading shared library libstdc++.so.6. On Alpine, install them with apk add libstdc++ libgcc, for example in your Dockerfile:

    RUN apk add --no-cache libstdc++ libgcc
    
  2. Next, install the PHP package by running the following composer command:

    composer require defectivecode/mjml
    
  3. That's it! If using Laravel, our package will automatically install using Laravel's package discovery. If using Symfony, register the bundle.

Linux Compatibility

The Linux binaries are tested on x64 and arm64 against these distributions:

libc Distributions
glibc Ubuntu 22.04, 24.04 and 26.04 LTS, Debian 12 and 13, Fedora 44 and 45
glibc Rocky Linux and AlmaLinux 8, 9 and 10, CentOS Stream 9 and 10
glibc Amazon Linux 2023, openSUSE Leap 16.0 and Tumbleweed, Arch Linux (x64 only)
musl Alpine 3.23 and 3.24

The PHP wrapper is also tested on the official php:8.5-cli and php:8.5-cli-alpine images.

These tests run in Docker, and containers share the host's kernel. They check each distribution's libraries, not older kernels or CPU features.

Usage (Without Laravel)

See the usage with Laravel or Symfony below if you are using either framework.

Rendering MJML

To render MJML, simply pass your MJML string to the render method:

use DefectiveCode\MJML\MJML;

$html = (new MJML)->render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

Validating MJML

To validate MJML, simply pass your MJML string to the isValid method:

use DefectiveCode\MJML\MJML;

$isValid = (new MJML)->isValid(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

Usage (With Laravel)

Rendering MJML

To render MJML, simply pass your MJML string to the render on the MJML facade:

use DefectiveCode\MJML\Facades\MJML;

$html = MJML::render(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

Validating MJML

To validate MJML, simply pass your MJML string to the isValid method on the MJML facade:

use DefectiveCode\MJML\Facades\MJML;

$isValid = MJML::isValid(
    '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
);

Configuration

You may publish the configuration file using the following command:

php artisan vendor:publish --provider="DefectiveCode\MJML\MJMLServiceProvider"

This will create a mjml.php configuration file in your config folder. All the options listed in the configuration file are past to the config object when you use the MJML facade.

Usage (With Symfony)

The Symfony bundle supports Symfony 7.4 and 8. The Twig features need Twig 3.21 or newer through TwigBundle.

Registering the Bundle

If your application uses Symfony Flex, it registers the bundle automatically when you install the package. Otherwise, enable it in config/bundles.php:

return [
    // ...
    DefectiveCode\MJML\MJMLBundle::class => ['all' => true],
];

Rendering MJML

Type-hint DefectiveCode\MJML\MJML to have the service injected, or fetch the mjml service:

use DefectiveCode\MJML\MJML;

class WelcomeEmail
{
    public function __construct(protected MJML $mjml) {}

    public function html(string $template): string
    {
        return $this->mjml->render($template);
    }
}

Each injection receives a new instance, so calling methods such as minify() only affects that instance.

Symfony Configuration

Create config/packages/mjml.yaml to change the defaults:

mjml:
    keep_comments: true
    ignore_includes: true
    beautify: false
    minify: true
    validation_level: soft # strict, soft or skip
    file_path: '%kernel.project_dir%'
    include_path: null
    # fonts, beautify_options, juice_options and juice_preserve_tags take a map
    fonts:
        Roboto: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700'

Setting fonts or beautify_options replaces the default list. Minification is on by default, as in the published Laravel configuration file.

Twig Templates

Templates whose name ends in .mjml.twig are converted to HTML when Twig renders them:

{# templates/emails/layout.mjml.twig #}
<mjml>
    <mj-body>
        {% block content %}{% endblock %}
    </mj-body>
</mjml>
{# templates/emails/signup.mjml.twig #}
{% extends 'emails/layout.mjml.twig' %}

{% block content %}
    <mj-section>
        <mj-column>
            <mj-text>Welcome, {{ name }}!</mj-text>
        </mj-column>
    </mj-section>
{% endblock %}

With Symfony Mailer, use the template as the HTML template. Symfony generates the plain text part from the converted HTML:

use Symfony\Bridge\Twig\Mime\TemplatedEmail;

$email = (new TemplatedEmail)
    ->to('[email protected]')
    ->subject('Welcome')
    ->htmlTemplate('emails/signup.mjml.twig')
    ->context(['name' => 'Taylor']);

Partials loaded with include, include() or embed become part of the outer document, which is converted once.

Keep the following in mind:

The Twig Filter

Use the mjml_to_html filter to convert MJML inside any other template:

{% apply mjml_to_html %}
    <mjml>
        <mj-body>
            <mj-section>
                <mj-column>
                    <mj-text>Hello {{ name }}</mj-text>
                </mj-column>
            </mj-section>
        </mj-body>
    </mjml>
{% endapply %}

The filter's output is not escaped, so only pass it MJML that you trust. Twig still escapes the variables inside your templates.

Symfony Render Failures

When MJML fails inside a template, Twig throws a Twig\Error\RuntimeError. Call getPrevious() to get the RenderException.

Configuration

All configuration options can be set by calling the following methods directly on the MJML object.

use DefectiveCode\MJML\MJML;

$html = (new MJML)
    ->minify()
    ->beautify(false)
    ->render(
        '<mjml><mj-body><mj-section><mj-column><mj-text>Hello World</mj-text></mj-column></mj-section></mj-body></mjml>'
    );

Our package follows the same configuration as the official MJML package except for the following:

Fonts

Our package uses the following fonts by default:

You may change the fonts by using the following methods:

Comments

Comments are kept by default. If you wish to remove comments, you may use the removeComments() method.

You may also revert the removeComments() by calling the keepComments() method.

Ignore Includes

By default, our package ignores mj-include tags. This matches MJML 5's safer default. You may enable includes by calling ignoreIncludes(false).

When enabling includes, use filePath(string $path) as the base directory and includePath(string|array|null $path) to allow additional include directories.

Beautify

Our package will beautify the HTML using js-beautify. MJML 5 also uses js-beautify internally, but this package keeps wrapper-level beautification so custom PHP beautifyOptions continue to work. The default options are:

While js-beautify uses snake_case to provide options, you should use camelCase when using our package. We made this choice to keep our package consistent with the rest of the configuration options. Our package will automatically convert the camelCase options to snake_case.

You may override any of these options by providing a valid js-beautify configuration using the following methods:

Minify

Our package will minify the HTML output when enabled. Minification performs the following:

You may enable or disable minification by calling the minify(bool $minify) method.

Why PHP-based minification? MJML 5 no longer uses the old vulnerable html-minifier package. This package still keeps minification in PHP to preserve the output behavior introduced in version 2.x. If you need MJML 5's native htmlnano/cssnano minification options, open a pull request that adds them.

Sending Email

When you render an email to send, minify the HTML and remove its comments:

use DefectiveCode\MJML\Facades\MJML;

$html = MJML::minify()->removeComments()->render($mjml);

Without Laravel:

use DefectiveCode\MJML\MJML;

$html = (new MJML)->minify()->removeComments()->render($mjml);

To do this on every render in Laravel, set both options in the published configuration file:

// config/mjml.php
'keep_comments' => false,
'minify' => true,

Comments are kept by default. The published configuration file turns minification on, but new MJML and an unpublished configuration leave it off.

Why Minify and Remove Comments

Checking the Size in Tests

Assert the rendered size of each template in your tests so it can't grow past Gmail's limit unnoticed. A budget below 102 KB leaves some headroom:

use DefectiveCode\MJML\Facades\MJML;

$html = MJML::minify()->removeComments()->render(view('emails.receipt')->render());

$this->assertLessThan(90_000, strlen($html));

Debugging

Beautified HTML is easier to read, but don't send it. Turn minification off when you beautify, because minification runs after beautification and undoes it:

$html = MJML::minify(false)->beautify()->render($mjml);

Validation Level

Our package will validate the MJML using the soft validation level by default. You may change this by using the validationLevel(ValidationLevel $validationLevel) method. The following validation levels are available:

Render Failures

When MJML fails to render, render() throws a DefectiveCode\MJML\Exceptions\RenderException, which extends Exception:

use DefectiveCode\MJML\MJML;
use DefectiveCode\MJML\Exceptions\RenderException;

try {
    $html = (new MJML)->render($mjml);
} catch (RenderException $exception) {
    $exitCode = $exception->getExitCode();
    $output = $exception->getOutput();
}

The exception message only includes the exit code. getOutput() returns the MJML binary's output, which can quote your template, such as attribute names, attribute values and file paths. If your templates contain personal data, don't send the output to logs or error trackers.

The isValid method returns false for validation errors and throws a RenderException for any other failure from the MJML binary.

File Path

Our package will use the . directory by default. You may change this by calling the filePath(string $path) method.

MJML 5 treats filePath as the include sandbox base. If includes are enabled, paths outside filePath are denied unless they are explicitly allowed with includePath(string|array|null $path).

Juice

We do not provide any juice options by default. You may add juice options by using the following methods:

Support Guidelines

Thanks for choosing our open source package! Please take a moment to check out these support guidelines. They'll help you get the most out of our project.

Community Driven Support

Our open-source project is fueled by our awesome community. If you have questions or need assistance, StackOverflow and other online resources are your best bets.

Bugs, and Feature Prioritization

The reality of managing an open-source project means we can't address every reported bug or feature request immediately. We prioritize issues in the following order:

1. Bugs Affecting Our Paid Products

Bugs that impact our paid products will always be our top priority. In some cases, we may only address bugs that affect us directly.

2. Community Pull Requests

If you've identified a bug and have a solution, please submit a pull request. After issues affecting our products, we give the next highest priority to these community-driven fixes. Once reviewed and approved, we'll merge your solution and credit your contribution.

3. Financial Support

For issues outside the mentioned categories, you can opt to fund their resolution. Each open issue is linked to an order form where you can contribute financially. We prioritize these issues based on the funding amount provided.

Community Contributions

Open source thrives when its community is active. Even if you're not fixing bugs, consider contributing through code improvements, documentation updates, tutorials, or by assisting others in community channels. We highly encourage everyone, as a community, to help support open-source work.

To reiterate, DefectiveCode will prioritize bugs based on how they impact our paid products, community pull requests, and the financial support received for issues.

License - MIT License

Copyright © Defective Code, LLC. All rights reserved

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.