Exemple #1
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)
Exemple #2
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)
Exemple #3
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": ugettext(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 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 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
    )
Exemple #4
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
    )