Git Product home page Git Product logo

mjml-php's Introduction

Convert MJML to HTML using PHP

Latest Version on Packagist Tests Total Downloads

MJML is a markup language designed to reduce the pain of coding a responsive email. Our mjml-php package can convert MJML to HTML.

Here's an example of how to use our package:

use Spatie\Mjml\Mjml;

$mjml = <<<'MJML'
    <mjml>
      <mj-body>
        <mj-section>
          <mj-column>
            <mj-text invalid-attribute>Hello World</mj-text>
          </mj-column>
        </mj-section>
      </mj-body>
    </mjml>
    MJML;

$html = Mjml::new()->toHtml($mjml);

The returned HTML will look like the HTML in this snapshot file (it's a bit too large to inline in this readme). Most email clients will be able to render this HTML perfectly.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/mjml-php

In your project, or on your server, you must have the JavaScript package mjml installed.

npm install mjml

... or Yarn.

yarn add mjml

Make sure you have installed Node 16 or higher.

Usage

The easiest way to convert MJML to HTML is by using the toHtml() method.

use Spatie\Mjml\Mjml;

// let's assume $mjml contains the MJML you want to convert

$html = Mjml::new()->toHtml($mjml);

If the MJML could not be converted at all a Spatie\Mjml\Exceptions\CouldNotRenderMjml exception will be thrown.

Using convert()

The toHtml() method will just return the converted HTML. There's also a convert() method that will return an instance of Spatie\Mjml\MjmlResult that contains the converted HTML and some metadata.

use Spatie\Mjml\Mjml;

// let's assume $mjml contains the MJML you want to convert

$result = Mjml::new()->convert($mjml); // returns an instance of Spatie\Mjml\MjmlResult

On the returned instance of Spatie\Mjml\MjmlResult you can call the following methods:

  • html(): returns the converted HTML
  • array(): returns a structured version of the given MJML
  • hasErrors(): returns a boolean indicating if there were errors while converting the MJML
  • errors(): returns an array of errors that occurred while converting the MJML

The errors() method returns an array containing instances of Spatie\Mjml\MjmlError. Each Spatie\Mjml\MjmlError has the following methods:

  • line(): returns the line number where the error occurred
  • message(): returns the error message
  • formattedMessage(): returns the error message with the line number prepended
  • tagName(): returns the name of the tag where the error occurred

Customizing the rendering

There are various methods you can call on the Mjml class to customize the rendering. For instance the minify() method will minify the HTML that is returned.

use Spatie\Mjml\Mjml;

// let's assume $mjml contains the MJML you want to convert
$minifiedHtml = Mjml::new()->minify()->toHtml($mjml);

These are all the methods you can call on the Mjml class:

  • minify(): minify the HTML that is returned
  • beautify(): beautify the HTML that is returned
  • hideComments(): hide comments in the HTML that is returned
  • validationLevel(ValidationLevel $validationLevel): set the validation level to strict, soft or skip

Instead of using these dedicated methods, you could opt to pass an array with options as the second argument of the toHtml or convert method. You can use any of the options that are mentioned in the MJML documentation for Node.js.

use Spatie\Mjml\Mjml;

// let's assume $mjml contains the MJML you want to convert
$minifiedHtml = Mjml::new()->minify()->toHtml($mjml, [
    'beautify' => true,
    'minify' => true,
]);

Validating MJML

You can make sure a piece of MJML is valid by using the canConvert() method.

use Spatie\Mjml\Mjml;

Mjml::new()->canConvert($mjml); // returns a boolean

If true is returned we'll be able to convert the given MJML to HTML. However, there may still be some errors while converting the MJML to HTML. These errors are not fatal and the MJML will still be converted to HTML. You can see these non-fatal errors when calling errors() on the MjmlResult instance that is returned when calling convert.

You can use canConvertWithoutErrors to make sure the MJML is both valid and that there are no non-fatal errors while converting it to HTML.

use Spatie\Mjml\Mjml;

Mjml::new()->canConvertWithoutErrors($mjml); // returns a boolean

Specifying the path to nodejs executable

By default, the package itself will try to determine the path to the node executable. If the package can't find a path, you can specify a path in the environment variable MJML_NODE_PATH

MJML_NODE_PATH=/home/user/.nvm/versions/node/v20.11.0/bin

Sidecar

This package also supports running through Sidecar in Laravel projects.

To use the ->sidecar() method, a few extra steps are needed:

Install the Sidecar package:

composer require spatie/mjml-sidecar

Register the MjmlFunction in your sidecar.php config file.

/*
 * All of your function classes that you'd like to deploy go here.
 */
'functions' => [
    \Spatie\MjmlSidecar\MjmlFunction::class,
],

Deploy the Lambda function by running:

php artisan sidecar:deploy --activate

See the Sidecar documentation for details.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

mjml-php's People

Contributors

baspa avatar dependabot[bot] avatar freekmurze avatar github-actions[bot] avatar nielsvanpach avatar riasvdv avatar thecaliskan avatar vladyslav-mikhieiev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mjml-php's Issues

[Bug]: Working with a rendered blade view as input does not work on Windows environment

What happened?

Currently I have a bug where the exact same code always works when running my app on MacOS and Linux machines, but I get a NodeJS JSON parse error on Windows environments.

My code is as follows:

in the content function of a Laravel mailable, I generate MJML like this:

        $mjmlViewData = view('mails.revision2023.account.activated', [
            'header' => __('mails.account.activated.subject'),
            'exampleData' => $exampleData
        ])->render();
        
        $html = Mjml::new()->toHtml($mjmlViewData);

the mail template looks like this basically:

<mjml>
    <mj-head>
        <mj-title>Foneday</mj-title>
.... etc
</mjml>

The toHtml() function works fine and renders HTML that can be used perfectly in emails, on Mac.

But on Windows, I get the following error:

The command ""C:\Program Files\nodejs\\node.EXE" mjml.mjs "[""<mjml>\r\n <mj-head>\r\n <mj-title>Test<\/mj-title>\r\n <mj-raw>\r\n <meta name=\""color-scheme\"" content=\""light dark\"">\r\n <meta name=\""supported-color-schemes\"" content=\""light dark\"">\r\n <link rel=\""preconnect\"" href=\""https:\/\/fonts.googleapis.com\"">\r\n <link rel=\""preconnect\"" href=\""https:\/\/fonts.gstatic.com\"" crossorigin>\r\n <\/mj-raw>\r\n\r\n <mj-font name=\""Montserrat\""

.......

<\/mj-body>\r\n<\/mjml>"",{""keepComments"":true,""ignoreIncludes"":false,""beautify"":false,""minify"":false,""validationLevel"":""strict"",""filePath"":"".""}]"" failed. Exit Code: 1(General error) Working directory: C:\Projects\shop\vendor\spatie\mjml-php\bin Output: ================ Error Output: ================ undefined:1 SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at file:///C:/Projects/shop/vendor/spatie/mjml-php/bin/mjml.mjs:3:19 at ModuleJob.run (node:internal/modules/esm/module_job:198:25) at async Promise.all (index 0) at async ESMLoader.import (node:internal/modules/esm/loader:385:24) at async loadESM (node:internal/process/esm_loader:88:5) at async handleMainPromise (node:internal/modules/run_main:61:12)

I tried a lot of things, like minifying, trimming characters, shortening the mjml code, etc etc., but nothing works.

The issue is also not with my node environment setup, because if I enter the code as input from the readme of the package then the toHtml() function does work and render the email correctly.:

$mjml = <<<'MJML'
    <mjml>
      <mj-body>
        <mj-section>
          <mj-column>
            <mj-text invalid-attribute>Hello World</mj-text>
          </mj-column>
        </mj-section>
      </mj-body>
    </mjml>
    MJML;

$html = Mjml::new()->toHtml($mjml);

The above works on my machine.

The issue seems to be with the rendered blade view content. But this sequence does work without issue on Mac.

What could be the problem here?

How to reproduce the bug

Try to convert pre-rendered mjml from a blade view to Html on a Windows environment.

Package Version

1.0.2

PHP Version

8.2.0

Which operating systems does with happen with?

Windows

Notes

No response

[Bug]: Installing mjml as global package in npm is not working correctly

What happened?

Within a Docker container with the package mjml installed globally the following error is happening.

Error:

root@ip:/var/www/html# cd /var/www/html/vendor/spatie/mjml-php/bin
root@ip:/var/www/html/vendor/spatie/mjml-php/bin# /usr/bin/node mjml.mjs
node:internal/modules/esm/resolve:844
  throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), null);
        ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'mjml' imported from /var/www/html/vendor/spatie/mjml-php/bin/mjml.mjs
    at packageResolve (node:internal/modules/esm/resolve:844:9)
    at moduleResolve (node:internal/modules/esm/resolve:901:20)
    at defaultResolve (node:internal/modules/esm/resolve:1121:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:396:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:365:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:240:38)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:85:39)
    at link (node:internal/modules/esm/module_job:84:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v20.10.0
root@ip:/var/www/html/vendor/spatie/mjml-php/bin# cd
root@ip:~# mjml

Command line error:
No input argument received

Note: The ip has been hidden.

How to reproduce the bug

Install npm globally using the following command (within Docker): npm install -g mjml

Part of the Dockerfile:

ARG PHP_VERSION=**
ARG NODE_MAJOR=**

#
# Nginx image
# https://github.com/serversideup/docker-php
#
FROM --platform=linux/amd64 serversideup/php:${PHP_VERSION}-fpm-nginx as nginx

ARG NODE_MAJOR

# Install jq and Node.js using regular Ubuntu commands
RUN apt-get update \
    && apt-get install -y --no-install-recommends jq ca-certificates curl gnupg \
    && mkdir -p /etc/apt/keyrings \
    && curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
    && echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list \
    && apt-get update \
    && apt-get install -y --no-install-recommends nodejs \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* /etc/apt/keyrings /etc/apt/sources.list.d/nodesource.list

# Install MJML
RUN npm install -g mjml

Make sure the mjml package is not installed within the project directory

Try to execute/compile mjml within the package.

Package Version

Latest

PHP Version

8.2.x

Which operating systems does with happen with?

Linux

Notes

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.