MJML Python Implementation
mjml-python is a Python implementation and wrapper around the high-performance Rust MJML engine MRML. It allows compiling MJML markup into responsive HTML without requiring a Node.js runtime, external API calls, or subprocesses. The current version is 0.12.0. Releases are published as needed, often reflecting updates to the underlying MJML standard or significant bug fixes.
Common errors
-
ModuleNotFoundError: No module named 'mjml'
cause The `mjml` package has not been installed in the current Python environment.fixInstall the package using pip: `pip install mjml`. -
TypeError: 'module' object is not callable
cause Attempting to call the `mjml` module directly instead of its `mjml2html` function.fixEnsure you are calling the `mjml2html` function: `from mjml import mjml2html; html = mjml2html(...)`. -
RuntimeError: Unable to load shared library 'libmjml_python_core.so' or 'mjml_python_core.dll'
cause This error typically occurs when the underlying Rust binary (MRML) cannot be loaded, usually due to an incompatible system architecture, missing C++ runtime libraries (on Windows), or issues during installation.fixEnsure you are on a supported operating system and architecture. For Windows, ensure the Visual C++ Redistributable is installed. Try reinstalling with verbose output to check for build errors: `pip install mjml --verbose`.
Warnings
- breaking Version 0.12.0 officially dropped support for Python 3.6, 3.7, and 3.8. Users on these Python versions must either upgrade their Python environment or pin to an older `mjml` release.
- breaking The `css-inline` dependency underwent incompatible API changes across `mjml` versions. Notably, `0.9.1` pinned `css_inline < 0.10`, while `0.10.0` required `css-inline >= 0.11` (which broke Python 3.6), and `0.11.1` accepted `css_inline >= 0.14`. Mixing `mjml` versions or `css-inline` manually can lead to runtime errors.
- breaking A security vulnerability (CVE-2024-26151) was fixed in `v0.11.0` where potentially untrusted input could be rendered directly as HTML, leading to script injection. Users of `0.10.0` are strongly encouraged to upgrade.
- gotcha As of v0.12.0, comments within your MJML code (`<!-- comment -->`) will now be preserved and present in the generated HTML output by default. In previous versions, these comments might have been stripped.
Install
-
pip install mjml
Imports
- mjml2html
from mjml import mjml2html
Quickstart
from mjml import mjml2html
mjml_template = '''
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-text font-size="20px" color="#F45E43" font-family="Open Sans">Hello, MJML!</mj-text>
<mj-button href="https://mjml.io/" background-color="#F45E43">Learn More</mj-button>
</mj-column>
</mj-section>
</mj-body>
</mjml>
'''
result = mjml2html(mjml_template)
if result.errors:
print("MJML compilation errors:", result.errors)
else:
print(result.html)