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.
pip install premailerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the most basic usage of `premailer` using the `transform` shortcut function. It takes an HTML string with embedded CSS and converts the styles into inline attributes. For more complex scenarios or better performance when processing multiple documents, it is recommended to use the `Premailer` class directly.
If you relied on classes being removed, explicitly set `remove_classes=True` in the `Premailer` constructor or `transform` function: `transform(html, remove_classes=True)`.
For batch processing, instantiate the `Premailer` class once and reuse its `transform` method: `p = Premailer(base_url=MY_BASE_URL); for html_string in get_html_documents(): transformed = p.transform(html_string)`.
To prevent network requests, set the `allow_network=False` option: `transform(html, allow_network=False)` or `Premailer(html, allow_network=False)`.
To capture CSS parsing logs, pass a `cssutils_logging_handler` and `cssutils_logging_level` to the `Premailer` constructor. For example: `import logging; from io import StringIO; mylog = StringIO(); myhandler = logging.StreamHandler(mylog); p = Premailer(..., cssutils_logging_handler=myhandler, cssutils_logging_level=logging.INFO)`.
Ensure your CSS is well-formed and avoid complex or unsupported `@media` rules. Consider pre-processing CSS to simplify media queries or explicitly ignore them using `data-premailer='ignore'` if premailer is not intended to handle them.
Provide the HTML content either to the `Premailer` constructor (e.g., `p = Premailer(html_string, with_html_string=True)`) or as the first argument to the `transform` method (e.g., `p = Premailer(); p.transform(html_string)`), but not both.
Disable external stylesheet loading by setting `allow_network=False` in the `Premailer` constructor, or ensure network access is available and URLs are correct. If the stylesheets are local, use `base_url` or `base_path` to help premailer locate them without network requests.
Ensure your input HTML is well-formed. If the issue persists, try pinning `lxml` to a compatible version (e.g., `pip install lxml==4.9.4`) or update `premailer` to a version that officially supports newer `lxml` releases if available.