{"id":13448249,"url":"https://github.com/peterbe/premailer","last_synced_at":"2025-05-14T11:12:33.175Z","repository":{"id":613604,"uuid":"251729","full_name":"peterbe/premailer","owner":"peterbe","description":"Turns CSS blocks into style attributes","archived":false,"fork":false,"pushed_at":"2023-12-16T17:54:12.000Z","size":636,"stargazers_count":1079,"open_issues_count":72,"forks_count":188,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-05-13T08:02:37.697Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://premailer.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"zeebo/gostbook","license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/peterbe.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGES.rst","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2009-07-15T10:59:28.000Z","updated_at":"2025-05-09T13:35:16.000Z","dependencies_parsed_at":"2024-01-17T08:44:49.124Z","dependency_job_id":"fa1b4623-714c-41ca-aed8-e1d03fc79079","html_url":"https://github.com/peterbe/premailer","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterbe%2Fpremailer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterbe%2Fpremailer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterbe%2Fpremailer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterbe%2Fpremailer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/peterbe","download_url":"https://codeload.github.com/peterbe/premailer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254129525,"owners_count":22019628,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T05:01:40.002Z","updated_at":"2025-05-14T11:12:28.155Z","avatar_url":"https://github.com/peterbe.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"premailer\n=========\n\n.. image:: https://travis-ci.org/peterbe/premailer.svg?branch=master\n  :target: https://travis-ci.org/peterbe/premailer\n\n.. image:: https://badge.fury.io/py/premailer.svg\n  :target: https://pypi.python.org/pypi/premailer\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n  :target: https://github.com/ambv/black\n\nLooking for sponsors\n--------------------\n\nThis project is actively looking for corporate sponsorship. If you want\nto help making this an active project consider `pinging\nPeter \u003chttps://www.peterbe.com/contact\u003e`__ and we can talk about putting\nup logos and links to your company.\n\nPython versions\n---------------\n\nOur\n`tox.ini \u003chttps://github.com/peterbe/premailer/blob/master/tox.ini\u003e`__\nmakes sure premailer works in:\n\n-  Python 3.4\n-  Python 3.5\n-  Python 3.6\n-  Python 3.7\n-  Python 3.8\n-  PyPy\n\nTurns CSS blocks into style attributes\n--------------------------------------\n\nWhen you send HTML emails you can't use style tags but instead you have\nto put inline ``style`` attributes on every element. So from this:\n\n.. code:: html\n\n    \u003chtml\u003e\n    \u003cstyle type=\"text/css\"\u003e\n    h1 { border:1px solid black }\n    p { color:red;}\n    \u003c/style\u003e\n    \u003ch1 style=\"font-weight:bolder\"\u003ePeter\u003c/h1\u003e\n    \u003cp\u003eHej\u003c/p\u003e\n    \u003c/html\u003e\n\nYou want this:\n\n.. code:: html\n\n    \u003chtml\u003e\n    \u003ch1 style=\"font-weight:bolder; border:1px solid black\"\u003ePeter\u003c/h1\u003e\n    \u003cp style=\"color:red\"\u003eHej\u003c/p\u003e\n    \u003c/html\u003e\n\npremailer does this. It parses an HTML page, looks up ``style`` blocks\nand parses the CSS. It then uses the ``lxml.html`` parser to modify the\nDOM tree of the page accordingly.\n\nWarning!\nBy default, premailer will attempt to download any external stylesheets by URL over the Internet.\nIf you want to prevent this you can use the ``allow_network=False`` option.\n\nGetting started\n---------------\n\nIf you haven't already done so, install ``premailer`` first:\n\n::\n\n    $ pip install premailer\n\nNext, the most basic use is to use the shortcut function, like this:\n\n.. code:: python\n\n    \u003e\u003e\u003e from premailer import transform\n    \u003e\u003e\u003e print(transform(\"\"\"\n    ...         \u003chtml\u003e\n    ...         \u003cstyle type=\"text/css\"\u003e\n    ...         h1 { border:1px solid black }\n    ...         p { color:red;}\n    ...         p::first-letter { float:left; }\n    ...         \u003c/style\u003e\n    ...         \u003cstyle type=\"text/css\" data-premailer=\"ignore\"\u003e\n    ...         h1 { color:blue; }\n    ...         \u003c/style\u003e\n    ...         \u003ch1 style=\"font-weight:bolder\"\u003ePeter\u003c/h1\u003e\n    ...         \u003cp\u003eHej\u003c/p\u003e\n    ...         \u003c/html\u003e\n    ... \"\"\"))\n    \u003chtml\u003e\n    \u003chead\u003e\n        \u003cstyle type=\"text/css\"\u003ep::first-letter {float:left}\u003c/style\u003e\n        \u003cstyle type=\"text/css\"\u003e\n        h1 { color:blue; }\n        \u003c/style\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n        \u003ch1 style=\"border:1px solid black; font-weight:bolder\"\u003ePeter\u003c/h1\u003e\n        \u003cp style=\"color:red\"\u003eHej\u003c/p\u003e\n    \u003c/body\u003e\n    \u003c/html\u003e\n\nThe ``transform`` shortcut function transforms the given HTML using the defaults for all options:\n\n.. code:: python\n\n    base_url=None, # Optional URL prepended to all relative links (both stylesheets and internal)\n    disable_link_rewrites=False, # Allow link rewrites (e.g. using base_url)\n    preserve_internal_links=False, # Do not preserve links to named anchors when using base_url\n    preserve_inline_attachments=True, # Preserve links with cid: scheme when base_url is specified\n    preserve_handlebar_syntax=False # Preserve handlebar syntax from being encoded\n    exclude_pseudoclasses=True, # Ignore pseudoclasses when processing styles\n    keep_style_tags=False, # Discard original style tag\n    include_star_selectors=False, # Ignore star selectors when processing styles\n    remove_classes=False, # Leave class attributes on HTML elements\n    capitalize_float_margin=False, # Do not capitalize float and margin properties\n    strip_important=True, # Remove !important from property values\n    external_styles=None, # Optional list of URLs to load and parse\n    css_text=None, # Optional CSS text to parse\n    method=\"html\", # Parse input as HTML (as opposed to \"xml\")\n    base_path=None, # Optional base path to stylesheet in your file system\n    disable_basic_attributes=None, # Optional list of attribute names to preserve on HTML elements\n    disable_validation=False, # Validate CSS when parsing it with cssutils\n    cache_css_parsing=True, # Do cache parsed output for CSS\n    cssutils_logging_handler=None, # See \"Capturing logging from cssutils\" below\n    cssutils_logging_level=None,\n    disable_leftover_css=False, # Output CSS that was not inlined into the HEAD\n    align_floating_images=True, # Add align attribute for floated images\n    remove_unset_properties=True # Remove CSS properties if their value is unset when merged\n    allow_network=True # allow network access to fetch linked css files\n    allow_insecure_ssl=False # Don't allow unverified SSL certificates for external links\n    allow_loading_external_files=False # Allow loading any non-HTTP external file URL\n    session=None # Session used for http requests - supply your own for caching or to provide authentication\n\nFor more advanced options, check out the code of the ``Premailer`` class\nand all its options in its constructor.\n\nYou can also use premailer from the command line by using its main\nmodule.\n\n::\n\n    $ python -m premailer -h\n    usage: python -m premailer [options]\n\n    optional arguments:\n    -h, --help            show this help message and exit\n    -f [INFILE], --file [INFILE]\n                          Specifies the input file. The default is stdin.\n    -o [OUTFILE], --output [OUTFILE]\n                          Specifies the output file. The default is stdout.\n    --base-url BASE_URL\n    --remove-internal-links PRESERVE_INTERNAL_LINKS\n                          Remove links that start with a '#' like anchors.\n    --exclude-pseudoclasses\n                          Pseudo classes like p:last-child', p:first-child, etc\n    --preserve-style-tags\n                          Do not delete \u003cstyle\u003e\u003c/style\u003e tags from the html\n                          document.\n    --remove-star-selectors\n                          All wildcard selectors like '* {color: black}' will be\n                          removed.\n    --remove-classes      Remove all class attributes from all elements\n    --strip-important     Remove '!important' for all css declarations.\n    --method METHOD       The type of html to output. 'html' for HTML, 'xml' for\n                          XHTML.\n    --base-path BASE_PATH\n                          The base path for all external stylsheets.\n    --external-style EXTERNAL_STYLES\n                          The path to an external stylesheet to be loaded.\n    --disable-basic-attributes DISABLE_BASIC_ATTRIBUTES\n                          Disable provided basic attributes (comma separated)\n    --disable-validation  Disable CSSParser validation of attributes and values\n    --pretty              Pretty-print the outputted HTML.\n    --allow-insecure-ssl  Skip SSL certificate verification for external URLs.\n    --allow-loading-external-files Allow opening any non-HTTP external file URL.\n\nA basic example:\n\n::\n\n    $ python -m premailer --base-url=http://google.com/ -f newsletter.html\n    \u003chtml\u003e\n    \u003chead\u003e\u003cstyle\u003e.heading { color:red; }\u003c/style\u003e\u003c/head\u003e\n    \u003cbody\u003e\u003ch1 class=\"heading\" style=\"color:red\"\u003e\u003ca href=\"http://google.com/\"\u003eTitle\u003c/a\u003e\u003c/h1\u003e\u003c/body\u003e\n    \u003c/html\u003e\n\nThe command line interface supports standard input.\n\n::\n\n    $ echo '\u003cstyle\u003e.heading { color:red; }\u003c/style\u003e\u003ch1 class=\"heading\"\u003e\u003ca href=\"/\"\u003eTitle\u003c/a\u003e\u003c/h1\u003e' | python -m premailer --base-url=http://google.com/\n    \u003chtml\u003e\n    \u003chead\u003e\u003cstyle\u003e.heading { color:red; }\u003c/style\u003e\u003c/head\u003e\n    \u003cbody\u003e\u003ch1 class=\"heading\" style=\"color:red\"\u003e\u003ca href=\"http://google.com/\"\u003eTitle\u003c/a\u003e\u003c/h1\u003e\u003c/body\u003e\n    \u003c/html\u003e\n\nTurning relative URLs into absolute URLs\n----------------------------------------\n\nAnother thing premailer can do for you is to turn relative URLs (e.g.\n\"/some/page.html\" into \"http://www.peterbe.com/some/page.html\"). It does\nthis to all ``href`` and ``src`` attributes that don't have a ``://``\npart in it. For example, turning this:\n\n.. code:: html\n\n    \u003chtml\u003e\n    \u003cbody\u003e\n    \u003ca href=\"/\"\u003eHome\u003c/a\u003e\n    \u003ca href=\"page.html\"\u003ePage\u003c/a\u003e\n    \u003ca href=\"http://crosstips.org\"\u003eExternal\u003c/a\u003e\n    \u003cimg src=\"/folder/\"\u003eFolder\u003c/a\u003e\n    \u003c/body\u003e\n    \u003c/html\u003e\n\nInto this:\n\n.. code:: html\n\n    \u003chtml\u003e\n    \u003cbody\u003e\n    \u003ca href=\"http://www.peterbe.com/\"\u003eHome\u003c/a\u003e\n    \u003ca href=\"http://www.peterbe.com/page.html\"\u003ePage\u003c/a\u003e\n    \u003ca href=\"http://crosstips.org\"\u003eExternal\u003c/a\u003e\n    \u003cimg src=\"http://www.peterbe.com/folder/\"\u003eFolder\u003c/a\u003e\n    \u003c/body\u003e\n    \u003c/html\u003e\n\nby using ``transform('...', base_url='http://www.peterbe.com/')``.\n\nIgnore certain ``\u003cstyle\u003e`` or ``\u003clink\u003e`` tags\n---------------------------------------------\n\nSuppose you have a style tag that you don't want to have processed and\ntransformed you can simply set a data attribute on the tag like:\n\n.. code:: html\n\n    \u003chead\u003e\n    \u003cstyle\u003e/* this gets processed */\u003c/style\u003e\n    \u003cstyle data-premailer=\"ignore\"\u003e/* this gets ignored */\u003c/style\u003e\n    \u003c/head\u003e\n\nThat tag gets completely ignored except when the HTML is processed, the\nattribute ``data-premailer`` is removed.\n\nIt works equally for a ``\u003clink\u003e`` tag like:\n\n.. code:: html\n\n    \u003chead\u003e\n    \u003clink rel=\"stylesheet\" href=\"foo.css\" data-premailer=\"ignore\"\u003e\n    \u003c/head\u003e\n\nHTML attributes created additionally\n------------------------------------\n\nCertain HTML attributes are also created on the HTML if the CSS contains\nany ones that are easily translated into HTML attributes. For example,\nif you have this CSS: ``td { background-color:#eee; }`` then this is\ntransformed into ``style=\"background-color:#eee\"`` and as an HTML\nattribute ``bgcolor=\"#eee\"``.\n\nHaving these extra attributes basically as a \"back up\" for really shit\nemail clients that can't even take the style attributes. A lot of\nprofessional HTML newsletters such as Amazon's use this. You can disable\nsome attributes in ``disable_basic_attributes``.\n\n\nCapturing logging from ``cssutils``\n-----------------------------------\n\n`cssutils \u003chttps://pypi.python.org/pypi/cssutils/\u003e`__ is the library that\n``premailer`` uses to parse CSS. It will use the python ``logging`` module\nto mention all issues it has with parsing your CSS. If you want to capture\nthis, you have to pass in ``cssutils_logging_handler`` and\n``cssutils_logging_level`` (optional). For example like this:\n\n.. code:: python\n\n    \u003e\u003e\u003e import logging\n    \u003e\u003e\u003e import premailer\n    \u003e\u003e\u003e from io import StringIO\n    \u003e\u003e\u003e mylog = StringIO()\n    \u003e\u003e\u003e myhandler = logging.StreamHandler(mylog)\n    \u003e\u003e\u003e p = premailer.Premailer(\n    ...     cssutils_logging_handler=myhandler,\n    ...     cssutils_logging_level=logging.INFO\n    ... )\n    \u003e\u003e\u003e result = p.transform(\"\"\"\n    ...         \u003chtml\u003e\n    ...         \u003cstyle type=\"text/css\"\u003e\n    ...         @keyframes foo { from { opacity: 0; } to { opacity: 1; } }\n    ...         \u003c/style\u003e\n    ...         \u003cp\u003eHej\u003c/p\u003e\n    ...         \u003c/html\u003e\n    ... \"\"\")\n    \u003e\u003e\u003e mylog.getvalue()\n    'CSSStylesheet: Unknown @rule found. [2:1: @keyframes]\\n'\n\n\nIf execution speed is on your mind\n----------------------------------\n\nIf execution speed is important, it's very plausible that you're not just converting\n1 HTML document but *a lot* of HTML documents. Then, the first thing you should do\nis avoid using the ``premailer.transform`` function because it creates a ``Premailer``\nclass instance every time.\n\n.. code:: python\n\n    # WRONG WAY!\n    from premailer import transform\n\n    for html_string in get_html_documents():\n        transformed = transform(html_string, base_url=MY_BASE_URL)\n        # do something with 'transformed'\n\nInstead...\n\n.. code:: python\n\n    # RIGHT WAY\n    from premailer import Premailer\n\n    instance = Premailer(base_url=MY_BASE_URL)\n    for html_string in get_html_documents():\n        transformed = instance.transform(html_string)\n        # do something with 'transformed'\n\nAnother thing to watch out for when you're reusing the same imported Python code\nand reusing it is that internal memoize function caches might build up. The\nenvironment variable to control is ``PREMAILER_CACHE_MAXSIZE``. This parameter\nrequires a little bit of fine-tuning and calibration if your workload is really\nbig and memory even becomes an issue.\n\nAdvanced options\n----------------\n\nBelow are some advanced configuration options that probably doesn't matter for\nmost people with regular load.\n\nChoosing the cache implementation\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nBy default, ``premailer`` uses `LFUCache\n\u003chttps://cachetools.readthedocs.io/en/latest/#cachetools.LFUCache\u003e`__ to cache\nselectors, styles and parsed CSS strings. If LFU doesn't serve your purpose, it\nis possible to switch to an alternate implementation using below environment\nvariables.\n\n- ``PREMAILER_CACHE``: Can be LRU, LFU or TTL. Default is LFU.\n- ``PREMAILER_CACHE_MAXSIZE``: Maximum no. of items to be stored in cache. Defaults to 128.\n- ``PREMAILER_CACHE_TTL``: Time to live for cache entries. Only applicable for TTL cache. Defaults to 1 hour.\n\n\nGetting coding\n--------------\n\nFirst clone the code and create whatever virtualenv you need, then run:\n\n.. code:: bash\n\n    pip install -e \".[dev]\"\n\n\nThen to run the tests, run:\n\n.. code:: bash\n\n    tox\n\nThis will run the *whole test suite* for every possible version of Python\nit can find on your system. To run the tests more incrementally, open\nup the ``tox.ini`` and see how it works.\n\nCode style is all black\n-----------------------\n\nAll code has to be formatted with `Black \u003chttps://pypi.org/project/black/\u003e`_\nand the best tool for checking this is\n`therapist \u003chttps://pypi.org/project/therapist/\u003e`_ since it can help you run\nall, help you fix things, and help you make sure linting is passing before\nyou git commit. This project also uses ``flake8`` to check other things\nBlack can't check.\n\nTo check linting with ``tox`` use:\n\n.. code:: bash\n\n    tox -e lint\n\nTo install the ``therapist`` pre-commit hook simply run:\n\n.. code:: bash\n\n    therapist install\n\nWhen you run ``therapist run`` it will only check the files you've touched.\nTo run it for all files use:\n\n.. code:: bash\n\n    therapist run --use-tracked-files\n\nAnd to fix all/any issues run:\n\n.. code:: bash\n\n    therapist run --use-tracked-files --fix\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterbe%2Fpremailer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpeterbe%2Fpremailer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterbe%2Fpremailer/lists"}