コード例 #1
0
def send_mail(subject,
              template_name,
              context_dict,
              from_email=None,
              to_emails=None,
              language_code=None):
    """
    Send email with specified template and context.
    """
    if not to_emails:
        LOG.warning("Email will not be sent: no recipients were specified")
        return
    from_email = from_email or settings.DEFAULT_FROM_EMAIL

    if language_code:
        activate(language_code)
        html_part = render_to_string(template_name, context_dict)
        deactivate()
    else:
        html_part = render_to_string(template_name, context_dict)
    text_part = strip_tags(html_part).strip()

    msg = EmailMultiAlternatives(subject, text_part, from_email, to_emails)
    msg.attach_alternative(html_part, "text/html")

    try:
        msg.send(fail_silently=False)
        return True
    except Exception as e:
        LOG.error('Failed to send message to {to}: {err}'.format(
            to=repr(to_emails), err=unicode(e)))
        return False
コード例 #2
0
    def send_mail(self, template_prefix, email, context):
        """
        Sends an e-mail to `email`.  `template_prefix` identifies the
        e-mail that is to be sent, e.g. "account/email/email_confirmation"
        """
        subject = render_to_string('{0}_subject.txt'.format(template_prefix),
                                   context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()
        subject = self.format_email_subject(subject)

        bodies = {}
        for ext in ['html', 'txt']:
            try:
                template_name = '{0}_message.{1}'.format(template_prefix, ext)
                bodies[ext] = render_to_string(template_name,
                                               context).strip()
            except TemplateNotFound:
                if ext == 'txt' and not bodies:
                    # We need at least one body
                    raise
        if 'txt' in bodies:
            msg = EmailMultiAlternatives(subject, 
                                         bodies['txt'], 
                                         settings.DEFAULT_FROM_EMAIL,
                                         [email])
            if 'html' in bodies:
                msg.attach_alternative(bodies['html'], 'text/html')
        else:
            msg = EmailMessage(subject, 
                               bodies['html'], 
                               settings.DEFAULT_FROM_EMAIL, 
                               [email])
            msg.content_subtype = 'html'  # Main content is now text/html
        msg.send()
コード例 #3
0
ファイル: models.py プロジェクト: gabrielx52/baph
    def send_activation_email(self):
        """
        Sends a activation email to the user.

        This email is send when the user wants to activate their newly created
        user.

        """
        context = {'user': self.user,
                  'without_usernames': settings.BAPH_AUTH_WITHOUT_USERNAMES,
                  'protocol': get_protocol(),
                  'activation_days': settings.BAPH_ACTIVATION_DAYS,
                  'activation_key': self.activation_key,
                  'org': Organization.get_current(),
                  }

        subject = render_to_string('registration/emails/activation_email_subject.txt',
                                   context)
        subject = ''.join(subject.splitlines())

        message = render_to_string('registration/emails/activation_email_message.txt',
                                   context)
        send_mail(subject,
                  message,
                  django_settings.DEFAULT_FROM_EMAIL,
                  [self.user.email, ])
コード例 #4
0
 def _pre_test_email(self):
     template = 'piston/mails/consumer_%s.txt' % self.consumer.status
     try:
         render_to_string(template, {
             'consumer': self.consumer,
             'user': self.cuser,
         })
         return True
     except TemplateNotFound:
         '''They haven't set up the templates, which means they might not
         want these emails sent.
         '''
         return False
コード例 #5
0
ファイル: forms.py プロジェクト: ReadBox/readbox
    def send_activation_mail(self):
        context = dict(
            user=self.user,
        )
        rendered_body = shortcuts.render_to_string(
            'auth/email/activation_body.txt', context)
        rendered_subjet = shortcuts.render_to_string(
            'auth/email/activation_subject.txt', context)

        mail.send_mail(
            rendered_subjet,
            rendered_body,
            settings.DEFAULT_FROM_EMAIL,
            [self.user.email],
        )
コード例 #6
0
ファイル: forms.py プロジェクト: ReadBox/readbox
    def send_reset_mail(self, user):
        context = dict(
            user=user,
        )
        rendered_body = shortcuts.render_to_string(
            'auth/email/reset_body.txt', context)
        rendered_subjet = shortcuts.render_to_string(
            'auth/email/reset_subject.txt', context)

        mail.send_mail(
            rendered_subjet,
            rendered_body,
            settings.DEFAULT_FROM_EMAIL,
            [user.email],
        )
コード例 #7
0
  def build(self, context, headers=None):

    # Activate language
    translation.activate(self.language)

    # Render template
    site = get_current_site(None)
    message = u'Envoyé via %s' % site
    context.update({
      'site' : site,
    })
    mail_html = render_to_string(self.template, context)
    if settings.DEBUG:
      self.dump(mail_html)

    # Configure mail
    mail = EmailMultiAlternatives(self.subject, message, headers=headers)
    mail.to = self.to
    mail.cc = self.cc

    # Attach the rendered html
    mail.attach_alternative(mail_html, 'text/html')

    # Do not send, it's responsability of caller
    return mail
コード例 #8
0
 def paginate(request, queryset_or_list, per_page=25):
     context_instance = RequestContext(request)
     context = paginate_func(request, queryset_or_list, per_page)
     paging = Markup(
         render_to_string('paging/pager.html', context, context_instance))
     return dict(objects=context['paginator'].get('objects', []),
                 paging=paging)
コード例 #9
0
 def media_js(self, request):
     settings = self.get_settings()
     request_parameters = settings.get('REQUEST_PARAMETERS', {})
     ctx = { 'request_parameters': json.dumps(request_parameters) }
     return render_to_string('persona/auth.html',
                             ctx,
                             RequestContext(request))
コード例 #10
0
def paginate(context,
             queryset_or_list,
             request,
             asvar,
             per_page=25,
             is_endless=True):
    """{% paginate queryset_or_list from request as foo[ per_page 25][ is_endless False %}"""

    from django.template.loader import render_to_string

    context_instance = RequestContext(request)
    paging_context = paginate_func(request,
                                   queryset_or_list,
                                   per_page,
                                   endless=is_endless)
    paging = mark_safe(
        render_to_string('paging/pager.html', paging_context,
                         context_instance))

    result = dict(objects=paging_context['paginator'].get('objects', []),
                  paging=paging,
                  paginator=paging_context['paginator'])
    if asvar:
        context[asvar] = result
        return ''
    return result
コード例 #11
0
ファイル: forms.py プロジェクト: dieselmachine/baph
 def save(self,
          domain_override=None,
          email_template_name='registration/password_reset_email.html',
          use_https=False,
          token_generator=default_token_generator,
          request=None):
     '''Generates a one-use only link for resetting password and sends to
     the user.
     '''
     from django.core.mail import send_mail
     for user in self.users_cache:
         if not domain_override:
             current_site = get_current_site(request)
             site_name = current_site.name
             domain = current_site.domain
         else:
             site_name = domain = domain_override
         c = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': int_to_base36(user.id.int),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': use_https and 'https' or 'http',
         }
         body = render_to_string(email_template_name, c)
         send_mail(
             _("Password reset on %s") % site_name, body, None,
             [user.email])
コード例 #12
0
ファイル: views.py プロジェクト: ricree/Mafiastats
def buildPlayerGraph(player, playerset, teamset):
    if player.id in playerset:
        return
    playerset.add(player.id)
    node = cache.get("mafiastats_player_graph_" + str(player.id))
    teams = player.team_set.all()
    if not node:
        wonlist = [t for t in teams if t.won]
        lostlist = [t for t in teams if not t.won]
        adj = [{"nodeTo": "t" + str(team.id), "data": {}} for team in teams]
        node = {
            "id": "p" + str(player.id),
            "name": player.name,
            "data": {
                "infobox": render_to_string(
                    "playerGraphInfo.html", {"player": player, "wonlist": wonlist, "lostlist": lostlist}
                )
            },
            "adjacencies": adj,
        }
        cache.set("mafiastats_player_graph_" + str(player.id), node, 30 * 60)
    yield node
    for team in teams:
        for n in buildTeamGraph(team, playerset, teamset):
            yield n
コード例 #13
0
def render_to_string(template, context, request=None):
    if request:
        context_instance = RequestContext(request)
    else:
        context_instance = None

    return shortcuts.render_to_string(template, context, context_instance)
コード例 #14
0
def render_to_string(request, template, context):
    if request:
        context_instance = RequestContext(request)
    else:
        context_instance = None

    return shortcuts.render_to_string(template, context, context_instance)
コード例 #15
0
ファイル: models.py プロジェクト: gabrielx52/baph
    def send_confirmation_email(self):
        """
        Sends an email to confirm the new email address.

        This method sends out two emails. One to the new email address that
        contains the ``email_confirmation_key`` which is used to verify this
        this email address with :func:`UserenaUser.objects.confirm_email`.

        The other email is to the old email address to let the user know that
        a request is made to change this email address.

        """
        context = {'user': self.user,
                  'without_usernames': settings.BAPH_AUTH_WITHOUT_USERNAMES,
                  'new_email': self.email_unconfirmed,
                  'protocol': get_protocol(),
                  'confirmation_key': self.email_confirmation_key,
                  'org': Organization.get_current(),
                  }

        # Email to the old address, if present
        subject_old = render_to_string(
            'registration/emails/confirmation_email_subject_old.txt', context)
        subject_old = ''.join(subject_old.splitlines())

        message_old = render_to_string(
            'registration/emails/confirmation_email_message_old.txt', context)
        if self.user.email:
            send_mail(subject_old,
                      message_old,
                      django_settings.DEFAULT_FROM_EMAIL,
                    [self.user.email])

        # Email to the new address
        subject_new = render_to_string(
            'registration/emails/confirmation_email_subject_new.txt', context)
        subject_new = ''.join(subject_new.splitlines())

        message_new = render_to_string(
            'registration/emails/confirmation_email_message_new.txt', context)

        send_mail(subject_new,
                  message_new,
                  django_settings.DEFAULT_FROM_EMAIL,
                  [self.email_unconfirmed, ])
コード例 #16
0
ファイル: misc_tools.py プロジェクト: collingreen/startuppong
def send_html_email(template_path, context, subject, from_email, to_emails):
    """Renders an email template using render_to_string twice, once with render_type = 'text'
    and once with render_type = 'html', then sends an email with the given parameters
    with a text/html alternative."""

    # render templates
    context['render_type'] = 'text'
    text_content = render_to_string(template_path, context)
    context['render_type'] = 'html'
    html_content = render_to_string(template_path, context)
    html_content = defaultfilters.linebreaks(html_content)

    # send email
    message = EmailMultiAlternatives(subject, text_content, from_email, to_emails)
    message.attach_alternative(html_content, 'text/html')
    message.send()

    return True
コード例 #17
0
ファイル: misc_tools.py プロジェクト: collingreen/startuppong
def mail_admins_template(subject, template, context, fail_silently=False, connection=None, html_template=None):
    """Accepts a subject, template, context, (and optionally fail_silently,
    connection, and html_template), renders the template(s) using the context,
    and mails the admins using the templates and parameters via django.core.mail.mail_admins"""

    # render the message template - or fall back to blank if none given - requires html_template
    if not template and html_template:
        message = ''
    else:
        message = render_to_string(template, context)

    # renders html_template if applicable
    html_message = None
    if html_template:
        html_message = render_to_string(html_template, context)

    # sends the email
    mail_admins(subject, message, fail_silently, connection, html_message)
コード例 #18
0
ファイル: misc_tools.py プロジェクト: ssung1/startuppong
def send_html_email(template_path, context, subject, from_email, to_emails):
    """Renders an email template using render_to_string twice, once with render_type = 'text'
    and once with render_type = 'html', then sends an email with the given parameters
    with a text/html alternative."""

    # render templates
    context['render_type'] = 'text'
    text_content = render_to_string(template_path, context)
    context['render_type'] = 'html'
    html_content = render_to_string(template_path, context)
    html_content = defaultfilters.linebreaks(html_content)

    # send email
    message = EmailMultiAlternatives(subject, text_content, from_email,
                                     to_emails)
    message.attach_alternative(html_content, 'text/html')
    message.send()

    return True
コード例 #19
0
ファイル: __init__.py プロジェクト: iconfinder/paloma
    def render_template(self, template_name, context):
        """Render a template.

        :param template_name: Template name.
        :type template_name: str
        :param context: Context.
        :returns: the rendered template.
        """

        return render_to_string(template_name, context)
コード例 #20
0
 def add_message(self, request, level, message_template, message_context={}, extra_tags=''):
     """
     Wrapper of `django.contrib.messages.add_message`, that reads
     the message text from a template.
     """
     try:
         message = render_to_string(message_template,
                                    message_context).strip()
         if message:
             messages.add_message(request, level, message, extra_tags=extra_tags)
     except TemplateNotFound:
         pass
コード例 #21
0
ファイル: middleware.py プロジェクト: Govexec/django-fatpages
def page_404(request):

    view_vars = {
        "page":  Page({
        "category": None,
        "title": '404',
        }, request, ad_settings=settings.DART_AD_DEFAULTS),
        'gpt': {
            'ad_unit': '/{}/{}'.format(settings.GPT_NETWORK_CODE, settings.GPT_BASE_AD_UNIT_PATH),
        }
    }


    if settings.SITE_NAME == "Nextgov":
        return HttpResponseNotFound(render_to_string("nextgov/content/main/404.html", view_vars, context_instance=RequestContext(request)))
    elif settings.SITE_NAME == "Defense One":
        return HttpResponseNotFound(render_to_string("defenseone/content/main/404.html", view_vars, context_instance=RequestContext(request)))
    elif settings.SITE_NAME == "Route Fifty":
        return HttpResponseNotFound(render_to_string("route_fifty/404.html", view_vars, context_instance=RequestContext(request)))
    else:
        return HttpResponseNotFound(render_to_string("content/main/404.html", view_vars, context_instance=RequestContext(request)))
コード例 #22
0
ファイル: djangojinja2.py プロジェクト: funkotron/kaizen
def render_to_string(template_name, context=None, request=None,
                     processors=None):
    """Render a template into a string."""
    context = dict(context or {})
    if request is not None:
        context['request'] = request
        context_instance = RequestContext(request)
        for processor in chain(get_standard_processors(), processors or ()):
            context.update(processor(request)) 
    else:
        context_instance = None
    return shortcuts.render_to_string(template_name, context, context_instance)
コード例 #23
0
ファイル: __init__.py プロジェクト: piquadrat/paloma
    def send(self, to, context={}, tags=None, metadata=None):
        """Send the e-mail.

        :param to: Recipient of the e-mail.
        :param context: Recipient-specific template context.
        """

        # Construct the local context.
        local_context = {}
        if self.context:
            for k, v in self.context.items():
                local_context[k] = v
        if context:
            for k, v in context.items():
                local_context[k] = v

        # Render what needs to be rendered.
        subject = None
        if self.subject_template_name:
            subject = ''.join(render_to_string(self.subject_template_name,
                                               local_context)
                              .strip()
                              .splitlines())

        text_body = render_to_string(self.text_template_name,
                                     local_context).strip()

        html_body = None
        if self.html_template_name:
            html_body = render_to_string(self.html_template_name,
                                         local_context).strip()

        super(TemplateMail, self).send(
            to = to,
            text_body = text_body,
            html_body = html_body,
            subject = subject,
            tags = tags,
            metadata = metadata,
        )
コード例 #24
0
ファイル: helpers.py プロジェクト: La0/beers
    def wrapper(request, *args, **kwargs):
      try:
        context = view_func(request, *args, **kwargs)
        if not context:
          raise Exception('No context generated')
        
        # Skip render on redirect
        if isinstance(context, HttpResponseRedirect):
          return context

        # Add some settings to context
        context['DEBUG'] = DEBUG
        context['IS_AJAX'] = request.is_ajax()
        #context['GOOGLE_ANALYTICS'] = GOOGLE_ANALYTICS

        # Ajax render using json
        if request.is_ajax() and json_template:
          
          # Render the template to html
          html = render_to_string(json_template, context)
          json_data = {
            'status' : 'ok',
            'html' : html,
          }
          
          resp = HttpResponse(mimetype='application/json')
          resp.write(simplejson.dumps(json_data))
            
        # Html render
        elif html_template:
          resp = render_to_response(
            html_template,
            context,
            context_instance=RequestContext(request),
          )
          
        else:
          raise Exception('No template found')
        
      except Exception, e:
        if DEBUG:
          raise
        if request.is_ajax():
          json_data = {'status' : 'error', 'message' : str(e)}
          resp = HttpResponse(mimetype='application/json')
          resp.write(simplejson.dumps(json_data))
        else:
          resp = render_to_response(
            'error.html',
            {'error' : str(e),},
          )
コード例 #25
0
ファイル: forms.py プロジェクト: devhub/baph
 def save(self, domain_override=None,
          subject_template_name='registration/password_reset_subject.txt',
          email_template_name='registration/password_reset_email.html',
          use_https=False, token_generator=default_token_generator,
          from_email=None, request=None):
     '''Generates a one-use only link for resetting password and sends to
     the user.
     '''
     from django.core.mail import send_mail
     for user in self.users_cache:
         if not user.has_usable_password():
             continue
         if not domain_override:
             org = Organization.get_current()
             if isinstance(org, dict):
                 site_name = org['name']
                 domain = org['host']
             else:
                 site_name = org.name
                 domain = org.host
         else:
             site_name = domain = domain_override
         site_name =None
         c = {
             'email': user.email,
             'domain': domain,
             'site_name': site_name,
             'uid': int_to_base36(user.id),
             'user': user,
             'token': token_generator.make_token(user),
             'protocol': use_https and 'https' or 'http',
         }
         subject = render_to_string(subject_template_name, \
                                    RequestContext(request, c))
         subject = ''.join(subject.splitlines())
         email = render_to_string(email_template_name, \
                                  RequestContext(request, c))
         send_mail(subject, email, from_email, [user.email])
コード例 #26
0
def paginate(context, queryset_or_list, request, asvar, per_page=25):
    """{% paginate queryset_or_list from request as foo[ per_page 25] %}"""
    
    from django.template.loader import render_to_string

    context_instance = RequestContext(request)
    paging_context = paginate_func(request, queryset_or_list, per_page)
    paging = mark_safe(render_to_string('paging/pager.html', paging_context, context_instance))

    result = dict(objects=paging_context['paginator'].get('objects', []), paging=paging)
    if asvar:
        context[asvar] = result
        return ''
    return result
コード例 #27
0
ファイル: misc_tools.py プロジェクト: ssung1/startuppong
def mail_admins_template(subject,
                         template,
                         context,
                         fail_silently=False,
                         connection=None,
                         html_template=None):
    """Accepts a subject, template, context, (and optionally fail_silently,
    connection, and html_template), renders the template(s) using the context,
    and mails the admins using the templates and parameters via django.core.mail.mail_admins"""

    # render the message template - or fall back to blank if none given - requires html_template
    if not template and html_template:
        message = ''
    else:
        message = render_to_string(template, context)

    # renders html_template if applicable
    html_message = None
    if html_template:
        html_message = render_to_string(html_template, context)

    # sends the email
    mail_admins(subject, message, fail_silently, connection, html_message)
コード例 #28
0
 def render(self, context, template_name="voter/default_rating.html"):
     obj = self.obj.resolve(context)
     obj_type = self.obj_type.resolve(context)
     if self.user: 
         user = self.user.resolve(context)
     else:
         user = None
     rating, rating_class = get_rating(obj)
     context['rating'] = rating
     context['can_vote'] = can_vote(context['request'].user, user, obj.rating)
     context['rating_class'] = rating_class
     context['obj_id'] = obj.id
     context['obj_type'] = obj_type
     
     return render_to_string(template_name, context)
コード例 #29
0
 def media_js(self, request):
     locale = self.get_locale_for_request(request)
     try:
         app = self.get_app(request)
     except SocialApp.DoesNotExist:
         raise ImproperlyConfigured("No Facebook app configured: please"
                                    " add a SocialApp using the Django"
                                    " admin")
     fb_login_options = self.get_fb_login_options(request)
     ctx =  {'facebook_app': app,
             'facebook_channel_url':
             request.build_absolute_uri(reverse('facebook_channel')),
             'fb_login_options': mark_safe(json.dumps(fb_login_options)),
             'facebook_jssdk_locale': locale}
     return render_to_string('facebook/fbconnect.html',
                             ctx,
                             RequestContext(request))
コード例 #30
0
ファイル: views.py プロジェクト: ricree/Mafiastats
def buildTeamGraph(team, playerset, teamset):
    if team.id in teamset:
        return
    node = cache.get("mafiastats_team_graph_" + str(team.id))
    teamset.add(team.id)
    players = team.players.all()
    if not node:
        templatePlayers = [(player, player.role_set.filter(game=team.game)) for player in players]
        adj = [{"nodeTo": "p" + str(player.id), "data": {}} for player in team.players.all()]
        node = {
            "id": "t" + str(team.id),
            "name": team.title,
            "data": {"infobox": render_to_string("teamGraphInfo.html", {"team": team, "players": templatePlayers})},
            "adjacencies": adj,
        }
        cache.set("mafiastats_team_graph_" + str(team.id), node, 60 * 30)
    yield node
    for player in players:
        for n in buildPlayerGraph(player, playerset, teamset):
            yield n
コード例 #31
0
ファイル: util.py プロジェクト: ernop/wfmu
def r2s(template, context=None):
    from coffin.shortcuts import render_to_string
    return render_to_string(template, dictionary=context)
コード例 #32
0
 def media_js(self, request):
     settings = self.get_settings()
     request_parameters = settings.get('REQUEST_PARAMETERS', {})
     ctx = {'request_parameters': json.dumps(request_parameters)}
     return render_to_string('persona/auth.html', ctx,
                             RequestContext(request))
コード例 #33
0
def render_to_string(template, context, request=None):
    if request:
        context_instance = RequestContext(request)
    else:
        context_instance = None
    return loader.render_to_string(template, context, context_instance)
コード例 #34
0
ファイル: modules.py プロジェクト: appost/treeio
def dajaxice_js_import(context):
    "Thin wrapper for dajaxice"
    
    return Markup(coffinshortcuts.render_to_string('dajaxice/dajaxice_js_import.html',
                                                   dajaxice_orig_tag(context)))
コード例 #35
0
ファイル: modules.py プロジェクト: vovkd/treeio
def dajaxice_js_import(context):
    "Thin wrapper for dajaxice"

    return Markup(
        coffinshortcuts.render_to_string('dajaxice/dajaxice_js_import.html',
                                         dajaxice_orig_tag(context)))
コード例 #36
0
class Reference(unicode):
    def __new__(cls, string, homonym_order=None):
        instance = unicode.__new__(cls, string)
        instance.homonym_order = homonym_order
        return instance

letter_parts = []
part_entries = []
letter = entries3[0][0].lstrip(u' =')[0].upper()
for wordform, group in itertools.groupby(entries3, lambda x: x[0]):
    lst = list(group)
    if wordform.lstrip(u' =')[0].upper() != letter:
        letter_parts.append((letter, part_entries))
        part_entries = []
        letter = wordform.lstrip(u' =')[0].upper()
    if len(lst) < 2:
        wordform, reference, lexeme = lst[0]
        part_entries.append((reference, lexeme))
    else:
        for i, (wordform, reference, lexeme) in enumerate(lst):
            if reference:
                reference = Reference(reference, homonym_order=i+1)
            else:
                lexeme.homonym_order = i + 1
            part_entries.append((reference, lexeme))
letter_parts.append((letter, part_entries))

xml = render_to_string('indesign/slavdict.xml', {'letter_parts': letter_parts})
sys.stdout.write(xml.encode('utf-8'))
sys.exit(0)
コード例 #37
0
ファイル: trackerutils.py プロジェクト: ernop/tracker
def r2s(template, context=None):
    from coffin.shortcuts import render_to_string
    #fake=FakeRequestContext(None, dict_=context)
    from django.conf import settings
    return render_to_string(template, dictionary=context)
コード例 #38
0
ファイル: jinja.py プロジェクト: akatrevorjay/solarsanweb
 def render(self, context):
     return jinja_shortcuts.render_to_string(self.filename, context)
コード例 #39
0
ファイル: jinja.py プロジェクト: WoLpH/coffin
 def render(self, context):
     from coffin import shortcuts
     return shortcuts.render_to_string(self.filename, context)
コード例 #40
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def paginate(request, queryset_or_list, per_page=25):
     context_instance = RequestContext(request)
     context = paginate_func(request, queryset_or_list, per_page)
     paging = Markup(render_to_string('paging/pager.html', context, context_instance))
     return dict(objects=context['paginator'].get('objects', []), paging=paging)