How to use the premailer.Premailer function in premailer

To help you get started, we’ve selected a few premailer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vovantics / flask-bluebone / app / session / views.py View on Github external
response.status_code = 200
                current_app.logger.debug('Returning success; response.data=[%s]' % response.data)
                return response
            else:
                # User reactivation request.
                user.activation_key = str(uuid4())
                db.session.add(user)
                db.session.commit()

                # Send reactivation confirmation email.
                css = get_resource_as_string('static/css/email.css')
                reactivate_url = '%s/#accounts/reactivate/%s/%s/' % (current_app.config['DOMAIN'], quote(user.email), user.activation_key)
                html = render_template('user/emails/reactivate_confirm.html', css=css, username=user.username, email_recipient=user.email, reactivate_url=reactivate_url)
                current_app.logger.debug('reactivate_url=[%s]' % reactivate_url)

                p = Premailer(html)
                result_html = p.transform()

                message = Message(subject='%s Account Reactivation' % current_app.config['APP_NAME'], html=result_html, recipients=[user.email])
                try:
                    mail.send(message)
                except SMTPDataError as e:
                    current_app.logger.debug('Returning fail = [%s].' % e)
                    response = jsonify(status='fail', data={'email': "Couldn't send email to %s." % form.email.data})
                    response.status_code = 200
                    return response
                # Return response
                response = jsonify(status='success', data=user.session_as_dict())
                response.status_code = 200
                current_app.logger.debug('Returning success')
                return response
        else:
github Aristotle-Metadata-Enterprises / wcag-zoo / wcag_zoo / utils.py View on Github external
import os
import sys
from io import BytesIO
import logging
from premailer import Premailer
from premailer.premailer import _cache_parse_css_string

# From Premailer
import cssutils
import re
cssutils.log.setLevel(logging.CRITICAL)
_element_selector_regex = re.compile(r'(^|\s)\w')
FILTER_PSEUDOSELECTORS = [':last-child', ':first-child', ':nth-child', ":focus"]


class Premoler(Premailer):
    def __init__(self, *args, **kwargs):
        self.media_rules = kwargs.pop('media_rules', [])
        super().__init__(*args, **kwargs)

    # We have to override this because an absolute path is from root, not the curent dir.
    def _load_external(self, url):
        """loads an external stylesheet from a remote url or local path
        """
        import codecs
        from premailer.premailer import ExternalNotFoundError, urljoin
        if url.startswith('//'):
            # then we have to rely on the base_url
            if self.base_url and 'https://' in self.base_url:
                url = 'https:' + url
            else:
                url = 'http:' + url
github frappe / frappe / frappe / email / email_body.py View on Github external
def inline_style_in_html(html):
	''' Convert email.css and html to inline-styled html
	'''
	from premailer import Premailer

	apps = frappe.get_installed_apps()

	css_files = []
	for app in apps:
		path = 'assets/{0}/css/email.css'.format(app)
		if os.path.exists(os.path.abspath(path)):
			css_files.append(path)

	p = Premailer(html=html, external_styles=css_files, strip_important=False)

	return p.transform()
github ebmdatalab / openprescribing / openprescribing / frontend / views / bookmark_utils.py View on Github external
def finalise_email(msg, template_name, context, tags):
    """Set message body, add HTML alternative, and add some headers.
    """

    template = get_template(template_name)
    html = template.render(context)
    html = Premailer(html, cssutils_logging_level=logging.ERROR).transform()
    html = unescape_href(html)
    text = email_as_text(html)
    msg.body = text
    msg.attach_alternative(html, "text/html")
    msg.extra_headers["list-unsubscribe"] = "<%s>" % context["unsubscribe_link"]
    msg.tags = ["monthly_update"] + tags
    return msg
github oddbird / portfoliyo / portfoliyo / notifications / render / base.py View on Github external
"""
    collection = collect.NotificationCollection(profile, clear=clear)

    # bail out if there's nothing to do
    if not collection:
        raise NothingToDo()

    context = collection.context
    context['BASE_URL'] = settings.PORTFOLIYO_BASE_URL

    subject = render_to_string(collection.get_subject_template(), context)

    text = consecutive_newlines.sub(
        '\n\n', render_to_string(TEXT_TEMPLATE, context))
    html = premailer.Premailer(
        render_to_string(HTML_TEMPLATE, context),
        base_url=settings.PORTFOLIYO_BASE_URL,
        output_xhtml=True,
        ).transform()

    return subject, text, html
github liuwons / EverMark / evermark.py View on Github external
html = u'<style>' + self.css_str
        html += '.markdown-body {box-sizing: border-box;min-width: ' \
                '200px;max-width: 980px;margin: 0 auto;padding: 45px;}'
        html += '</style>'
        html += '<article class="markdown-body">'
        md_html = markdown2.markdown(markdown_str, extras=["tables", "fenced-code-blocks", "cuddled-lists"])
        html += md_html
        html += '</article>'

        if log.isEnabledFor(logging.DEBUG):
            pre_html_file_path = os.path.join(self.html_log_path, str(time.time()).replace('.', '') + '-pre_inline.html')
            with open(pre_html_file_path, 'w')as f:
                f.write(html.encode('utf-8-sig'))
                log.debug('Dump html file ' + pre_html_file_path)

        prem = premailer.Premailer(html, preserve_inline_attachments=False, base_path='article')
        html = prem.transform(pretty_print=True)

        if log.isEnabledFor(logging.DEBUG):
            html_file_path = os.path.join(self.html_log_path, str(time.time()).replace('.', '') + '-inline.html')
            with open(html_file_path, 'w')as f:
                f.write(html.encode('utf-8-sig'))
                log.debug('Dump inlined html file ' + html_file_path)

        html = html[html.find('')+1:]
        html = html[:html.find('')]

        if log.isEnabledFor(logging.DEBUG):
            cut_html_file_path = os.path.join(self.html_log_path, str(time.time()).replace('.', '') + '-cut_inline.html')
            with open(cut_html_file_path, 'w')as f:
                f.write(html.encode('utf-8-sig'))
github pypa / warehouse / warehouse / email / services.py View on Github external
def from_template(cls, email_name, context, *, request):
        subject = render(f"email/{email_name}/subject.txt", context, request=request)
        body_text = render(f"email/{email_name}/body.txt", context, request=request)

        try:
            body_html = render(
                f"email/{email_name}/body.html", context, request=request
            )
            body_html = premailer.Premailer(body_html, remove_classes=True).transform()
        # Catching TemplateNotFound here is a bit of a leaky abstraction, but there's
        # not much we can do about it.
        except TemplateNotFound:
            body_html = None

        return cls(subject=subject, body_text=body_text, body_html=body_html)