本文整理汇总了Python中pynliner.fromString函数的典型用法代码示例。如果您正苦于以下问题:Python fromString函数的具体用法?Python fromString怎么用?Python fromString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fromString函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: notify_members
def notify_members(self, group, event, fail_silently=True):
project = group.project
interface_list = []
for interface in event.interfaces.itervalues():
body = interface.to_string(event)
if not body:
continue
interface_list.append((interface.get_title(), body))
subject = '[%s] %s: %s' % (project.name, event.get_level_display().upper(), event.message)
link = '%s/%d/group/%d/' % (settings.URL_PREFIX, group.project_id, group.id)
body = render_to_string('sentry/emails/error.txt', {
'group': group,
'event': event,
'link': link,
'interfaces': interface_list,
})
html_body = pynliner.fromString(render_to_string('sentry/emails/error.html', {
'group': group,
'event': event,
'link': link,
'interfaces': interface_list,
}))
self._send_mail(
subject=subject,
body=body,
html_body=html_body,
project=project,
fail_silently=fail_silently,
)
开发者ID:Erkan-Yilmaz,项目名称:sentry,代码行数:34,代码来源:__init__.py
示例2: saveFiles
def saveFiles():
from app import updateDB, app, matches
if matches:
matches = matches['matches']
print matches
updateDB()
freezer = Freezer(app)
# Create static html files
freezer.freeze()
with open('build/index.html','r') as html:
output = fromString(html.read())
with open('build/send.html','w') as send_file:
send_file.write(output)
with open('build/send.txt','wb') as f:
keys = matches[0].keys()
dict_writer = csv.DictWriter(f, keys)
dict_writer.writeheader()
dict_writer.writerows(matches)
return True
else:
print 'Looks like something wrong with date in initial URL, nothing saved'
return False
开发者ID:kolgusheva,项目名称:edgar-sec-scraping,代码行数:26,代码来源:frozenapp.py
示例3: format
def format(data):
'''
Will throw exception if data does not match expected structure (that is,
if the template rendering fails).
'''
# The values in `data` come directly from the user, so we shouldn't trust
# them enough to put them directly in to a filename.
platform = 'windows' if data['Metadata']['platform'] == 'windows' else 'android'
version = int(data['Metadata']['version'])
template_filename = 'templates/template_%s_%d.mako' % (platform, version)
if template_filename not in _cached_templates:
template_lookup = TemplateLookup(directories=['.'])
# SECURITY IMPORTANT: `'h'` in the `default_filters` list causes HTML
# escaping to be applied to all expression tags (${...}) in this
# template. Because we're output untrusted user-supplied data, this is
# essential.
_cached_templates[template_filename] = Template(filename=template_filename,
default_filters=['unicode', 'h'],
lookup=template_lookup)
try:
rendered = _cached_templates[template_filename].render(data=data)
except:
raise Exception(exceptions.text_error_template().render())
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
return rendered
开发者ID:PowerOlive,项目名称:mail-responder,代码行数:33,代码来源:mailformatter.py
示例4: send_mail
def send_mail(template_prefix, from_email, recipient_list, template_context, fail_silently=False, **kwargs):
# Sends a templated HTML email.
#
# Unrecognized arguments are passed on to Django's EmailMultiAlternatives's init method.
# add default template context variables from settings.DEFAULT_TEMPLATE_CONTEXT
template_context = build_template_context(template_context)
# subject
subject = render_to_string(template_prefix + '_subject.txt', template_context)
subject = ''.join(subject.splitlines()) # remove superfluous line breaks
# Add subject as a new context variable, and it is used in the base HTML template's title tag.
template_context['subject'] = subject
# body
text_body = render_to_string(template_prefix + '.txt', template_context)
html_body = render_to_string(template_prefix + '.html', template_context)
# inline HTML styles because some mail clients dont process the <style> tag
html_body = pynliner.fromString(html_body)
# construct MIME message
msg = EmailMultiAlternatives(
subject=subject,
body=text_body,
from_email=from_email,
to=recipient_list,
**kwargs
)
msg.attach_alternative(html_body, "text/html")
# send!
msg.send(fail_silently=fail_silently)
开发者ID:sbellem,项目名称:django-html-emailer,代码行数:34,代码来源:__init__.py
示例5: render_mail
def render_mail(data):
'''
Will throw exception if data does not match expected structure (that is,
if the template rendering fails).
'''
template_filename = 'psi_mail_stats.mako'
template_lookup = TemplateLookup(directories=[os.path.dirname(os.path.abspath(__file__))])
# SECURITY IMPORTANT: `'h'` in the `default_filters` list causes HTML
# escaping to be applied to all expression tags (${...}) in this
# template. Because we're output untrusted user-supplied data, this is
# essential.
template = Template(filename=template_filename,
default_filters=['unicode', 'h'],
lookup=template_lookup)
try:
rendered = template.render(data=data)
except:
raise Exception(exceptions.text_error_template().render())
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
return rendered
开发者ID:PowerOlive,项目名称:mail-responder,代码行数:26,代码来源:psi_mail_stats.py
示例6: sendmail
def sendmail(template, to, subject, headers=None, **kwargs):
"""
Sends an email with the selected html template.
html templates can be found inside the broadguage/templates
directory.
Params:
=======
template: str
Link to the html file to be used as template. The html
file is parsed by Jinja Templating before sending to the
recipient.
Keyword Args:
=============
to: str
Recipient's email
sub: str
Subject of the mail
P.S: Other keywords are sent to Jinja Templating Language for
direct parsing, as it is.
Example:
>>> from sendmail import sendmail
>>> sendmail("emails/trainers/welcome.html",to=..."some_email.com",
sub="Hey Friend!", variable1=var, variable2=var2)
Email sent to some_email.com
"""
if not web.config.get('smtp_server'):
# TODO: log warn message
return
html = render_template(template, **kwargs)
# inline CSS to make mail clients happy
html = pynliner.fromString(html)
envelope = Envelope(
from_addr=web.config.from_address,
to_addr=to,
subject=subject,
html_body=html,
headers=headers
)
server = web.config.smtp_server
port = int(web.config.get('smtp_port', 25))
username = web.config.smtp_username
password = web.config.get('smtp_password')
tls = web.config.get('smtp_starttls', False)
result = envelope.send(
host=server,
port=port,
login=username,
password=password,
tls=tls)
return result
开发者ID:iambibhas,项目名称:broadgauge,代码行数:60,代码来源:sendmail.py
示例7: convert_one
def convert_one(part, config, charset):
text = part.get_payload(decode=True)
if part.get_charset():
charset = get_charset_from_message_fragment(part)
if not isinstance(text, six.text_type):
# decode=True only decodes the base64/uuencoded nature, and
# will always return bytes; gotta decode it
if charset is not None:
text = text.decode(charset)
else:
try:
text = text.decode('ascii')
except UnicodeError:
# this is because of message.py:278 and seems like a hack
text = text.decode('raw-unicode-escape')
if not text.startswith('!m'):
return None
text = re.sub(r'\s*!m\s*', '', text, re.M)
if '\n-- \n' in text:
pre_signature, signature = text.split('\n-- \n')
md = markdown.markdown(pre_signature, output_format="html5")
md += '\n<div class="signature" style="font-size: small"><p>-- <br />'
md += '<br />'.join(signature.split('\n'))
md += '</p></div>'
else:
md = markdown.markdown(text)
if config.css:
md = '<style>' + config.css + '</style>' + md
md = pynliner.fromString(md)
message = MIMEText(md, 'html', _charset="UTF-8")
return message
开发者ID:Roguelazer,项目名称:muttdown,代码行数:31,代码来源:main.py
示例8: _render_email
def _render_email(template_name, data):
rendered = _templates[template_name].render(data=data)
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
return rendered
开发者ID:PowerOlive,项目名称:mail-responder,代码行数:7,代码来源:statschecker.py
示例9: _send
def _send(recipient_pks, recipient_emails, template_path, context, from_email,
fail_silently):
recipients = list(User.objects.filter(pk__in=recipient_pks))
recipients += recipient_emails
current_language = get_language()
current_site = Site.objects.get(id=settings.SITE_ID)
default_context = context or {}
default_context["current_site"] = current_site
default_context["STATIC_URL"] = settings.STATIC_URL
subject_path = "%s/short.txt" % template_path
text_path = "%s/email.txt" % template_path
html_path = "%s/email.html" % template_path
for recipient in recipients:
# if it is user, get the email and switch the language
if isinstance(recipient, User):
email = recipient.email
try:
language = get_users_language(recipient)
except LanguageStoreNotAvailable:
language = None
if language is not None:
# activate the user's language
activate(language)
else:
email = recipient
# populate per-recipient context
context = Context(default_context)
context['recipient'] = recipient
context['email'] = email
# load email text and subject
subject = render_to_string(subject_path, context)
subject = "".join(subject.splitlines()) # this must be a single line
text = render_to_string(text_path, context)
msg = EmailMultiAlternatives(subject, text, from_email, [email])
# try to attach the html variant
try:
body = render_to_string(html_path, context)
if getattr(settings, "TEMPLATEDEMAILS_USE_PYNLINER", False):
import pynliner
body = pynliner.fromString(body)
msg.attach_alternative(body, "text/html")
except TemplateDoesNotExist:
logging.info("Email sent without HTML, since %s not found" % html_path)
msg.send(fail_silently=fail_silently)
# reset environment to original language
if isinstance(recipient, User):
activate(current_language)
开发者ID:hannesstruss,项目名称:templated-emails,代码行数:58,代码来源:utils.py
示例10: send
def send(self, extra_context=None, from_email=None, headers=None):
if extra_context is None:
extra_context = {}
if from_email is None:
from_email = settings.DEFAULT_FROM_EMAIL
user = self.recipient
notice_type = self.notice_type
formats = (
"short.txt",
"full.txt",
"full.html",
)
context = NotificationContext({
"recipient": user,
"sender": self.sender,
})
context.update(extra_context)
# get prerendered format messages
messages = get_formatted_messages(formats, notice_type.label, context)
# Strip newlines from subject
subject = "".join(render_to_string("notification/email_subject.txt", {
"message": messages["short.txt"],
}, context).splitlines())
subject = u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)
body = render_to_string("notification/email_body.txt", {
"message": messages["full.txt"],
}, context)
if self.can_send(medium="1"):
recipients = [user.email]
if messages['full.html']:
from django.core.mail import EmailMultiAlternatives
# check if premailer is enabled
if settings.NOTIFICATION_USE_PYNLINER:
import pynliner
messages['full.html'] = pynliner.fromString(messages['full.html'])
msg = EmailMultiAlternatives(subject, body, from_email, recipients,
headers=headers)
msg.attach_alternative(messages['full.html'], "text/html")
msg.send()
else:
from django.core.mail.message import EmailMessage
msg = EmailMessage(subject, body, from_email, recipients,
headers=headers)
msg.send()
开发者ID:hyperweek,项目名称:django-notification,代码行数:53,代码来源:models.py
示例11: export_templates
def export_templates(css_path):
clean()
css = u'<style type="text/css">\n%s\n</style>' % open(css_path).read()
copy_tree(SOURCE_DIR, TARGET_DIR)
for dirpath, dirnames, filenames in os.walk(TARGET_DIR):
for fpath in (dirpath + f for f in filenames if f.endswith('.html')):
contents = open(fpath).read()
contents = re.sub(ur'''<style.+?</style>''', css, contents, 1)
contents = pynliner.fromString(contents)
with open(fpath, 'w') as f:
f.write(contents.encode('utf-8'))
开发者ID:Gidsy,项目名称:gidsy-desk-templates,代码行数:14,代码来源:export_email_templates.py
示例12: with_inline_css
def with_inline_css(html_without_css):
"""Returns html with inline css if the css file path exists
else returns html with out the inline css.
"""
css_filepath = settings.NOTIFICATION_EMAIL_CSS
if not css_filepath.startswith('/'):
css_filepath = file_path_finder(settings.NOTIFICATION_EMAIL_CSS)
if css_filepath:
with open(css_filepath, "r") as _file:
css_content = _file.read()
# insert style tag in the html and run pyliner.
html_with_inline_css = pynliner.fromString('<style>' + css_content + '</style>' + html_without_css)
return html_with_inline_css
return html_without_css
开发者ID:Rosivania,项目名称:edx-platform,代码行数:17,代码来源:email_utils.py
示例13: sendmail_with_template
def sendmail_with_template(
template, to, subject,
cc=None, bcc=None, headers=None, **kwargs
):
"""
Sends an email with the selected html template.
html templates can be found inside the broadgauge/templates
directory.
Params:
=======
template: str
Link to the html file to be used as template. The html
file is parsed by Jinja Templating before sending to the
recipient.
Keyword Args:
=============
to: str
Recipient's email
sub: str
Subject of the mail
P.S: Other keywords are sent to Jinja Templating Language for
direct parsing, as it is.
Example:
>>> from sendmail import sendmail
>>> sendmail("emails/trainers/welcome.html",to=..."some_email.com",
sub="Hey Friend!", variable1=var, variable2=var2)
Email sent to some_email.com
"""
html = render_template(template, **kwargs)
# inline CSS to make mail clients happy
html = pynliner.fromString(html)
return sendmail(to_address=to,
subject=subject,
message_html=html,
headers=headers,
cc=cc,
bcc=bcc,
**kwargs)
开发者ID:PythonIreland,项目名称:broadgauge,代码行数:45,代码来源:sendmail.py
示例14: with_inline_css
def with_inline_css(html_without_css):
"""
returns html with inline css if css file path exists
else returns html with out the inline css.
"""
css_filepath = const.NOTIFICATION_DIGEST_EMAIL_CSS
if not css_filepath.startswith('/'):
css_filepath = finders.AppDirectoriesFinder().find(const.NOTIFICATION_DIGEST_EMAIL_CSS)
if css_filepath:
with open(css_filepath, "r") as _file:
css_content = _file.read()
# insert style tag in the html and run pyliner.
html_with_inline_css = pynliner.fromString('<style>' + css_content + '</style>' + html_without_css)
return html_with_inline_css
return html_without_css
开发者ID:muhhshoaib,项目名称:edx-notifications,代码行数:18,代码来源:digests.py
示例15: send_mail
def send_mail(record):
template_filename = 'psi_mail_hosts_load.mako'
template_lookup = TemplateLookup(directories=[os.path.dirname(os.path.abspath('__file__'))])
# SECURITY IMPORTANT: `'h'` in the `default_filters` list causes HTML
# escaping to be applied to all expression tags (${...}) in this
# template. Because we're output untrusted user-supplied data, this is
# essential.
template = Template(filename=template_filename, default_filters=['unicode', 'h'], lookup=template_lookup)
try:
rendered = template.render(data=record)
except:
raise Exception(exceptions.text_error_template().render())
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
log_diagnostics('Sending email...')
sender.send(config['statsEmailRecipients'], config['emailUsername'], 'Psiphon 3 Host Load Stats', repr(record), rendered)
log_diagnostics('Email sent.')
开发者ID:projectarkc,项目名称:psiphon,代码行数:18,代码来源:load.py
示例16: send_mail
def send_mail(record, subject='PSI Ansible Report',
template_filename=MAKO_TEMPLATE):
if not os.path.isfile(template_filename):
raise
template_lookup = TemplateLookup(directories=[os.path.dirname(os.path.abspath('__file__'))])
template = Template(filename=template_filename, default_filters=['unicode', 'h'], lookup=template_lookup)
try:
rendered = template.render(data=record)
except:
raise Exception(exceptions.text_error_template().render())
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
sender.send(config['emailRecipients'], config['emailUsername'], subject, None, rendered)
开发者ID:projectarkc,项目名称:psiphon,代码行数:18,代码来源:psi_ansible.py
示例17: _render_email
def _render_email(data):
logger.debug_log('_render_email: enter')
global _template
if not _template:
_template = Template(filename='templates/feedback_response.mako',
default_filters=['unicode', 'h', 'decode.utf8'],
input_encoding='utf-8', output_encoding='utf-8',
lookup=TemplateLookup(directories=['.']))
logger.debug_log('_render_email: template loaded')
rendered = _template.render(data=data)
# CSS in email HTML must be inline
rendered = pynliner.fromString(rendered)
logger.debug_log('_render_email: exiting with len(rendered)=%d' % len(rendered))
return rendered
开发者ID:projectarkc,项目名称:psiphon,代码行数:19,代码来源:autoresponder.py
示例18: sendmail
def sendmail(to_address, subject, message, message_html=None, reply_to=None, cc=None, bcc=None):
if 'SMTP_SERVER' not in app.config:
app.logger.warn("SMTP_SERVER config is not set, ignoring sendmail...")
return
app.logger.info("sending mail to %s with subject %r", to_address, subject)
headers = {}
if reply_to:
headers['Reply-To'] = reply_to
if message_html:
message_html = pynliner.fromString(message_html)
if Unsubscribe.contains(to_address):
app.logger.warn("%s is in the unsubscribed list. Not sending email.", to_address)
return
envelope = Envelope(
from_addr=app.config['FROM_ADDRESS'],
to_addr=to_address,
subject=subject,
text_body=message,
html_body=message_html,
headers=headers,
cc_addr=cc,
bcc_addr=bcc
)
server = app.config['SMTP_SERVER']
port = app.config.get('SMTP_PORT', 25)
username = app.config['SMTP_USERNAME']
password = app.config['SMTP_PASSWORD']
tls = app.config.get('SMTP_STARTTLS', False)
envelope.send(
host=server,
port=port,
login=username,
password=password,
tls=tls)
app.logger.info("mail sent to %s with subject %r", to_address, subject)
开发者ID:anandjanki,项目名称:cleansweep,代码行数:41,代码来源:mailer.py
示例19: run
def run(self):
recipient = self.recipient
if isinstance(recipient, get_user_model()):
email = recipient.email
try:
language = get_users_language(recipient)
except LanguageStoreNotAvailable:
language = None
if language is not None:
activate(language)
else:
email = recipient
# populate per-recipient context
context = Context(self.default_context)
context['recipient'] = recipient
context['email'] = email
# load email subject, strip and remove line breaks
subject = render_to_string(self.subject_path, context).strip()
subject = "".join(subject.splitlines()) # this must be a single line
text = render_to_string(self.text_path, context)
msg = EmailMultiAlternatives(
subject, text, self.from_email, [email], headers=self.extra_headers)
# try to attach the html variant
try:
body = render_to_string(self.html_path, context)
if pynliner:
body = pynliner.fromString(body)
msg.attach_alternative(body, "text/html")
except TemplateDoesNotExist:
logging.info("Email sent without HTML, since %s not found" % self.html_path)
msg.send(fail_silently=self.fail_silently)
# reset environment to original language
if isinstance(recipient, get_user_model()):
activate(self.current_language)
开发者ID:sprymak,项目名称:templated-emails,代码行数:41,代码来源:utils.py
示例20: convert_one
def convert_one(part, config):
try:
text = part.get_payload(None, True)
if not text.startswith('!m'):
return None
text = re.sub('\s*!m\s*', '', text, re.M)
if '\n-- \n' in text:
pre_signature, signature = text.split('\n-- \n')
md = markdown.markdown(pre_signature, output_format="html5")
md += '\n<div class="signature" style="font-size: small"><p>-- <br />'
md += '<br />'.join(signature.split('\n'))
md += '</p></div>'
else:
md = markdown.markdown(text)
if config.css:
md = '<style>' + config.css + '</style>' + md
md = pynliner.fromString(md)
message = MIMEText(md, 'html')
return message
except Exception:
return None
开发者ID:Eising,项目名称:muttdown,代码行数:21,代码来源:main.py
注:本文中的pynliner.fromString函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论