def test_reply_to(self):
        send_mail('subject', 'test body', from_email='*****@*****.**',
                  recipient_list=['*****@*****.**'], reply_to=['*****@*****.**'])

        headers = mail.outbox[0].extra_headers
        assert mail.outbox[0].reply_to == ['*****@*****.**']
        assert headers['Auto-Submitted'] == 'auto-generated'  # Still there.
 def test_async_will_stop_retrying(self, backend):
     backend.side_effect = self.make_backend_class([True, True])
     with self.assertRaises(RuntimeError):
         send_mail('test subject',
                   'test body',
                   max_retries=1,
                   recipient_list=['*****@*****.**'])
 def test_async_will_retry(self, backend):
     backend.side_effect = self.make_backend_class([True, True, False])
     with self.assertRaises(Retry):
         send_mail('test subject',
                   'test body',
                   max_retries=2,
                   recipient_list=['*****@*****.**'])
    def test_autoresponse_headers(self):
        send_mail('subject', 'test body', from_email='*****@*****.**',
                  recipient_list=['*****@*****.**'])

        headers = mail.outbox[0].extra_headers
        assert headers['X-Auto-Response-Suppress'] == 'RN, NRN, OOF, AutoReply'
        assert headers['Auto-Submitted'] == 'auto-generated'
 def test_dont_localize(self):
     user = UserProfile.objects.all()[0]
     to = user.email
     translation.activate('zh_TW')
     send_mail('test subject', 'test body', perm_setting='reply',
               recipient_list=[to])
     assert u'an add-on developer replies to' in mail.outbox[0].body
Example #6
0
def send_activity_mail(subject, message, version, recipients, from_email,
                       unique_id, perm_setting=None):
    thread_id = '{addon}/{version}'.format(
        addon=version.addon.id, version=version.id)
    reference_header = '<{thread}@{site}>'.format(
        thread=thread_id, site=settings.INBOUND_EMAIL_DOMAIN)
    message_id = '<{thread}/{message}@{site}>'.format(
        thread=thread_id, message=unique_id,
        site=settings.INBOUND_EMAIL_DOMAIN)
    headers = {
        'In-Reply-To': reference_header,
        'References': reference_header,
        'Message-ID': message_id,
    }

    for recipient in recipients:
        token, created = ActivityLogToken.objects.get_or_create(
            version=version, user=recipient)
        if not created:
            token.update(use_count=0)
        else:
            log.info('Created token with UUID %s for user: %s.' % (
                token.uuid, recipient.id))
        reply_to = "%s%s@%s" % (
            REPLY_TO_PREFIX, token.uuid.hex, settings.INBOUND_EMAIL_DOMAIN)
        log.info('Sending activity email to %s for %s version %s' % (
            recipient, version.addon.pk, version.pk))
        send_mail(
            subject, message, recipient_list=[recipient.email],
            from_email=from_email, use_deny_list=False, headers=headers,
            perm_setting=perm_setting, reply_to=[reply_to])
 def test_send_attachment(self):
     path = os.path.join(ATTACHMENTS_DIR, 'bacon.txt')
     attachments = [[os.path.basename(path), storage.open(path).read(),
                     mimetypes.guess_type(path)[0]]]
     send_mail('test subject', 'test body', from_email='*****@*****.**',
               recipient_list=['*****@*****.**'], attachments=attachments)
     assert attachments == mail.outbox[0].attachments, (
         'Attachments not included')
Example #8
0
    def mail_report(self, recipient, subject, content):
        log.info("Sending report '%s' to %s." % (subject, recipient))

        send_mail(subject,
                  content,
                  from_email='*****@*****.**',
                  recipient_list=[recipient],
                  html_message=content,
                  reply_to=[recipient])
Example #9
0
def test_send_email_autoescape():
    s = 'woo&&<>\'""'

    # Make sure HTML is not auto-escaped.
    send_mail(u'Random subject with %s', s,
              recipient_list=['*****@*****.**'],
              from_email='*****@*****.**',
              use_deny_list=False)
    assert len(mail.outbox) == 1
    assert mail.outbox[0].body == s
Example #10
0
    def test_blacklist_flag(self):
        to = "*****@*****.**"
        settings.EMAIL_BLACKLIST = (to,)
        success = send_mail("test subject", "test body", recipient_list=[to], fail_silently=False, use_blacklist=True)
        assert success
        assert len(mail.outbox) == 0

        success = send_mail("test subject", "test body", recipient_list=[to], fail_silently=False, use_blacklist=False)
        assert success
        assert len(mail.outbox) == 1
Example #11
0
    def restrict(self):
        from olympia.amo.utils import send_mail

        log.info(u"User (%s: <%s>) is being restricted and " "its user-generated content removed." % (self, self.email))
        g = Group.objects.get(rules="Restricted:UGC")
        GroupUser.objects.create(user=self, group=g)
        self.reviews.all().delete()
        self.collections.all().delete()

        t = loader.get_template("users/email/restricted.ltxt")
        send_mail(_("Your account has been restricted"), t.render(Context({})), None, [self.email], use_blacklist=False)
Example #12
0
 def test_send_attachment(self):
     path = os.path.join(ATTACHMENTS_DIR, "bacon.txt")
     attachments = [(os.path.basename(path), storage.open(path).read(), mimetypes.guess_type(path)[0])]
     send_mail(
         "test subject",
         "test body",
         from_email="*****@*****.**",
         recipient_list=["*****@*****.**"],
         attachments=attachments,
     )
     assert attachments == mail.outbox[0].attachments, "Attachments not included"
Example #13
0
def edit(request):
    # Don't use request.user since it has too much caching.
    amouser = UserProfile.objects.get(pk=request.user.id)
    if request.method == 'POST':
        # ModelForm alters the instance you pass in.  We need to keep a copy
        # around in case we need to use it below (to email the user)
        original_email = amouser.email
        form = forms.UserEditForm(request.POST, request.FILES, request=request,
                                  instance=amouser)
        if form.is_valid():
            messages.success(request, _('Profile Updated'))
            if amouser.email != original_email:

                l = {'user': amouser,
                     'mail1': original_email,
                     'mail2': amouser.email}
                log.info(u"User (%(user)s) has requested email change from "
                         u"(%(mail1)s) to (%(mail2)s)" % l)
                messages.info(
                    request, _('Email Confirmation Sent'),
                    _(u'An email has been sent to {0} to confirm your new '
                      u'email address. For the change to take effect, you '
                      u'need to click on the link provided in this email. '
                      u'Until then, you can keep logging in with your '
                      u'current email address.').format(amouser.email))

                token, hash_ = EmailResetCode.create(amouser.id, amouser.email)
                url = '%s%s' % (settings.SITE_URL,
                                reverse('users.emailchange',
                                        args=[amouser.id, token, hash_]))
                t = loader.get_template('users/email/emailchange.ltxt')
                c = {'domain': settings.DOMAIN, 'url': url}
                send_mail(
                    _('Please confirm your email address '
                      'change at %s' % settings.DOMAIN),
                    t.render(Context(c)), None, [amouser.email],
                    use_blacklist=False, real_email=True)

                # Reset the original email back.  We aren't changing their
                # address until they confirm the new one
                amouser.email = original_email
            form.save()
            return redirect('users.edit')
        else:

            messages.error(
                request,
                _('Errors Found'),
                _('There were errors in the changes you made. Please correct '
                  'them and resubmit.'))
    else:
        form = forms.UserEditForm(instance=amouser, request=request)
    return render(request, 'users/edit.html',
                  {'form': form, 'amouser': amouser})
Example #14
0
    def send(self):
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous coward'

        target_url = ('%s%s' % (settings.SITE_URL, self.target.get_url_path())
                      if self.target else 'GUID not in database')
        name = self.target.name if self.target else self.guid
        msg = u'%s reported abuse for %s (%s).\n\n%s' % (
            user_name, name, target_url, self.message)
        send_mail(unicode(self), msg, recipient_list=(settings.ABUSE_EMAIL,))
    def test_deny_flag(self):
        to = '*****@*****.**'
        settings.EMAIL_DENY_LIST = (to,)
        success = send_mail('test subject', 'test body',
                            recipient_list=[to], use_deny_list=True)
        assert success
        assert len(mail.outbox) == 0

        success = send_mail('test subject', 'test body',
                            recipient_list=[to], use_deny_list=False)
        assert success
        assert len(mail.outbox) == 1
Example #16
0
    def test_dont_localize(self, fake_Context):
        perm_setting = []

        def ctx(d, autoescape):
            perm_setting.append(unicode(d["perm_setting"]))
            return TemplateContext(d, autoescape=autoescape)

        fake_Context.side_effect = ctx
        user = UserProfile.objects.all()[0]
        to = user.email
        translation.activate("zh_TW")
        send_mail("test subject", "test body", perm_setting="reply", recipient_list=[to], fail_silently=False)
        assert perm_setting[0] == u"an add-on developer replies to my review"
Example #17
0
    def email_confirmation_code(self):
        from olympia.amo.utils import send_mail
        log.debug("Sending account confirmation code for user (%s)", self)

        url = "%s%s" % (settings.SITE_URL,
                        reverse('users.confirm',
                                args=[self.id, self.confirmationcode]))
        domain = settings.DOMAIN
        t = loader.get_template('users/email/confirm.ltxt')
        c = {'domain': domain, 'url': url, }
        send_mail(_("Please confirm your email address"),
                  t.render(Context(c)), None, [self.email],
                  use_blacklist=False, real_email=True)
Example #18
0
    def test_dont_localize(self, fake_Context):
        perm_setting = []

        def ctx(d, autoescape):
            perm_setting.append(unicode(d['perm_setting']))
            return TemplateContext(d, autoescape=autoescape)
        fake_Context.side_effect = ctx
        user = UserProfile.objects.all()[0]
        to = user.email
        translation.activate('zh_TW')
        send_mail('test subject', 'test body', perm_setting='reply',
                  recipient_list=[to], fail_silently=False)
        eq_(perm_setting[0], u'an add-on developer replies to my review')
Example #19
0
    def restrict(self):
        from olympia.amo.utils import send_mail
        log.info(u'User (%s: <%s>) is being restricted and '
                 'its user-generated content removed.' % (self, self.email))
        g = Group.objects.get(rules='Restricted:UGC')
        GroupUser.objects.create(user=self, group=g)
        self.reviews.all().delete()
        self.collections.all().delete()

        t = loader.get_template('users/email/restricted.ltxt')
        send_mail(_('Your account has been restricted'),
                  t.render(Context({})),
                  None, [self.email],
                  use_blacklist=False)
Example #20
0
    def send(self):
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous user'

        target_url = ('%s%s' % (settings.SITE_URL, self.target.get_url_path())
                      if self.target else 'GUID not in database')
        name = self.target.name if self.target else self.guid
        msg = u'%s reported abuse for %s (%s).\n\n%s' % (
            user_name, name, target_url, self.message)
        send_mail(six.text_type(self),
                  msg,
                  recipient_list=(settings.ABUSE_EMAIL, ))
Example #21
0
def send_api_key_revocation_email(emails):
    log.info(u'[1@None] Sending API key revocation email to %s.' % emails)
    subject = ugettext(
        u'Mozilla Security Notice: Your AMO API credentials have been revoked')
    template = loader.get_template(
        'devhub/email/submission_api_key_revocation.txt')
    context = {
        'api_keys_url': reverse('devhub.api_key')
    }
    send_mail(subject, template.render(context),
              from_email=settings.ADDONS_EMAIL,
              recipient_list=emails,
              use_deny_list=False,
              perm_setting='individual_contact')
Example #22
0
def send_api_key_revocation_email(emails):
    log.info(u'[1@None] Sending API key revocation email to %s.' % emails)
    subject = ugettext(
        u'Mozilla Security Notice: Your AMO API credentials have been revoked')
    template = loader.get_template(
        'devhub/email/submission_api_key_revocation.txt')
    context = {
        'api_keys_url': reverse('devhub.api_key')
    }
    send_mail(subject, template.render(context),
              from_email=settings.ADDONS_EMAIL,
              recipient_list=emails,
              use_deny_list=False,
              perm_setting='individual_contact')
    def test_blacklist_flag(self):
        to = '*****@*****.**'
        settings.EMAIL_BLACKLIST = (to,)
        success = send_mail('test subject', 'test body',
                            recipient_list=[to], fail_silently=False,
                            use_blacklist=True)
        assert success
        assert len(mail.outbox) == 0

        success = send_mail('test subject', 'test body',
                            recipient_list=[to], fail_silently=False,
                            use_blacklist=False)
        assert success
        assert len(mail.outbox) == 1
Example #24
0
 def test_send_attachment(self):
     path = os.path.join(ATTACHMENTS_DIR, 'bacon.txt')
     attachments = [[
         os.path.basename(path),
         storage.open(path).read(),
         mimetypes.guess_type(path)[0]
     ]]
     send_mail('test subject',
               'test body',
               from_email='*****@*****.**',
               recipient_list=['*****@*****.**'],
               attachments=attachments)
     assert attachments == mail.outbox[0].attachments, (
         'Attachments not included')
Example #25
0
    def test_blacklist_flag(self):
        to = '*****@*****.**'
        settings.EMAIL_BLACKLIST = (to,)
        success = send_mail('test subject', 'test body',
                            recipient_list=[to], fail_silently=False,
                            use_blacklist=True)
        assert success
        eq_(len(mail.outbox), 0)

        success = send_mail('test subject', 'test body',
                            recipient_list=[to], fail_silently=False,
                            use_blacklist=False)
        assert success
        eq_(len(mail.outbox), 1)
Example #26
0
 def test_success_fake_mail(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 0)
     eq_(FakeEmail.objects.count(), 1)
     eq_(FakeEmail.objects.get().message.endswith('test body'), True)
Example #27
0
 def test_qa_whitelist(self):
     assert send_mail("test subject", "test body", recipient_list=["*****@*****.**"], fail_silently=False)
     assert len(mail.outbox) == 1
     assert mail.outbox[0].subject.find("test subject") == 0
     assert mail.outbox[0].body.find("test body") == 0
     assert FakeEmail.objects.count() == 1
     assert FakeEmail.objects.get().message.endswith("test body")
Example #28
0
 def test_qa_whitelist_with_mixed_emails(self):
     assert send_mail(
         "test subject", "test body", recipient_list=["*****@*****.**", "*****@*****.**"], fail_silently=False
     )
     assert len(mail.outbox) == 1
     assert mail.outbox[0].to == ["*****@*****.**"]
     assert FakeEmail.objects.count() == 1
Example #29
0
    def send(self):
        obj = self.addon or self.user
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous coward'

        with no_translation():
            type_ = (gettext(amo.ADDON_TYPE[self.addon.type])
                     if self.addon else 'User')

        subject = u'[%s] Abuse Report for %s' % (type_, obj.name)
        msg = u'%s reported abuse for %s (%s%s).\n\n%s' % (
            user_name, obj.name, settings.SITE_URL, obj.get_url_path(),
            self.message)
        send_mail(subject, msg, recipient_list=(settings.ABUSE_EMAIL, ))
 def test_qa_whitelist_with_mixed_emails(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**', '*****@*****.**'],
                      fail_silently=False)
     assert len(mail.outbox) == 1
     assert mail.outbox[0].to == ['*****@*****.**']
     assert FakeEmail.objects.count() == 1
Example #31
0
 def test_qa_allowed_list_with_mixed_emails(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**', '*****@*****.**'],
                      fail_silently=False)
     assert len(mail.outbox) == 1
     assert mail.outbox[0].to == ['*****@*****.**']
     assert FakeEmail.objects.count() == 1
Example #32
0
 def test_qa_whitelist_with_mixed_emails(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**', '*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 1)
     eq_(mail.outbox[0].to, ['*****@*****.**'])
     eq_(FakeEmail.objects.count(), 1)
Example #33
0
 def test_success_real_mail(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 1)
     eq_(mail.outbox[0].subject.find('test subject'), 0)
     eq_(mail.outbox[0].body.find('test body'), 0)
Example #34
0
def bounce_mail(message, reason):
    recipient = (None if not isinstance(message, dict)
                 else message.get('From', message.get('ReplyTo')))
    if not recipient:
        log.error('Tried to bounce incoming activity mail but no From or '
                  'ReplyTo header present.')
        return

    body = (loader.get_template('activity/emails/bounce.txt').
            render({'reason': reason, 'SITE_URL': settings.SITE_URL}))
    send_mail(
        'Re: %s' % message.get('Subject', 'your email to us'),
        body,
        recipient_list=[recipient['EmailAddress']],
        from_email=settings.ADDONS_EMAIL,
        use_deny_list=False)
Example #35
0
 def test_success_fake_mail(self):
     assert send_mail('test subject',
                      'test body',
                      recipient_list=['*****@*****.**'])
     assert len(mail.outbox) == 0
     assert FakeEmail.objects.count() == 1
     assert FakeEmail.objects.get().message.endswith('test body')
Example #36
0
 def test_qa_allowed_list_with_mixed_emails(self):
     assert send_mail('test subject',
                      'test body',
                      recipient_list=['*****@*****.**', '*****@*****.**'])
     assert len(mail.outbox) == 1
     assert mail.outbox[0].to == ['*****@*****.**']
     assert FakeEmail.objects.count() == 1
Example #37
0
    def test_deny(self):
        to = '*****@*****.**'
        settings.EMAIL_DENY_LIST = (to,)
        success = send_mail('test subject', 'test body', recipient_list=[to])

        assert success
        assert len(mail.outbox) == 0
Example #38
0
def bounce_mail(message, reason):
    recipient = (None if not isinstance(message, dict)
                 else message.get('From', message.get('ReplyTo')))
    if not recipient:
        log.error('Tried to bounce incoming activity mail but no From or '
                  'ReplyTo header present.')
        return

    body = (loader.get_template('activity/emails/bounce.txt').
            render({'reason': reason, 'SITE_URL': settings.SITE_URL}))
    send_mail(
        'Re: %s' % message.get('Subject', 'your email to us'),
        body,
        recipient_list=[recipient['EmailAddress']],
        from_email=settings.REVIEWERS_EMAIL,
        use_deny_list=False)
Example #39
0
 def test_success_real_mail(self):
     assert send_mail('test subject',
                      'test body',
                      recipient_list=['*****@*****.**'])
     assert len(mail.outbox) == 1
     assert mail.outbox[0].subject.find('test subject') == 0
     assert mail.outbox[0].body.find('test body') == 0
Example #40
0
 def test_success_real_mail(self):
     assert send_mail('test subject',
                      'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 1)
     eq_(mail.outbox[0].subject.find('test subject'), 0)
     eq_(mail.outbox[0].body.find('test body'), 0)
    def test_dont_localize(self, fake_Context):
        perm_setting = []

        def ctx(d, autoescape):
            perm_setting.append(unicode(d['perm_setting']))
            return TemplateContext(d, autoescape=autoescape)

        fake_Context.side_effect = ctx
        user = UserProfile.objects.all()[0]
        to = user.email
        translation.activate('zh_TW')
        send_mail('test subject',
                  'test body',
                  perm_setting='reply',
                  recipient_list=[to],
                  fail_silently=False)
        assert perm_setting[0] == u'an add-on developer replies to my review'
Example #42
0
 def test_qa_allowed_list(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**'])
     assert len(mail.outbox) == 1
     assert mail.outbox[0].subject.find('test subject') == 0
     assert mail.outbox[0].body.find('test body') == 0
     assert FakeEmail.objects.count() == 1
     assert FakeEmail.objects.get().message.endswith('test body')
Example #43
0
    def send(self):
        obj = self.addon or self.user
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous coward'

        with no_translation():
            type_ = (gettext(amo.ADDON_TYPE[self.addon.type])
                     if self.addon else 'User')

        subject = u'[%s] Abuse Report for %s' % (type_, obj.name)
        msg = u'%s reported abuse for %s (%s%s).\n\n%s' % (
            user_name, obj.name, settings.SITE_URL, obj.get_url_path(),
            self.message)
        send_mail(subject, msg,
                  recipient_list=(settings.ABUSE_EMAIL,))
Example #44
0
def send_activity_mail(subject,
                       message,
                       version,
                       recipients,
                       from_email,
                       unique_id,
                       perm_setting=None):
    thread_id = f'{version.addon.id}/{version.id}'
    reference_header = '<{thread}@{site}>'.format(
        thread=thread_id, site=settings.INBOUND_EMAIL_DOMAIN)
    message_id = '<{thread}/{message}@{site}>'.format(
        thread=thread_id,
        message=unique_id,
        site=settings.INBOUND_EMAIL_DOMAIN)
    headers = {
        'In-Reply-To': reference_header,
        'References': reference_header,
        'Message-ID': message_id,
    }

    for recipient in recipients:
        token, created = ActivityLogToken.objects.get_or_create(
            version=version, user=recipient)
        if not created:
            token.update(use_count=0)
        else:
            log.info(
                f'Created token with UUID {token.uuid} for user: {recipient.id}.'
            )
        reply_to = '{}{}@{}'.format(
            REPLY_TO_PREFIX,
            token.uuid.hex,
            settings.INBOUND_EMAIL_DOMAIN,
        )
        log.info('Sending activity email to %s for %s version %s' %
                 (recipient, version.addon.pk, version.pk))
        send_mail(
            subject,
            message,
            recipient_list=[recipient.email],
            from_email=from_email,
            use_deny_list=False,
            headers=headers,
            perm_setting=perm_setting,
            reply_to=[reply_to],
        )
Example #45
0
 def test_success_fake_mail(self):
     assert send_mail('test subject',
                      'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 0)
     eq_(FakeEmail.objects.count(), 1)
     eq_(FakeEmail.objects.get().message.endswith('test body'), True)
Example #46
0
def send_activity_mail(subject, message, version, recipients, from_email,
                       perm_setting=None):
    for recipient in recipients:
        token, created = ActivityLogToken.objects.get_or_create(
            version=version, user=recipient)
        if not created:
            token.update(use_count=0)
        else:
            log.info('Created token with UUID %s for user: %s.' % (
                token.uuid, recipient.id))
        reply_to = "%s%s@%s" % (
            REPLY_TO_PREFIX, token.uuid.hex, settings.INBOUND_EMAIL_DOMAIN)
        log.info('Sending activity email to %s for %s version %s' % (
            recipient, version.addon.pk, version.pk))
        send_mail(
            subject, message, recipient_list=[recipient.email],
            from_email=from_email, use_deny_list=False,
            perm_setting=perm_setting, reply_to=[reply_to])
Example #47
0
    def email_confirmation_code(self):
        from olympia.amo.utils import send_mail
        log.debug("Sending account confirmation code for user (%s)", self)

        url = "%s%s" % (settings.SITE_URL,
                        reverse('users.confirm',
                                args=[self.id, self.confirmationcode]))
        domain = settings.DOMAIN
        t = loader.get_template('users/email/confirm.ltxt')
        c = {
            'domain': domain,
            'url': url,
        }
        send_mail(_("Please confirm your email address"),
                  t.render(Context(c)),
                  None, [self.email],
                  use_blacklist=False,
                  real_email=True)
Example #48
0
 def test_qa_whitelist(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     eq_(len(mail.outbox), 1)
     eq_(mail.outbox[0].subject.find('test subject'), 0)
     eq_(mail.outbox[0].body.find('test body'), 0)
     eq_(FakeEmail.objects.count(), 1)
     eq_(FakeEmail.objects.get().message.endswith('test body'), True)
 def test_qa_whitelist(self):
     assert send_mail('test subject', 'test body',
                      recipient_list=['*****@*****.**'],
                      fail_silently=False)
     assert len(mail.outbox) == 1
     assert mail.outbox[0].subject.find('test subject') == 0
     assert mail.outbox[0].body.find('test body') == 0
     assert FakeEmail.objects.count() == 1
     assert FakeEmail.objects.get().message.endswith('test body')
Example #50
0
    def send_notification(self, version):
        user_log.info('Sending addon update notice to %s for %s' %
                      (self.user.email, self.addon.pk))

        if version.channel == amo.RELEASE_CHANNEL_LISTED:
            listing_url = absolutify(
                reverse('addons.detail',
                        args=[self.addon.pk],
                        add_prefix=False))
        else:
            # If the submission went to the unlisted channel,
            # do not link to the listing.
            listing_url = None
        context = {
            'name':
            self.addon.name,
            'url':
            listing_url,
            'number':
            version.version,
            'review':
            absolutify(
                reverse(
                    'reviewers.review',
                    kwargs={
                        'addon_id': self.addon.pk,
                        'channel': amo.CHANNEL_CHOICES_API[version.channel],
                    },
                    add_prefix=False,
                )),
            'SITE_URL':
            settings.SITE_URL,
        }
        # Not being localised because we don't know the reviewer's locale.
        subject = 'Mozilla Add-ons: %s Updated' % self.addon.name
        template = loader.get_template('reviewers/emails/notify_update.ltxt')
        send_mail(
            subject,
            template.render(context),
            recipient_list=[self.user.email],
            from_email=settings.ADDONS_EMAIL,
            use_deny_list=False,
        )
Example #51
0
 def send_notification(self, version):
     user_log.info('Sending addon update notice to %s for %s' %
                   (self.user.email, self.addon.pk))
     context = Context({
         'name': self.addon.name,
         'url': absolutify(reverse('addons.detail', args=[self.addon.pk],
                                   add_prefix=False)),
         'number': version.version,
         'review': absolutify(reverse('editors.review',
                                      args=[self.addon.pk],
                                      add_prefix=False)),
         'SITE_URL': settings.SITE_URL,
     })
     # Not being localised because we don't know the editors locale.
     subject = 'Mozilla Add-ons: %s Updated' % self.addon.name
     template = loader.get_template('editors/emails/notify_update.ltxt')
     send_mail(subject, template.render(Context(context)),
               recipient_list=[self.user.email],
               from_email=settings.EDITORS_EMAIL,
               use_blacklist=False)
Example #52
0
def on_stripe_charge_succeeded(event):
    event_id = event.get("id")
    event_type = event.get("type")

    if event_type != "charge.succeeded":
        log.error(
            'invalid event "%s" received (event_id=%s).', event_type, event_id
        )
        return

    # This event should contain a `charge` object.
    charge = event.get("data", {}).get("object")
    if not charge:
        log.error("no charge object in event (event_id=%s).", event_id)
        return

    charge_id = charge["id"]
    log.info('received "%s" event with charge_id=%s.', event_type, charge_id)

    # Create the Stripe URL pointing to the Stripe payment.
    stripe_payment_url = settings.STRIPE_DASHBOARD_URL
    if not charge.get("livemode"):
        stripe_payment_url = stripe_payment_url + "/test"
    stripe_payment_url = (
        f"{stripe_payment_url}/payments/{charge.get('payment_intent')}"
    )

    subject = "Stripe payment succeeded"
    template = loader.get_template(
        "promoted/emails/stripe_charge_succeeded.txt"
    )
    context = {
        "stripe_payment_url": stripe_payment_url,
    }

    send_mail(
        subject,
        template.render(context),
        from_email=settings.ADDONS_EMAIL,
        recipient_list=[settings.VERIFIED_ADDONS_EMAIL],
    )
Example #53
0
    def send(self):
        if self.reporter:
            user_name = '%s (%s)' % (self.reporter.name, self.reporter.email)
        else:
            user_name = 'An anonymous user'

        # Give a URL pointing to the admin for that report. If there is a
        # target (add-on or user in database) we can point directly to the
        # admin url for that object, otherwise we use the admin url of the
        # report itself.
        if self.target:
            target_url = self.target.get_admin_absolute_url()
            target_name = self.target.name
        else:
            target_url = self.get_admin_absolute_url()
            target_name = self.guid
        metadata = '\n'.join(
            ['%s => %s' % (k, v) for k, v in self.metadata.items()])
        msg = '%s reported abuse for %s (%s).\n\n%s\n\n%s' % (
            user_name, target_name, target_url, metadata, self.message)
        send_mail(str(self), msg, recipient_list=(settings.ABUSE_EMAIL, ))
Example #54
0
def tally_job_results(job_id, **kw):
    sql = """select sum(1),
                    sum(case when completed IS NOT NULL then 1 else 0 end)
             from validation_result
             where validation_job_id=%s"""
    cursor = connection.cursor()
    cursor.execute(sql, [job_id])
    total, completed = cursor.fetchone()
    if completed == total:
        # The job has finished.
        job = ValidationJob.objects.get(pk=job_id)
        job.update(completed=datetime.now())
        if job.finish_email:
            send_mail(
                u'Behold! Validation results for %s %s->%s' %
                (amo.APP_IDS[job.application].pretty,
                 job.curr_max_version.version, job.target_version.version),
                textwrap.dedent("""
                          Aww yeah
                          %s
                          """ % absolutify(reverse('zadmin.validation'))),
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[job.finish_email])
Example #55
0
def on_stripe_charge_succeeded(event):
    event_id = event.get('id')
    event_type = event.get('type')

    if event_type != 'charge.succeeded':
        log.error('invalid event "%s" received (event_id=%s).', event_type,
                  event_id)
        return

    # This event should contain a `charge` object.
    charge = event.get('data', {}).get('object')
    if not charge:
        log.error('no charge object in event (event_id=%s).', event_id)
        return

    charge_id = charge['id']
    log.info('received "%s" event with charge_id=%s.', event_type, charge_id)

    # Create the Stripe URL pointing to the Stripe payment.
    stripe_payment_url = settings.STRIPE_DASHBOARD_URL
    if not charge.get('livemode'):
        stripe_payment_url = stripe_payment_url + '/test'
    stripe_payment_url = f"{stripe_payment_url}/payments/{charge.get('payment_intent')}"

    subject = 'Stripe payment succeeded'
    template = loader.get_template(
        'promoted/emails/stripe_charge_succeeded.txt')
    context = {
        'stripe_payment_url': stripe_payment_url,
    }

    send_mail(
        subject,
        template.render(context),
        from_email=settings.ADDONS_EMAIL,
        recipient_list=[settings.VERIFIED_ADDONS_EMAIL],
    )
Example #56
0
    def test_user_setting_unchecked(self):
        user = UserProfile.objects.all()[0]
        to = user.email
        n = notifications.NOTIFICATIONS_BY_SHORT['reply']
        UserNotification.objects.get_or_create(
            notification_id=n.id, user=user, enabled=False)

        # Confirm we're reading from the database.
        assert UserNotification.objects.filter(
            notification_id=n.id).count() == 1

        success = send_mail('test subject', 'test body', perm_setting='reply',
                            recipient_list=[to])

        assert success, "Email wasn't sent"
        assert len(mail.outbox) == 0
Example #57
0
    def test_user_mandatory(self):
        # Make sure there's no unsubscribe link in mandatory emails.
        user = UserProfile.objects.all()[0]
        to = user.email
        n = notifications.NOTIFICATIONS_BY_SHORT['individual_contact']

        UserNotification.objects.get_or_create(
            notification_id=n.id, user=user, enabled=True)

        assert n.mandatory, "Notification isn't mandatory"

        success = send_mail('test subject', 'test body', perm_setting=n,
                            recipient_list=[to])

        assert success, "Email wasn't sent"
        body = mail.outbox[0].body
        assert "Unsubscribe:" not in body
        assert "You can't unsubscribe from" in body
Example #58
0
    def test_user_setting_default(self):
        user = UserProfile.objects.all()[0]
        to = user.email

        # Confirm there's nothing in the DB and we're using the default
        assert UserNotification.objects.count() == 0

        # Make sure that this is True by default
        setting = notifications.NOTIFICATIONS_BY_SHORT['reply']
        assert setting.default_checked

        success = send_mail('test subject', 'test body', perm_setting='reply',
                            recipient_list=[to])

        assert success, "Email wasn't sent"
        assert len(mail.outbox) == 1
        # bug 676601
        assert mail.outbox[0].body.count('users/unsubscribe') == 1
Example #59
0
    def test_user_setting_checked(self):
        user = UserProfile.objects.all()[0]
        to = user.email
        n = notifications.NOTIFICATIONS_BY_SHORT['reply']
        UserNotification.objects.get_or_create(notification_id=n.id,
                                               user=user,
                                               enabled=True)

        # Confirm we're reading from the database
        eq_(UserNotification.objects.filter(notification_id=n.id).count(), 1)

        success = send_mail('test subject',
                            'test body',
                            perm_setting='reply',
                            recipient_list=[to],
                            fail_silently=False)

        assert "You received this email because" in mail.outbox[0].body
        assert success, "Email wasn't sent"
        eq_(len(mail.outbox), 1)