Premailer
Premailer is a Python library that converts HTML documents containing CSS `<style>` blocks or `<link>` tags into HTML with inline `style` attributes. It leverages `lxml` for parsing and is primarily used for preparing HTML emails, where external stylesheets are often unsupported. The library's latest stable version is 3.10.0 and it maintains an active development status.
Warnings
- breaking In version 3.0.0, the default value for the `remove_classes` option changed from `True` to `False`. This means CSS class attributes are now kept in the output HTML by default.
- gotcha Using `premailer.transform` repeatedly in a loop for multiple HTML documents can lead to poor performance, as it creates a new `Premailer` instance with each call.
- gotcha By default, `premailer` attempts to download external stylesheets specified by URLs over the network. This can introduce security risks or performance issues.
- gotcha The underlying `cssutils` library, used by `premailer` for CSS parsing, uses Python's standard `logging` module to report issues. By default, these logs might not be captured or visible.
Install
-
pip install premailer
Imports
- transform
from premailer import transform
- Premailer
from premailer import Premailer
Quickstart
from premailer import transform
html_content = """
<html>
<head>
<style type="text/css">
h1 { border:1px solid black }
p { color:red;}
</style>
</head>
<body>
<h1 style="font-weight:bolder">Peter</h1>
<p>Hej</p>
</body>
</html>
"""
# Transform the HTML to inline styles
result_html = transform(html_content)
print(result_html)