Exemplo n.º 1
0
def notify_topic_subscribers(post):
    topic = post.topic
    old_lang = translation.get_language()

    # Define constants for templates rendering
    context_vars = {
        'delete_url': reverse('pybb:delete_subscription',
                              args=[post.topic.id]),
        'site_url': get_setting('site', 'global', 'siteurl'),
        'is_new_topic': post == topic.head,
        'post': post,
        'post_url': reverse('pybb:post', args=[post.id]),
        'forum_url': reverse('pybb:forum', args=[topic.forum.id]),
    }
    from_email = settings.DEFAULT_FROM_EMAIL

    mails = tuple()
    if post == topic.head:
        subject_template = 'pybb/mail_templates/moderator_email_subject.html'
        users = topic.forum.moderators.all()
    else:
        subject_template = 'pybb/mail_templates/subscription_email_subject.html'
        users = topic.subscribers.exclude(pk=post.user.pk)

    subject = render_to_string(template_name=subject_template,
                               context={
                                   'site_url': context_vars['site_url'],
                                   'post': post,
                                   'topic': topic
                               })
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())

    for user in users:
        message = get_email_message(user, **context_vars)
        if message:
            message = add_tendenci_footer(message, content_type="text")
            mails += ((subject, message, from_email, [user.email]), )

    # Send mails
    send_mass_mail(mails, fail_silently=True)

    # Reactivate previous language
    translation.activate(old_lang)
Exemplo n.º 2
0
def notify_topic_subscribers(post):
    topic = post.topic
    old_lang = translation.get_language()

    # Define constants for templates rendering
    context_vars = {'delete_url': reverse('pybb:delete_subscription', args=[post.topic.id]),
                    'site_url': get_setting('site', 'global', 'siteurl'),
                    'is_new_topic': post == topic.head,
                    'post': post,
                    'post_url': reverse('pybb:post', args=[post.id]),
                    'forum_url': reverse('pybb:forum', args=[topic.forum.id]),
                    }
    from_email = settings.DEFAULT_FROM_EMAIL

    mails = tuple()
    if post == topic.head:
        subject_template = 'pybb/mail_templates/moderator_email_subject.html'
        users = topic.forum.moderators.all()
    else:
        subject_template = 'pybb/mail_templates/subscription_email_subject.html'
        users = topic.subscribers.exclude(pk=post.user.pk)

    subject = render_to_string(subject_template,
                                   {'site_url': context_vars['site_url'],
                                    'post': post,
                                    'topic': topic})
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())

    for user in users:
        message = get_email_message(user, **context_vars)
        if message:
            message = add_tendenci_footer(message, content_type="text")
            mails += ((subject, message, from_email, [user.email]),)

    # Send mails
    send_mass_mail(mails, fail_silently=True)

    # Reactivate previous language
    translation.activate(old_lang)
Exemplo n.º 3
0
    def send(self, fail_silently=False, **kwargs):
        recipient_list = []
        recipient_bcc_list = []
        headers = kwargs.get('headers', {})
        attachments = kwargs.get('attachments', [])

        if isinstance(self.recipient, str):
            recipient_list = self.recipient.split(',')
            recipient_list = [
                recipient.strip() for recipient in recipient_list
                if recipient.strip() != ''
            ]
        else:
            recipient_list = list(self.recipient)
        if isinstance(self.recipient_cc, str):
            recipient_cc_list = self.recipient_cc.split(',')
            recipient_cc_list = [
                recipient_cc.strip() for recipient_cc in recipient_cc_list
                if recipient_cc.strip() != ''
            ]
            recipient_list += recipient_cc_list
        else:
            recipient_list += list(self.recipient_cc)
        if isinstance(self.recipient_bcc, str):
            recipient_bcc_list = self.recipient_bcc.split(',')
            recipient_bcc_list = [
                recipient_bcc.strip() for recipient_bcc in recipient_bcc_list
                if recipient_bcc.strip() != ''
            ]
        else:
            recipient_bcc_list = list(self.recipient_bcc)

        if self.reply_to:
            headers['Reply-To'] = self.reply_to
        if not self.sender:
            self.sender = get_setting(
                'site', 'global',
                'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if self.sender_display:
            # Add quotes around display name to prevent errors on sending
            # When display name contains comma or other control characters,
            headers['From'] = '"%s"<%s>' % (self.sender_display, self.sender)
        if self.priority and self.priority == 1:
            headers['X-Priority'] = '1'
            headers['X-MSMail-Priority'] = 'High'

        # remove blocked from recipient_list and recipient_bcc_list
        temp_recipient_list = copy.copy(recipient_list)
        for e in temp_recipient_list:
            if self.is_blocked(e):
                recipient_list.remove(e)
        temp_recipient_bcc_list = copy.copy(recipient_bcc_list)
        for e in temp_recipient_bcc_list:
            if self.is_blocked(e):
                recipient_bcc_list.remove(e)

        if recipient_list or recipient_bcc_list:
            msg = EmailMessage(self.subject,
                               add_tendenci_footer(self.body),
                               self.sender,
                               recipient_list,
                               recipient_bcc_list,
                               headers=headers,
                               connection=kwargs.get('connection', None))
            if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML:
                msg.content_subtype = 'html'
            if attachments:
                msg.attachments = attachments
            msg.send(fail_silently=fail_silently)
Exemplo n.º 4
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            str(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            extra_context.update({
                "user": user,
                "notice": gettext(notice_type.display),
                "notices_url": notices_url,
                "current_site": current_site,
            })

            # test for request in the extra_context
            if 'request' in extra_context:
                request = extra_context['request']
            else:
                request = None

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, extra_context)

            # Strip newlines from subject
            extra_context.update({'message': mark_safe(messages['short'])})
            subject = ''.join(render_to_string(template_name='notification/email_subject.txt',
                context=extra_context, request=request).splitlines())

            extra_context.update({'message': mark_safe(messages['full'])})
            body = render_to_string(template_name='notification/email_body.txt',
                context=extra_context, request=request)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, add_tendenci_footer(body), settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)
Exemplo n.º 5
0
def send_emails(emails, label, extra_context=None, on_site=True):
    """
    This method accepts a list of email addresses
    as opposed to a list of users. This is a custom method
    as opposed to send(), send_now(), and queue()

    Just send the notice to a list of emails immediately.
    No new notice created here
    notification.send_emails(email_list, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    """
    # exclude blocked emails
    emails = [e for e in emails if not Email.is_blocked(e)]
    if not emails:
        return
    
    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except NoticeType.DoesNotExist as err:
        logger.warning('Skipping notification send for "{label}": {err}'.format(
            label=label, err=err))
        # Stop here because we need a notice_type
        return None

    headers = {}
    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        str(current_site),
        reverse("notification_notices"),
    )

    formats = (
        'full.html',
        'short.txt',
        'notice.html',
    )  # TODO make formats configurable

    extra_context.update({
        "notice": gettext(notice_type.display),
        "notices_url": notices_url,
        "current_site": current_site,
        'SITE_GLOBAL_SITEURL': get_setting('site', 'global', 'siteurl'),
        'SITE_GLOBAL_SITEDISPLAYNAME': get_setting('site', 'global', 'sitedisplayname'),
    })

    # test for request in the extra_context
    if 'request' in extra_context:
        request = extra_context['request']
    else:
        request = None

    # get prerendered format messages
    messages = get_formatted_messages(formats, label, extra_context)

    if 'admin' in label:
        subject = messages['short']
        body = messages['full']

    else:
        extra_context.update({'message': mark_safe(messages['short'])})
        subject = render_to_string(
            template_name='notification/email_subject.txt',
            context=extra_context, request=request)

        extra_context.update({'message': mark_safe(messages['full'])})
        body = render_to_string(
            template_name='notification/email_body.txt',
            context=extra_context, request=request)

    if 'reply_to' in extra_context:
        reply_to = extra_context['reply_to']
        if reply_to:
            headers['Reply-To'] = reply_to
    else:
        reply_to = ''

    sender = extra_context.get('sender', '')
    if not sender:
        sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if not sender:
            sender = settings.DEFAULT_FROM_EMAIL

    sender_display = extra_context.get('sender_display', '')
    # Add quotes around display name to prevent errors on sending
    # when display name contains comma or other control characters, - jennyq
    from_display = '"%s" <%s>' % (sender_display, sender)

    if sender_display:
        headers['From'] = from_display

    recipient_bcc = extra_context.get('recipient_bcc') or []
    content_type = 'html'

    # removing newlines
    subject = ''.join(subject.splitlines())
    body = add_tendenci_footer(body)

    for email_addr in emails:
        if validate_email(email_addr):
            recipients = [email_addr]

            if recipient_bcc:
                email = EmailMessage(subject, body, sender,
                                     recipients, recipient_bcc, headers=headers)
            else:
                email = EmailMessage(subject, body, sender,
                                     recipients, headers=headers)
            email.content_subtype = content_type
    
            try:
                email.send(fail_silently=True)  # should we raise exception or not?
            except UnicodeError:
                pass

    to = ','.join(emails)
    bcc = ','.join(recipient_bcc)
    reply_to = reply_to or str()

    NoticeEmail.objects.create(
        emails=to,
        sender=sender,
        bcc=bcc,
        title=subject,
        content=body,
        reply_to=reply_to,
        from_display=from_display,
        notice_type=notice_type
    )
Exemplo n.º 6
0
    def send(self, fail_silently=False, **kwargs):
        recipient_list = []
        recipient_bcc_list = []
        headers = kwargs.get('headers', {})
        attachments = kwargs.get('attachments', [])

        if isinstance(self.recipient, basestring):
            recipient_list = self.recipient.split(',')
            recipient_list = [recipient.strip() for recipient in recipient_list
                              if recipient.strip() != '']
        else:
            recipient_list = list(self.recipient)
        if isinstance(self.recipient_cc, basestring):
            recipient_cc_list = self.recipient_cc.split(',')
            recipient_cc_list = [recipient_cc.strip() for recipient_cc in recipient_cc_list if
                                  recipient_cc.strip() != '']
            recipient_list += recipient_cc_list
        else:
            recipient_list += list(self.recipient_cc)
        if isinstance(self.recipient_bcc, basestring):
            recipient_bcc_list = self.recipient_bcc.split(',')
            recipient_bcc_list = [recipient_bcc.strip() for recipient_bcc in recipient_bcc_list if
                                   recipient_bcc.strip() != '']
        else:
            recipient_bcc_list = list(self.recipient_bcc)

        if self.reply_to:
            headers['Reply-To'] = self.reply_to
        if not self.sender:
            self.sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if self.sender_display:
            # Add quotes around display name to prevent errors on sending
            # When display name contains comma or other control characters,
            headers['From'] = '"%s" <%s>' % (self.sender_display, self.sender)
        if self.priority and self.priority == 1:
            headers['X-Priority'] = '1'
            headers['X-MSMail-Priority'] = 'High'

        # remove blocked from recipient_list and recipient_bcc_list
        temp_recipient_list = copy.copy(recipient_list)
        for e in temp_recipient_list:
            if self.is_blocked(e) or not is_valid_domain(e):
                recipient_list.remove(e)
        temp_recipient_bcc_list = copy.copy(recipient_bcc_list)
        for e in temp_recipient_bcc_list:
            if self.is_blocked(e) or not is_valid_domain(e):
                recipient_bcc_list.remove(e)

        if recipient_list or recipient_bcc_list:
            msg = EmailMessage(self.subject,
                               add_tendenci_footer(self.body),
                               self.sender,
                               recipient_list,
                               recipient_bcc_list,
                               headers=headers,
                               connection=kwargs.get('connection', None))
            if self.content_type == 'html' or self.content_type == self.CONTENT_TYPE_HTML:
                msg.content_subtype = 'html'
            if attachments:
                msg.attachments = attachments
            msg.send(fail_silently=fail_silently)
Exemplo n.º 7
0
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs):
    """
    Creates a new notice.

    This is intended to be how other apps create new notices.

    notification.send(user, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )

    You can pass in on_site=False to prevent the notice emitted from being
    displayed on the site.
    """

    send = kwargs.get('send', False)

    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned):
        notice_type = None

    if notice_type:

        protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
        current_site = Site.objects.get_current()

        notices_url = u"%s://%s%s" % (
            protocol,
            unicode(current_site),
            reverse("notification_notices"),
        )

        current_language = get_language()

        formats = (
            'full.html',
            'short.txt',
            'notice.html',
        )  # TODO make formats configurable

        for user in users:
            if not user.email or Email.is_blocked(user.email):
                continue

            recipients = []
            headers = {}
            # get user language for user from language store defined in
            # NOTIFICATION_LANGUAGE_MODULE setting
            try:
                language = get_notification_language(user)
            except LanguageStoreNotAvailable:
                language = None

            if language is not None:
                # activate the user's language
                activate(language)

            # test for request in the extra_context
            if 'request' in extra_context.keys():
                context = RequestContext(extra_context['request'])
                extra_context.update({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)
            else:
                # update context with user specific translations
                context = Context({
                    "user": user,
                    "notice": ugettext(notice_type.display),
                    "notices_url": notices_url,
                    "current_site": current_site,
                })
                context.update(extra_context)

            # get prerendered format messages
            messages = get_formatted_messages(formats, label, context)

            # Strip newlines from subject
            subject = ''.join(render_to_string('notification/email_subject.txt', {
                'message': messages['short'][0],
            }, context).splitlines())

            body = render_to_string('notification/email_body.txt', {
                'message': messages['full'][0],
            }, context)

            Notice.objects.create(user=user,
                                  message=messages['notice'][0],
                                  notice_type=notice_type,
                                  on_site=on_site)
            if should_send(user, notice_type, "1", send=send) and user.email:  # Email
                recipients.append(user.email)

            if messages['full'][1] == '.html':
                # headers = {'Content-Type': 'text/html'}
                content_type = 'html'
            else:
                # headers = {'Content-Type': 'text/plain'}
                content_type = 'text'

            email = EmailMessage(subject, add_tendenci_footer(body), settings.DEFAULT_FROM_EMAIL, recipients, headers=headers)
            email.content_subtype = content_type
            email.send()

        # reset environment to original language
        activate(current_language)
Exemplo n.º 8
0
def send_emails(emails, label, extra_context=None, on_site=True):
    """
    This method accepts a list of email addresses
    as opposed to a list of users. This is a custom method
    as opposed to send(), send_now(), and queue()

    Just send the notice to a list of emails immediately.
    No new notice created here
    notification.send_emails(email_list, 'friends_invite_sent', {
        'spam': 'eggs',
        'foo': 'bar',
    )
    """
    if extra_context is None:
        extra_context = {}

    try:
        notice_type = NoticeType.objects.get(label=label)
    except NoticeType.DoesNotExist as err:
        logger.warning('Skipping notification send for "{label}": {err}'.format(
            label=label, err=err))
        # Stop here because we need a notice_type
        return None

    headers = {}
    protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http")
    current_site = Site.objects.get_current()

    notices_url = u"%s://%s%s" % (
        protocol,
        unicode(current_site),
        reverse("notification_notices"),
    )

    formats = (
        'full.html',
        'short.txt',
        'notice.html',
    )  # TODO make formats configurable

    # test for request in the extra_context
    if 'request' in extra_context.keys():
        context = RequestContext(extra_context['request'])
        extra_context.update({
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)
    else:
        # update context with user specific translations
        context = Context({
            "notice": ugettext(notice_type.display),
            "notices_url": notices_url,
            "current_site": current_site,
        })
        context.update(extra_context)

    # get prerendered format messages
    messages = get_formatted_messages(formats, label, context)

    if 'admin' in label:
        subject = messages['short']
        body = messages['full']

    else:
        subject = render_to_string(
            'notification/email_subject.txt',
            {'message': mark_safe(messages['short'])},
            context)

        body = render_to_string(
            'notification/email_body.txt',
            {'message': mark_safe(messages['full'])},
            context)

    if 'reply_to' in extra_context.keys():
        reply_to = extra_context['reply_to']
        headers['Reply-To'] = reply_to
    else:
        reply_to = ''

    sender = extra_context.get('sender', '')
    if not sender:
        sender = get_setting('site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL
        if not sender:
            sender = settings.DEFAULT_FROM_EMAIL

    sender_display = extra_context.get('sender_display', '')
    # Add quotes around display name to prevent errors on sending
    # when display name contains comma or other control characters, - jennyq
    from_display = '"%s" <%s>' % (sender_display, sender)

    if sender_display:
        headers['From'] = from_display

    recipient_bcc = extra_context.get('recipient_bcc') or []
    content_type = 'html'

    # removing newlines
    subject = ''.join(subject.splitlines())
    body = add_tendenci_footer(body)

    for email_addr in emails:
        if is_valid_domain(email_addr):
            recipients = [email_addr]

            if recipient_bcc:
                email = EmailMessage(subject, body, sender,
                                     recipients, recipient_bcc, headers=headers)
            else:
                email = EmailMessage(subject, body, sender,
                                     recipients, headers=headers)
            email.content_subtype = content_type
    
            try:
                email.send(fail_silently=True)  # should we raise exception or not?
            except UnicodeError:
                pass

    to = ','.join(emails)
    bcc = ','.join(recipient_bcc)
    reply_to = reply_to or unicode()

    NoticeEmail.objects.create(
        emails=to,
        sender=sender,
        bcc=bcc,
        title=subject,
        content=body,
        reply_to=reply_to,
        from_display=from_display,
        notice_type=notice_type
    )