• Stars
    star
    1,041
  • Rank 44,255 (Top 0.9 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 15 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Turns CSS blocks into style attributes

premailer

https://travis-ci.org/peterbe/premailer.svg?branch=master

Looking for sponsors

This project is actively looking for corporate sponsorship. If you want to help making this an active project consider pinging Peter and we can talk about putting up logos and links to your company.

Python versions

Our tox.ini makes sure premailer works in:

  • Python 3.4
  • Python 3.5
  • Python 3.6
  • Python 3.7
  • Python 3.8
  • PyPy

Turns CSS blocks into style attributes

When you send HTML emails you can't use style tags but instead you have to put inline style attributes on every element. So from this:

<html>
<style type="text/css">
h1 { border:1px solid black }
p { color:red;}
</style>
<h1 style="font-weight:bolder">Peter</h1>
<p>Hej</p>
</html>

You want this:

<html>
<h1 style="font-weight:bolder; border:1px solid black">Peter</h1>
<p style="color:red">Hej</p>
</html>

premailer does this. It parses an HTML page, looks up style blocks and parses the CSS. It then uses the lxml.html parser to modify the DOM tree of the page accordingly.

Warning! By default, premailer will attempt to download any external stylesheets by URL over the Internet. If you want to prevent this you can use the allow_network=False option.

Getting started

If you haven't already done so, install premailer first:

$ pip install premailer

Next, the most basic use is to use the shortcut function, like this:

>>> from premailer import transform
>>> print(transform("""
...         <html>
...         <style type="text/css">
...         h1 { border:1px solid black }
...         p { color:red;}
...         p::first-letter { float:left; }
...         </style>
...         <style type="text/css" data-premailer="ignore">
...         h1 { color:blue; }
...         </style>
...         <h1 style="font-weight:bolder">Peter</h1>
...         <p>Hej</p>
...         </html>
... """))
<html>
<head>
    <style type="text/css">p::first-letter {float:left}</style>
    <style type="text/css">
    h1 { color:blue; }
    </style>
</head>
<body>
    <h1 style="border:1px solid black; font-weight:bolder">Peter</h1>
    <p style="color:red">Hej</p>
</body>
</html>

The transform shortcut function transforms the given HTML using the defaults for all options:

base_url=None, # Optional URL prepended to all relative links (both stylesheets and internal)
disable_link_rewrites=False, # Allow link rewrites (e.g. using base_url)
preserve_internal_links=False, # Do not preserve links to named anchors when using base_url
preserve_inline_attachments=True, # Preserve links with cid: scheme when base_url is specified
preserve_handlebar_syntax=False # Preserve handlebar syntax from being encoded
exclude_pseudoclasses=True, # Ignore pseudoclasses when processing styles
keep_style_tags=False, # Discard original style tag
include_star_selectors=False, # Ignore star selectors when processing styles
remove_classes=False, # Leave class attributes on HTML elements
capitalize_float_margin=False, # Do not capitalize float and margin properties
strip_important=True, # Remove !important from property values
external_styles=None, # Optional list of URLs to load and parse
css_text=None, # Optional CSS text to parse
method="html", # Parse input as HTML (as opposed to "xml")
base_path=None, # Optional base path to stylesheet in your file system
disable_basic_attributes=None, # Optional list of attribute names to preserve on HTML elements
disable_validation=False, # Validate CSS when parsing it with cssutils
cache_css_parsing=True, # Do cache parsed output for CSS
cssutils_logging_handler=None, # See "Capturing logging from cssutils" below
cssutils_logging_level=None,
disable_leftover_css=False, # Output CSS that was not inlined into the HEAD
align_floating_images=True, # Add align attribute for floated images
remove_unset_properties=True # Remove CSS properties if their value is unset when merged
allow_network=True # allow network access to fetch linked css files
allow_insecure_ssl=False # Don't allow unverified SSL certificates for external links
allow_loading_external_files=False # Allow loading any non-HTTP external file URL
session=None # Session used for http requests - supply your own for caching or to provide authentication

For more advanced options, check out the code of the Premailer class and all its options in its constructor.

You can also use premailer from the command line by using its main module.

$ python -m premailer -h
usage: python -m premailer [options]

optional arguments:
-h, --help            show this help message and exit
-f [INFILE], --file [INFILE]
                      Specifies the input file. The default is stdin.
-o [OUTFILE], --output [OUTFILE]
                      Specifies the output file. The default is stdout.
--base-url BASE_URL
--remove-internal-links PRESERVE_INTERNAL_LINKS
                      Remove links that start with a '#' like anchors.
--exclude-pseudoclasses
                      Pseudo classes like p:last-child', p:first-child, etc
--preserve-style-tags
                      Do not delete <style></style> tags from the html
                      document.
--remove-star-selectors
                      All wildcard selectors like '* {color: black}' will be
                      removed.
--remove-classes      Remove all class attributes from all elements
--strip-important     Remove '!important' for all css declarations.
--method METHOD       The type of html to output. 'html' for HTML, 'xml' for
                      XHTML.
--base-path BASE_PATH
                      The base path for all external stylsheets.
--external-style EXTERNAL_STYLES
                      The path to an external stylesheet to be loaded.
--disable-basic-attributes DISABLE_BASIC_ATTRIBUTES
                      Disable provided basic attributes (comma separated)
--disable-validation  Disable CSSParser validation of attributes and values
--pretty              Pretty-print the outputted HTML.
--allow-insecure-ssl  Skip SSL certificate verification for external URLs.
--allow-loading-external-files Allow opening any non-HTTP external file URL.

A basic example:

$ python -m premailer --base-url=http://google.com/ -f newsletter.html
<html>
<head><style>.heading { color:red; }</style></head>
<body><h1 class="heading" style="color:red"><a href="http://google.com/">Title</a></h1></body>
</html>

The command line interface supports standard input.

$ echo '<style>.heading { color:red; }</style><h1 class="heading"><a href="/">Title</a></h1>' | python -m premailer --base-url=http://google.com/
<html>
<head><style>.heading { color:red; }</style></head>
<body><h1 class="heading" style="color:red"><a href="http://google.com/">Title</a></h1></body>
</html>

Turning relative URLs into absolute URLs

Another thing premailer can do for you is to turn relative URLs (e.g. "/some/page.html" into "http://www.peterbe.com/some/page.html"). It does this to all href and src attributes that don't have a :// part in it. For example, turning this:

<html>
<body>
<a href="/">Home</a>
<a href="page.html">Page</a>
<a href="http://crosstips.org">External</a>
<img src="/folder/">Folder</a>
</body>
</html>

Into this:

<html>
<body>
<a href="http://www.peterbe.com/">Home</a>
<a href="http://www.peterbe.com/page.html">Page</a>
<a href="http://crosstips.org">External</a>
<img src="http://www.peterbe.com/folder/">Folder</a>
</body>
</html>

by using transform('...', base_url='http://www.peterbe.com/').

Ignore certain <style> or <link> tags

Suppose you have a style tag that you don't want to have processed and transformed you can simply set a data attribute on the tag like:

<head>
<style>/* this gets processed */</style>
<style data-premailer="ignore">/* this gets ignored */</style>
</head>

That tag gets completely ignored except when the HTML is processed, the attribute data-premailer is removed.

It works equally for a <link> tag like:

<head>
<link rel="stylesheet" href="foo.css" data-premailer="ignore">
</head>

HTML attributes created additionally

Certain HTML attributes are also created on the HTML if the CSS contains any ones that are easily translated into HTML attributes. For example, if you have this CSS: td { background-color:#eee; } then this is transformed into style="background-color:#eee" and as an HTML attribute bgcolor="#eee".

Having these extra attributes basically as a "back up" for really shit email clients that can't even take the style attributes. A lot of professional HTML newsletters such as Amazon's use this. You can disable some attributes in disable_basic_attributes.

Capturing logging from cssutils

cssutils is the library that premailer uses to parse CSS. It will use the python logging module to mention all issues it has with parsing your CSS. If you want to capture this, you have to pass in cssutils_logging_handler and cssutils_logging_level (optional). For example like this:

>>> import logging
>>> import premailer
>>> from io import StringIO
>>> mylog = StringIO()
>>> myhandler = logging.StreamHandler(mylog)
>>> p = premailer.Premailer(
...     cssutils_logging_handler=myhandler,
...     cssutils_logging_level=logging.INFO
... )
>>> result = p.transform("""
...         <html>
...         <style type="text/css">
...         @keyframes foo { from { opacity: 0; } to { opacity: 1; } }
...         </style>
...         <p>Hej</p>
...         </html>
... """)
>>> mylog.getvalue()
'CSSStylesheet: Unknown @rule found. [2:1: @keyframes]\n'

If execution speed is on your mind

If execution speed is important, it's very plausible that you're not just converting 1 HTML document but a lot of HTML documents. Then, the first thing you should do is avoid using the premailer.transform function because it creates a Premailer class instance every time.

# WRONG WAY!
from premailer import transform

for html_string in get_html_documents():
    transformed = transform(html_string, base_url=MY_BASE_URL)
    # do something with 'transformed'

Instead...

# RIGHT WAY
from premailer import Premailer

instance = Premailer(base_url=MY_BASE_URL)
for html_string in get_html_documents():
    transformed = instance.transform(html_string)
    # do something with 'transformed'

Another thing to watch out for when you're reusing the same imported Python code and reusing it is that internal memoize function caches might build up. The environment variable to control is PREMAILER_CACHE_MAXSIZE. This parameter requires a little bit of fine-tuning and calibration if your workload is really big and memory even becomes an issue.

Advanced options

Below are some advanced configuration options that probably doesn't matter for most people with regular load.

Choosing the cache implementation

By default, premailer uses LFUCache to cache selectors, styles and parsed CSS strings. If LFU doesn't serve your purpose, it is possible to switch to an alternate implementation using below environment variables.

  • PREMAILER_CACHE: Can be LRU, LFU or TTL. Default is LFU.
  • PREMAILER_CACHE_MAXSIZE: Maximum no. of items to be stored in cache. Defaults to 128.
  • PREMAILER_CACHE_TTL: Time to live for cache entries. Only applicable for TTL cache. Defaults to 1 hour.

Getting coding

First clone the code and create whatever virtualenv you need, then run:

pip install -e ".[dev]"

Then to run the tests, run:

tox

This will run the whole test suite for every possible version of Python it can find on your system. To run the tests more incrementally, open up the tox.ini and see how it works.

Code style is all black

All code has to be formatted with Black and the best tool for checking this is therapist since it can help you run all, help you fix things, and help you make sure linting is passing before you git commit. This project also uses flake8 to check other things Black can't check.

To check linting with tox use:

tox -e lint

To install the therapist pre-commit hook simply run:

therapist install

When you run therapist run it will only check the files you've touched. To run it for all files use:

therapist run --use-tracked-files

And to fix all/any issues run:

therapist run --use-tracked-files --fix

More Repositories

1

mincss

Tool for finding out which CSS selectors you're NOT using.
Python
855
star
2

minimalcss

Extract the minimal CSS used in a set of URLs with puppeteer
JavaScript
351
star
3

autocompeter

A really fast AJAX autocomplete service and widget
Python
277
star
4

django-static

Template tags for better serving static files from templates in Django
Python
194
star
5

django-cache-memoize

Django utility for a memoization decorator that uses the Django cache framework.
Python
158
star
6

github-pr-triage

A dashboard of Github Pull Requests
JavaScript
149
star
7

django-fancy-cache

A Django `cache_page` decorator on steroids.
Python
145
star
8

tornado-utils

Utility scripts for a Tornado site
Python
135
star
9

tiler

App for allowing you to host some huge ass photos on the web.
JavaScript
127
star
10

django-mongokit

Bridging Django to MongoDB with the MongoKit ODM (Object Document Mapper)
Python
122
star
11

govspy

Go vs. Python
Python
112
star
12

django-sockjs-tornado

Makes it easy to run a SockJS server in Django through Tornado.
Python
102
star
13

hashin

Helping you write hashed entries for packages in your requirements.txt
Python
98
star
14

whatsdeployed

What's deployed from a Github repo on various server environments?
JavaScript
84
star
15

python-gorun

Using (py)inotify to run commands when files change
Python
66
star
16

toocool

too cool for me
JavaScript
62
star
17

worklog

Tornado app behind DoneCal
JavaScript
59
star
18

django-peterbecom

Code for my personal home page
CSS
54
star
19

django-html-validator

A tool to do validation of your HTML generated from your Django app.
Python
47
star
20

tornado_gists

Collaborative collection of Tornado related Github gists
Python
39
star
21

htmltree

Finding out which DOM nodes weigh the most
CSS
28
star
22

premailer.io

A website that uses premailer
JavaScript
25
star
23

docsql

docsQL - Getting an overview over your Markdown file in your Jamstack site
TypeScript
22
star
24

grymt

Preps a set of HTML files for deployment
Python
20
star
25

groce

A mobile web app to help families do grocery and meal planning.
TypeScript
19
star
26

buggy

A client-side wrapper on the bugzilla.mozilla.org REST API.
JavaScript
16
star
27

optisorl

Django backend plugin for sorl-thumbnail that optimizes thumbnails
Python
14
star
28

fastestdb

A collection of benchmarks for which database is the fastest for Tornado
JavaScript
13
star
29

workon

Personally opinionated Todo list in React
JavaScript
9
star
30

minimalcss-website

Single-page-app website for showcasing minimalcss
JavaScript
9
star
31

minimalcss-server

Node Express server to wrap calling minimalcss
JavaScript
8
star
32

django-fastest-redis

Trying different configurations for django-redis
Python
8
star
33

bgg

A love story with Bugzilla, git and Github
Python
8
star
34

django-jingo-offline-compressor

Using jingo and django_compressor but miss offline compression?
Python
8
star
35

next-peterbecom

New front-end for www.peterbe.com
CSS
7
star
36

github-action-tricks

Tips and tricks to make you a GitHub Actions power-user
Shell
7
star
37

django-spellcorrector

Spellcorrector app for Django
Python
6
star
38

json-schema-reducer

Extract from a JSON/dict ONLY whats in the JSON Schema
Python
6
star
39

youshouldwatch-next

A to-watch list of movies and TV shows
TypeScript
6
star
40

IssueTrackerProduct

A bug/issue tracker for Zope2
Python
5
star
41

django-spending

Bengtsson Household Spending app
Python
5
star
42

remix-peterbecom

Front-end for www.peterbe.com in Remix
TypeScript
5
star
43

sockshootout

Comparing WebSockets vs. jQuery AJAX using Tornado
JavaScript
5
star
44

jest-ts-and-http

Node/TypeScript project that uses `jest` to test a local server
TypeScript
5
star
45

slimmer

slimmer
Python
5
star
46

headsupper

Houston. We have commits coming in.
CSS
5
star
47

peepin

Project superseded by https://github.com/peterbe/hashin
Python
5
star
48

howsmywifi

Measure (repeatedly) your broadband speed using Fast.com in a headless browser.
JavaScript
5
star
49

fake-failbot

Mock server to use locally instead of a real FailBot server
JavaScript
5
star
50

django-fastest-cache

Experiment to see speed of using various caching backends
Python
5
star
51

chiveproxy

Experimental React PWA
JavaScript
4
star
52

cheerio-to-text

Turning a Cheerio objects into plain text
TypeScript
4
star
53

ghdocs-goer

A VS Code Extension for people who contribute to https://github.com/github/docs by editing Markdown files in VS Code.
TypeScript
4
star
54

redunter

Hunting down unused CSS since 2015
Python
4
star
55

gg

Git and GitHub for the productivity addicted
Python
4
star
56

python-reverse-geocode-test

Comparing Google Reverse Geocoding against GeoNames
3
star
57

python-donecal

Python interface for the donecal.com restful HTTP API
Python
3
star
58

sockshootout2019

XHR vs WebSockets 2019
JavaScript
3
star
59

hylite

A CLI for syntax highlighting code to HTML
TypeScript
3
star
60

minimalcss2

A Node library to extract the minimal (critical) CSS based on a string of HTML and a string of CSS.
TypeScript
3
star
61

uslicenseplates

US License Plate Spotter
JavaScript
3
star
62

fwc_mobile

Python
3
star
63

esrun-tsnode-esno

ts-node vs. esrun vs. esno vs. bun
TypeScript
3
star
64

rpsls

Rock Paper Scissors Lizard Spock
3
star
65

render-block-images-in-css

Experimenting with inlining CSS images with data URLs
JavaScript
3
star
66

slowpage

Experimenting with browsers' resource download behaviour
Python
3
star
67

SMTPSink

Very basic script for running a SMTP service to see sent emails
Python
2
star
68

mdn-yari-content

All the MDN documents as index.html and index.yaml.
2
star
69

tornado_gkc

GKC (tornado)
JavaScript
2
star
70

minimalcss-cli

JavaScript
2
star
71

activity

An experiment with logging project activities
JavaScript
2
star
72

react-buggy

Side-project in need of a better name
JavaScript
2
star
73

FriedZopeBase

Misc utility Zope2 Product with nifty base classess
JavaScript
2
star
74

kl

Crosstips.org
Python
2
star
75

programmatically-render-next-page

Programmatically render a Next page without a server in Node
TypeScript
2
star
76

podcasttime2

client-side for podcastti.me
JavaScript
2
star
77

dinnerd

Experiment to plan weekly dinners
JavaScript
2
star
78

express-vs-fastify-vs-polka

Comparing Express, Polka, and Fastify for serving static assets
JavaScript
2
star
79

ZSQL

A Zope2 Product for executing SQL in a file based Zope2 product
Python
2
star
80

mdn-nottranslated

Actually NOT Translated on MDN?
JavaScript
2
star
81

fake-hydro

Receive Hydro send events locally
JavaScript
2
star
82

langdetect

Wrapping whatlanggo as a CLI in Go
Go
2
star
83

battleshits

You will never shit in peace
JavaScript
2
star
84

github-slideshow

A robot powered training repository ๐Ÿค–
HTML
2
star
85

primer-autocomplete

A standalone implementation of @primer/react Autocomplete to build a typehead search feature
TypeScript
2
star
86

ws-sane-demo

A playground to play with WebSockets and Sane.
JavaScript
1
star
87

gityouracttogether

Learning how to pretend a commit never happened
1
star
88

zope_products

Old ZOPE products
Python
1
star
89

justmerge

Automatically merge/land GitHub Pull Requests that are ready
Python
1
star
90

http-request-relay

Make HTTP request via distributed AWS Lambda functions
Python
1
star
91

gitbusy

What are you gitting busy with?
JavaScript
1
star
92

django-thuawood

A website for my mom.
Python
1
star
93

elmo-docs

Documentation for the Mozilla Elmo project
Python
1
star
94

django-stephanie

A website for my friend Stephanie Kearley Mรผller
CSS
1
star
95

gaffwall

canvas + slippy map
JavaScript
1
star
96

spellthese

"Train your own spell corrector with TextBlob" blog post demo code
HTML
1
star
97

mondayosaseri

1
star
98

lang-analyze

A scrappy script to analyze the state of translated documents in MDN.
JavaScript
1
star
99

classy

An online Bayesian classifier for anybody via a REST API
JavaScript
1
star
100

aroundtheworld

JavaScript
1
star