示例#1
0
    def test_correct_url_update_notification(self):
        # Make sure the user is subscribed
        perm_setting = email.NOTIFICATIONS[0]
        un = UserNotification.objects.create(notification_id=perm_setting.id,
                                             user=self.user_profile,
                                             enabled=True)

        # Create a URL
        token, hash = UnsubscribeCode.create(self.user.email)
        url = reverse('users.unsubscribe', args=[token, hash,
                                                 perm_setting.short])

        # Load the URL
        r = self.client.get(url)
        doc = pq(r.content)

        # Check that it was successful
        assert doc('#unsubscribe-success').length
        assert doc('#standalone').length
        eq_(doc('#standalone ul li').length, 1)

        # Make sure the user is unsubscribed
        un = UserNotification.objects.filter(notification_id=perm_setting.id,
                                             user=self.user)
        eq_(un.count(), 1)
        eq_(un.all()[0].enabled, False)
示例#2
0
    def test_correct_url_update_notification(self):
        # Make sure the user is subscribed
        perm_setting = email.NOTIFICATIONS[0]
        un = UserNotification.objects.create(notification_id=perm_setting.id,
                                             user=self.user_profile,
                                             enabled=True)

        # Create a URL
        token, hash = UnsubscribeCode.create(self.user.email)
        url = reverse('users.unsubscribe', args=[token, hash,
                                                 perm_setting.short])

        # Load the URL
        r = self.client.get(url)
        doc = pq(r.content)

        # Check that it was successful
        assert doc('#unsubscribe-success').length
        assert doc('#standalone').length
        eq_(doc('#standalone ul li').length, 1)

        # Make sure the user is unsubscribed
        un = UserNotification.objects.filter(notification_id=perm_setting.id,
                                             user=self.user)
        eq_(un.count(), 1)
        eq_(un.all()[0].enabled, False)
示例#3
0
    def test_wrong_url(self):
        perm_setting = email.NOTIFICATIONS[0]
        token, hash = UnsubscribeCode.create(self.user.email)
        hash = hash[::-1]  # Reverse the hash, so it's wrong

        url = reverse("users.unsubscribe", args=[token, hash, perm_setting.short])
        r = self.client.get(url)
        doc = pq(r.content)

        eq_(doc("#unsubscribe-fail").length, 1)
示例#4
0
    def test_wrong_url(self):
        perm_setting = email.NOTIFICATIONS[0]
        token, hash = UnsubscribeCode.create(self.user.email)
        hash = hash[::-1]  # Reverse the hash, so it's wrong

        url = reverse('users.unsubscribe', args=[token, hash,
                                                 perm_setting.short])
        r = self.client.get(url)
        doc = pq(r.content)

        eq_(doc('#unsubscribe-fail').length, 1)
示例#5
0
文件: utils.py 项目: Nolski/olympia
        if async:
            return send_email.delay(*args, **kwargs)
        else:
            return send_email(*args, **kwargs)

    if white_list:
        if perm_setting:
            html_template = loader.get_template('amo/emails/unsubscribe.html')
            text_template = loader.get_template('amo/emails/unsubscribe.ltxt')
            if not manage_url:
                manage_url = urlparams(absolutify(
                    reverse('users.edit', add_prefix=False)),
                    'acct-notify')
            for recipient in white_list:
                # Add unsubscribe link to footer.
                token, hash = UnsubscribeCode.create(recipient)
                unsubscribe_url = absolutify(
                    reverse('users.unsubscribe',
                            args=[token, hash, perm_setting.short],
                            add_prefix=False))

                context_options = {
                    'message': message,
                    'manage_url': manage_url,
                    'unsubscribe_url': unsubscribe_url,
                    'perm_setting': perm_setting.label,
                    'SITE_URL': settings.SITE_URL,
                    'mandatory': perm_setting.mandatory,
                }
                # Render this template in the default locale until
                # bug 635840 is fixed.
示例#6
0
def send_mail(subject, message, from_email=None, recipient_list=None,
              fail_silently=False, use_blacklist=True, perm_setting=None,
              manage_url=None, headers=None, cc=None, real_email=False,
              html_message=None):
    """
    A wrapper around django.core.mail.EmailMessage.

    Adds blacklist checking and error logging.
    """
    from amo.helpers import absolutify
    import users.notifications as notifications
    if not recipient_list:
        return True

    if isinstance(recipient_list, basestring):
        raise ValueError('recipient_list should be a list, not a string.')

    connection = get_email_backend(real_email)

    # Check against user notification settings
    if perm_setting:
        if isinstance(perm_setting, str):
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
        perms = dict(UserNotification.objects
                                     .filter(user__email__in=recipient_list,
                                             notification_id=perm_setting.id)
                                     .values_list('user__email', 'enabled'))

        d = perm_setting.default_checked
        recipient_list = [e for e in recipient_list
                          if e and perms.setdefault(e, d)]

    # Prune blacklisted emails.
    if use_blacklist:
        white_list = []
        for email in recipient_list:
            if email and email.lower() in settings.EMAIL_BLACKLIST:
                log.debug('Blacklisted email removed from list: %s' % email)
            else:
                white_list.append(email)
    else:
        white_list = recipient_list

    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL
    cc = cc and [cc] or None
    if not headers:
        headers = {}

    def send(recipient, message, html_message=None):
        backend = EmailMultiAlternatives if html_message else EmailMessage

        result = backend(subject, message,
            from_email, recipient, cc=cc, connection=connection,
            headers=headers)

        if html_message:
            result.attach_alternative(html_message, 'text/html')

        try:
            result.send(fail_silently=False)
            return result
        except Exception as e:
            log.error('send_mail failed with error: %s' % e)
            if not fail_silently:
                raise
            return False

    if white_list:
        if perm_setting:
            html_template = loader.get_template('amo/emails/unsubscribe.html')
            text_template = loader.get_template('amo/emails/unsubscribe.ltxt')
            if not manage_url:
                manage_url = urlparams(absolutify(
                    reverse('users.edit', add_prefix=False)),
                    'acct-notify')
            for recipient in white_list:
                # Add unsubscribe link to footer.
                token, hash = UnsubscribeCode.create(recipient)
                unsubscribe_url = absolutify(reverse('users.unsubscribe',
                    args=[token, hash, perm_setting.short],
                    add_prefix=False))

                context = {
                    'message': message,
                    'manage_url': manage_url,
                    'unsubscribe_url': unsubscribe_url,
                    'perm_setting': perm_setting.label,
                    'SITE_URL': settings.SITE_URL,
                    'mandatory': perm_setting.mandatory
                }
                # Render this template in the default locale until
                # bug 635840 is fixed.
                with no_translation():
                    message_with_unsubscribe = text_template.render(
                        Context(context, autoescape=False))

                if html_message:
                    context['message'] = html_message
                    with no_translation():
                        html_message_with_unsubscribe = html_template.render(
                            Context(context, autoescape=False))
                        result = send([recipient], message_with_unsubscribe,
                            html_message_with_unsubscribe)
                else:
                    result = send([recipient], message_with_unsubscribe)
        else:
            result = send(recipient_list, message=message,
                          html_message=html_message)
    else:
        result = True

    return result
示例#7
0
文件: utils.py 项目: pennyfx/zamboni
def send_mail(subject,
              message,
              from_email=None,
              recipient_list=None,
              fail_silently=False,
              use_blacklist=True,
              perm_setting=None,
              headers=None,
              connection=None):
    """
    A wrapper around django.core.mail.EmailMessage.

    Adds blacklist checking and error logging.
    """
    import users.notifications as notifications
    if not recipient_list:
        return True

    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL

    # Check against user notification settings
    if perm_setting:
        if isinstance(perm_setting, str):
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
        perms = dict(
            UserNotification.objects.filter(
                user__email__in=recipient_list,
                notification_id=perm_setting.id).values_list(
                    'user__email', 'enabled'))

        d = perm_setting.default_checked
        recipient_list = [
            e for e in recipient_list if e and perms.setdefault(e, d)
        ]

    # Prune blacklisted emails.
    if use_blacklist:
        white_list = []
        for email in recipient_list:
            if email and email.lower() in settings.EMAIL_BLACKLIST:
                log.debug('Blacklisted email removed from list: %s' % email)
            else:
                white_list.append(email)
    else:
        white_list = recipient_list

    try:
        if white_list:
            if perm_setting:
                template = loader.get_template('amo/emails/unsubscribe.ltxt')
                for recipient in white_list:
                    # Add unsubscribe link to footer
                    token, hash = UnsubscribeCode.create(recipient)
                    from amo.helpers import absolutify
                    unsubscribe_url = absolutify(
                        reverse('users.unsubscribe',
                                args=[token, hash, perm_setting.short]))
                    manage_url = urlparams(absolutify(reverse('users.edit')),
                                           'acct-notify')

                    context = {
                        'message': message,
                        'manage_url': manage_url,
                        'unsubscribe_url': unsubscribe_url,
                        'perm_setting': perm_setting.label,
                        'SITE_URL': settings.SITE_URL,
                        'mandatory': perm_setting.mandatory
                    }
                    # Render this template in the default locale until
                    # bug 635840 is fixed.
                    with no_translation():
                        send_message = template.render(
                            Context(context, autoescape=False))

                        result = EmailMessage(
                            subject,
                            send_message,
                            from_email,
                            [recipient],
                            connection=connection,
                            headers=headers or {},
                        ).send(fail_silently=False)
            else:
                result = EmailMessage(
                    subject,
                    message,
                    from_email,
                    white_list,
                    connection=connection,
                    headers=headers or {},
                ).send(fail_silently=False)
        else:
            result = True
    except Exception as e:
        result = False
        log.error('send_mail failed with error: %s' % e)
        if not fail_silently:
            raise

    return result
示例#8
0
文件: utils.py 项目: chenba/zamboni
def send_mail(subject, message, from_email=None, recipient_list=None,
              fail_silently=False, use_blacklist=True, perm_setting=None,
              connection=None):
    """
    A wrapper around django.core.mail.send_mail.

    Adds blacklist checking and error logging.
    """
    if not recipient_list:
        return True

    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL

    # Check against user notification settings
    if perm_setting:
        if isinstance(perm_setting, str):
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
        perms = dict(UserNotification.objects
                                     .filter(user__email__in=recipient_list,
                                             notification_id=perm_setting.id)
                                     .values_list('user__email', 'enabled'))

        d = perm_setting.default_checked
        recipient_list = [e for e in recipient_list
                          if e and perms.setdefault(e, d)]

    # Prune blacklisted emails.
    if use_blacklist:
        white_list = []
        for email in recipient_list:
            if email and email.lower() in settings.EMAIL_BLACKLIST:
                log.debug('Blacklisted email removed from list: %s' % email)
            else:
                white_list.append(email)
    else:
        white_list = recipient_list

    try:
        if white_list:
            if perm_setting:
                template = loader.get_template('amo/emails/unsubscribe.ltxt')
                for recipient in white_list:
                    # Add unsubscribe link to footer
                    token, hash = UnsubscribeCode.create(recipient)
                    from amo.helpers import absolutify
                    url = absolutify(reverse('users.unsubscribe',
                            args=[token, hash, perm_setting.short]))
                    context = {'message': message, 'unsubscribe': url,
                               'perm_setting': perm_setting.label,
                               'SITE_URL': settings.SITE_URL}
                    send_message = template.render(Context(context,
                                                           autoescape=False))

                    result = django_send_mail(subject, send_message, from_email,
                                              [recipient], fail_silently=False,
                                              connection=connection)
            else:
                result = django_send_mail(subject, message, from_email,
                                          white_list, fail_silently=False,
                                          connection=connection)
        else:
            result = True
    except Exception as e:
        result = False
        log.error('send_mail failed with error: %s' % e)
        if not fail_silently:
            raise

    return result
示例#9
0
        if async:
            return send_email.delay(*args, **kwargs)
        else:
            return send_email(*args, **kwargs)

    if white_list:
        if perm_setting:
            html_template = loader.get_template('amo/emails/unsubscribe.html')
            text_template = loader.get_template('amo/emails/unsubscribe.ltxt')
            if not manage_url:
                manage_url = urlparams(
                    absolutify(reverse('users.edit', add_prefix=False)),
                    'acct-notify')
            for recipient in white_list:
                # Add unsubscribe link to footer.
                token, hash = UnsubscribeCode.create(recipient)
                unsubscribe_url = absolutify(
                    reverse('users.unsubscribe',
                            args=[token, hash, perm_setting.short],
                            add_prefix=False))

                context_options = {
                    'message': message,
                    'manage_url': manage_url,
                    'unsubscribe_url': unsubscribe_url,
                    'perm_setting': perm_setting.label,
                    'SITE_URL': settings.SITE_URL,
                    'mandatory': perm_setting.mandatory,
                    # Hide "Unsubscribe" links in Marketplace emails
                    # (bug 802379).
                    'show_unsubscribe': not settings.MARKETPLACE
示例#10
0
def send_mail(subject, message, from_email=None, recipient_list=None,
              fail_silently=False, use_blacklist=True, perm_setting=None,
              manage_url=None, headers=None, cc=None, real_email=False,
              html_message=None, attachments=None):
    """
    A wrapper around django.core.mail.EmailMessage.

    Adds blacklist checking and error logging.
    """
    from amo.helpers import absolutify
    import users.notifications as notifications
    if not recipient_list:
        return True

    if isinstance(recipient_list, basestring):
        raise ValueError('recipient_list should be a list, not a string.')

    connection = get_email_backend(real_email)

    # Check against user notification settings
    if perm_setting:
        if isinstance(perm_setting, str):
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
        perms = dict(UserNotification.objects
                                     .filter(user__email__in=recipient_list,
                                             notification_id=perm_setting.id)
                                     .values_list('user__email', 'enabled'))

        d = perm_setting.default_checked
        recipient_list = [e for e in recipient_list
                          if e and perms.setdefault(e, d)]

    # Prune blacklisted emails.
    if use_blacklist:
        white_list = []
        for email in recipient_list:
            if email and email.lower() in settings.EMAIL_BLACKLIST:
                log.debug('Blacklisted email removed from list: %s' % email)
            else:
                white_list.append(email)
    else:
        white_list = recipient_list

    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL
    cc = cc and [cc] or None
    if not headers:
        headers = {}

    def send(recipient, message, html_message=None, attachments=None):
        backend = EmailMultiAlternatives if html_message else EmailMessage

        result = backend(subject, message,
                         from_email, recipient, cc=cc, connection=connection,
                         headers=headers, attachments=attachments)

        if html_message:
            result.attach_alternative(html_message, 'text/html')

        try:
            result.send(fail_silently=False)
            return result
        except Exception as e:
            log.error('send_mail failed with error: %s' % e)
            if not fail_silently:
                raise
            return False

    if white_list:
        if perm_setting:
            html_template = loader.get_template('amo/emails/unsubscribe.html')
            text_template = loader.get_template('amo/emails/unsubscribe.ltxt')
            if not manage_url:
                manage_url = urlparams(absolutify(
                    reverse('users.edit', add_prefix=False)),
                    'acct-notify')
            for recipient in white_list:
                # Add unsubscribe link to footer.
                token, hash = UnsubscribeCode.create(recipient)
                unsubscribe_url = absolutify(reverse('users.unsubscribe',
                    args=[token, hash, perm_setting.short],
                    add_prefix=False))

                context = {
                    'message': message,
                    'manage_url': manage_url,
                    'unsubscribe_url': unsubscribe_url,
                    'perm_setting': perm_setting.label,
                    'SITE_URL': settings.SITE_URL,
                    'mandatory': perm_setting.mandatory
                }
                # Render this template in the default locale until
                # bug 635840 is fixed.
                with no_translation():
                    message_with_unsubscribe = text_template.render(
                        Context(context, autoescape=False))

                if html_message:
                    context['message'] = html_message
                    with no_translation():
                        html_message_with_unsubscribe = html_template.render(
                            Context(context, autoescape=False))
                        result = send([recipient], message_with_unsubscribe,
                                      html_message_with_unsubscribe,
                                      attachments=attachments)
                else:
                    result = send([recipient], message_with_unsubscribe,
                                  attachments=attachments)
        else:
            result = send(recipient_list, message=message,
                          html_message=html_message, attachments=attachments)
    else:
        result = True

    return result
示例#11
0
文件: utils.py 项目: vaidik/zamboni
def send_mail(
    subject,
    message,
    from_email=None,
    recipient_list=None,
    fail_silently=False,
    use_blacklist=True,
    perm_setting=None,
    headers=None,
    connection=None,
):
    """
    A wrapper around django.core.mail.EmailMessage.

    Adds blacklist checking and error logging.
    """
    import users.notifications as notifications

    if not recipient_list:
        return True

    if not from_email:
        from_email = settings.DEFAULT_FROM_EMAIL

    # Check against user notification settings
    if perm_setting:
        if isinstance(perm_setting, str):
            perm_setting = notifications.NOTIFICATIONS_BY_SHORT[perm_setting]
        perms = dict(
            UserNotification.objects.filter(
                user__email__in=recipient_list, notification_id=perm_setting.id
            ).values_list("user__email", "enabled")
        )

        d = perm_setting.default_checked
        recipient_list = [e for e in recipient_list if e and perms.setdefault(e, d)]

    # Prune blacklisted emails.
    if use_blacklist:
        white_list = []
        for email in recipient_list:
            if email and email.lower() in settings.EMAIL_BLACKLIST:
                log.debug("Blacklisted email removed from list: %s" % email)
            else:
                white_list.append(email)
    else:
        white_list = recipient_list

    try:
        if white_list:
            if perm_setting:
                template = loader.get_template("amo/emails/unsubscribe.ltxt")
                for recipient in white_list:
                    # Add unsubscribe link to footer
                    token, hash = UnsubscribeCode.create(recipient)
                    from amo.helpers import absolutify

                    unsubscribe_url = absolutify(reverse("users.unsubscribe", args=[token, hash, perm_setting.short]))
                    manage_url = urlparams(absolutify(reverse("users.edit")), "acct-notify")

                    context = {
                        "message": message,
                        "manage_url": manage_url,
                        "unsubscribe_url": unsubscribe_url,
                        "perm_setting": perm_setting.label,
                        "SITE_URL": settings.SITE_URL,
                        "mandatory": perm_setting.mandatory,
                    }
                    # Render this template in the default locale until
                    # bug 635840 is fixed.
                    with no_translation():
                        send_message = template.render(Context(context, autoescape=False))

                        result = EmailMessage(
                            subject, send_message, from_email, [recipient], connection=connection, headers=headers or {}
                        ).send(fail_silently=False)
            else:
                result = EmailMessage(
                    subject, message, from_email, white_list, connection=connection, headers=headers or {}
                ).send(fail_silently=False)
        else:
            result = True
    except Exception as e:
        result = False
        log.error("send_mail failed with error: %s" % e)
        if not fail_silently:
            raise

    return result