Python django.conf.settings.DEFAULT_FROM_EMAIL Examples

The following are 30 code examples for showing how to use django.conf.settings.DEFAULT_FROM_EMAIL(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def oauth_authorize(request, request_token, callback, params):
    """
    The callback view for oauth_provider's OAUTH_AUTHORIZE_VIEW.
    """
    consumer = request_token.consumer
    consumerinfo = ConsumerInfo.objects.filter(consumer_id=request_token.consumer_id).order_by('-timestamp').first()
    form = AuthorizeRequestTokenForm(initial={'oauth_token': request_token.key})

    # email the user so we're super-sure they know this is happening
    person = get_object_or_404(Person, userid=request.user.username)
    manage_url = request.build_absolute_uri(reverse('config:manage_tokens'))
    message = EMAIL_INFORM_TEMPLATE.format(consumername=consumer.name, url=manage_url)
    send_mail('CourSys access requested', message, settings.DEFAULT_FROM_EMAIL, [person.email()], fail_silently=False)

    context = {
        'consumer': consumer,
        'consumerinfo': consumerinfo,
        'form': form,
    }
    return render(request, 'api/oauth_authorize.html', context) 
Example 2
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_memo(self):
        """
        Emails the registration confirmation email if there is one and if none has been emailed for this registration
        before.
        """
        # If this registration is waitlisted, don't email!
        if self.waitlisted:
            return
        if 'email' not in self.config and self.event.registration_email_text:
            subject = 'Registration Confirmation'
            from_email = settings.DEFAULT_FROM_EMAIL
            content = self.event.registration_email_text
            msg = EmailMultiAlternatives(subject, content, from_email,
                                         [self.email], headers={'X-coursys-topic': 'outreach'})
            msg.send()
            self.email_sent = content
            self.save() 
Example 3
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_contract(self):
        unit = self.posting.unit
        try:
            contract_email = unit.contract_email_text
            content = contract_email.content
            subject = contract_email.subject
        except TAContractEmailText.DoesNotExist:
            content = DEFAULT_EMAIL_TEXT
            subject = DEFAULT_EMAIL_SUBJECT

        response = HttpResponse(content_type="application/pdf")
        response['Content-Disposition'] = 'inline; filename="%s-%s.pdf"' % (self.posting.slug,
                                                                            self.application.person.userid)
        ta_form(self, response)
        to_email = self.application.person.email()
        if self.posting.contact():
            from_email = self.posting.contact().email()
        else:
            from_email = settings.DEFAULT_FROM_EMAIL
        msg = EmailMultiAlternatives(subject, content, from_email,
                                     [to_email], headers={'X-coursys-topic': 'ta'})
        msg.attach(('"%s-%s.pdf' % (self.posting.slug, self.application.person.userid)), response.getvalue(),
                   'application/pdf')
        msg.send() 
Example 4
Project: telemetry-analysis-service   Author: mozilla   File: test_tasks.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_send_expiration_mails(mailoutbox, mocker, now, cluster_factory):
    cluster = cluster_factory(
        expires_at=now + timedelta(minutes=59),  # 1 hours is the cut-off
        most_recent_status=models.Cluster.STATUS_WAITING,
    )
    assert len(mailoutbox) == 0
    tasks.send_expiration_mails()
    assert len(mailoutbox) == 1
    message = mailoutbox[0]
    assert message.subject == (
        "%sCluster %s is expiring soon!"
        % (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier)
    )
    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.to) == [cluster.created_by.email]
    cluster.refresh_from_db()
    assert cluster.expiration_mail_sent 
Example 5
Project: anytask   Author: znick   File: send_mail_notifications.py    License: MIT License 6 votes vote down vote up
def handle(self, **options):
        start_time = time.time()

        domain = Site.objects.get_current().domain
        from_email = settings.DEFAULT_FROM_EMAIL

        if hasattr(settings, 'SEND_MESSAGE_FULLTEXT') and settings.SEND_MESSAGE_FULLTEXT:
            notify_messages = send_fulltext(domain, from_email)
        else:
            notify_messages = [send_only_notify(domain, from_email)]

        num_sent = 0
        sleep_time = 0
        for messages in notify_messages:
            if messages:
                num_sent += send_mass_mail_html(messages)
                time.sleep(1)
                sleep_time += 1

        # logging to cron log
        print "Command send_mail_notifications send {0} email(s) and took {1} seconds (sleep {2} seconds)" \
            .format(num_sent, time.time() - start_time, sleep_time) 
Example 6
Project: timed-backend   Author: adfinis-sygroup   File: notify_changed_employments.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        email = options["email"]
        last_days = options["last_days"]

        # today is excluded
        end = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        start = end - timedelta(days=last_days)

        employments = Employment.objects.filter(updated__range=[start, end])
        if employments.exists():
            from_email = settings.DEFAULT_FROM_EMAIL
            subject = "[Timed] Employments changed in last {0} days".format(last_days)
            body = template.render({"employments": employments})
            message = EmailMessage(
                subject=subject,
                body=body,
                from_email=from_email,
                to=[email],
                headers=settings.EMAIL_EXTRA_HEADERS,
            )
            message.send() 
Example 7
Project: Django-3-by-Example   Author: PacktPublishing   File: enroll_reminder.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        emails = []
        subject = 'Enroll in a course'
        date_joined = timezone.now().today() - \
                      datetime.timedelta(days=options['days'])
        users = User.objects.annotate(course_count=Count('courses_joined'))\
                            .filter(course_count=0,
                                    date_joined__date__lte=date_joined)
        for user in users:
            message = """Dear {},
            We noticed that you didn't enroll in any courses yet.
            What are you waiting for?""".format(user.first_name)
            emails.append((subject,
                           message,
                           settings.DEFAULT_FROM_EMAIL,
                           [user.email]))
        send_mass_mail(emails)
        self.stdout.write('Sent {} reminders'.format(len(emails))) 
Example 8
Project: django-simple-forum   Author: MicroPyramid   File: views.py    License: MIT License 6 votes vote down vote up
def form_valid(self, form):
        user = User.objects.filter(email=self.request.POST.get('email'))
        if user:
            user = user[0]
            subject = "Password Reset"
            password = get_random_string(6)
            message = '<p>Your Password for the forum account is <strong>'+password + \
                '</strong></p><br/><p>Use this credentials to login into <a href="' + \
                settings.HOST_URL + '/forum/">forum</a></p>'
            to = user.email
            from_email = settings.DEFAULT_FROM_EMAIL
            Memail([to], from_email, subject, message, email_template_name=None, context=None)
            user.set_password(password)
            user.save()
            data = {
                "error": False, "response": "An Email is sent to the entered email id"}
            return JsonResponse(data)
        else:
            data = {
                "error": True, "message": "User With this email id doesn't exists!!!"}
            return JsonResponse(data) 
Example 9
Project: conf_site   Author: pydata   File: mail.py    License: MIT License 6 votes vote down vote up
def send_email(to, kind, cc=[], **kwargs):

    current_site = Site.objects.get_current()

    ctx = {"current_site": current_site, "STATIC_URL": settings.STATIC_URL}
    ctx.update(kwargs.get("context", {}))
    subject = "[%s] %s" % (
        current_site.name,
        render_to_string(
            "symposion/emails/%s/subject.txt" % kind, ctx
        ).strip(),
    )

    message_html = render_to_string(
        "symposion/emails/%s/message.html" % kind, ctx
    )
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    email = EmailMultiAlternatives(
        subject, message_plaintext, from_email, to, cc=cc
    )
    email.attach_alternative(message_html, "text/html")
    email.send() 
Example 10
Project: pasportaservo   Author: tejoesperanto   File: places.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_email(self, user, place):
        config = SiteConfiguration.get_solo()
        email_template_subject = get_template('email/new_authorization_subject.txt')
        email_template_text = get_template('email/new_authorization.txt')
        email_template_html = get_template('email/new_authorization.html')
        # TODO : Unsubscribe link in the email
        email_context = {
            'site_name': config.site_name,
            'ENV': settings.ENVIRONMENT,
            'subject_prefix': settings.EMAIL_SUBJECT_PREFIX_FULL,
            'user': user,
            'place': place,
        }
        # TODO : send mail only if the user chose to receive this type
        send_mail(
            ''.join(email_template_subject.render(email_context).splitlines()),
            email_template_text.render(email_context),
            settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            html_message=email_template_html.render(email_context),
            fail_silently=False,
        ) 
Example 11
Project: pasportaservo   Author: tejoesperanto   File: test_utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_mass_html_mail(self):
        test_data = list()
        faker = Faker()
        for i in range(random.randint(3, 7)):
            test_data.append((
                faker.sentence(),
                faker.word(), "<strong>{}</strong>".format(faker.word()),
                "test@ps", [],
            ))
            for j in range(random.randint(1, 3)):
                test_data[i][4].append(faker.email())

        result = send_mass_html_mail(test_data)
        self.assertEqual(result, len(test_data))
        self.assertEqual(len(mail.outbox), len(test_data))
        for i in range(len(test_data)):
            for j in range(len(test_data[i][4])):
                self.assertEqual(mail.outbox[i].subject, test_data[i][0])
                self.assertEqual(mail.outbox[i].from_email, settings.DEFAULT_FROM_EMAIL)
                self.assertEqual(mail.outbox[i].to, test_data[i][4]) 
Example 12
Project: pasportaservo   Author: tejoesperanto   File: utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None,
                        connection=None):
    """
    Given a datatuple of (subject, text_content, html_content, from_email,
    recipient_list), sends each message to each recipient list. Returns the
    number of emails sent.

    If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
    If auth_user and auth_password are set, they're used to log in.
    If auth_user is None, the EMAIL_HOST_USER setting is used.
    If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
    """
    connection = connection or get_connection(
        username=user, password=password, fail_silently=fail_silently)
    messages = []
    default_from = settings.DEFAULT_FROM_EMAIL
    for subject, text, html, from_email, recipients in datatuple:
        message = EmailMultiAlternatives(
            subject, text, default_from, recipients,
            headers={'Reply-To': 'Pasporta Servo <saluton@pasportaservo.org>'})
        message.attach_alternative(html, 'text/html')
        messages.append(message)
    return connection.send_messages(messages) or 0 
Example 13
Project: codesy   Author: codesy   File: check_validation.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        accounts = StripeAccount.objects.all()
        for account in accounts:
            try:
                stripe_account = stripe.Account.retrieve(account.account_id)
                if account.verification != stripe_account.verification:
                    account.verification = json.dumps(
                        stripe_account.verification)
                    account.save()
                    if stripe_account.verification.fields_needed:
                        email_context = (
                            {'expiration': stripe_account.verification.due_by})
                        message = email_template.render(email_context)
                        send_mail(
                            '[codesy] Account validation needed',
                            message,
                            settings.DEFAULT_FROM_EMAIL,
                            [account.user.email]
                        )
            except:
                e = sys.exc_info()[0]
                logger.error("Error during check_validation: %s" % e) 
Example 14
Project: codesy   Author: codesy   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_matching_askers(sender, instance, **kwargs):
    email_template = get_template('../templates/email/ask_met.html')
    unnotified_asks = Bid.objects.filter(
        url=instance.url, ask_match_sent=None).exclude(ask__lte=0)

    for bid in unnotified_asks:
        if bid.ask_met():
            email_context = {'ask': bid.ask, 'url': bid.url}
            subject = (
                "[codesy] There's $%(ask)d waiting for you!" % email_context
            )
            message = email_template.render(email_context)
            send_mail(
                subject,
                message,
                settings.DEFAULT_FROM_EMAIL,
                [bid.user.email]
            )
            # use .update to avoid recursive signal processing
            Bid.objects.filter(id=bid.id).update(ask_match_sent=timezone.now()) 
Example 15
Project: appstore   Author: nextcloud   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def password_changed_signal(sender, instance, **kwargs):
    """
    Regenerate token on password change
    :param sender:
    :param instance:
    :param kwargs:
    :return:
    """
    mail_subect = _('Nextcloud Appstore password changed')
    mail_message = _('Your Appstore password has changed. '
                     'Contact support if this wasn\'t you.')

    try:
        user = get_user_model().objects.get(pk=instance.pk)
        if user.password != instance.password:
            update_token(user.username)
            send_mail(
                    mail_subect,
                    mail_message,
                    settings.DEFAULT_FROM_EMAIL,
                    [user.email],
                    False)
    except User.DoesNotExist:
        pass 
Example 16
Project: djreservation   Author: luisza   File: email.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_html_email(subject, template, context=None):
    if context is None:
        context = {}
    reservation = context['reservation']
    message = render_to_string(template,
                               context)
    send_mail(
        subject=subject,
        message=_('Please, use an email with html support'),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[reservation.user.email],
        fail_silently=True,
        html_message=message
    ) 
Example 17
Project: oxidizr   Author: pixlie   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def email(recipient, context, template_name, sender=None):
    if not settings.MANDRILL_API_KEY or settings.MANDRILL_API_KEY == 'None':
        return
    current_site = Site.objects.get_current()
    context['domain'] = current_site.domain
    User = django.contrib.auth.get_user_model()
    # The recipient list can be a list of User model instances or Email Address string
    # Which means you could pass a User model QuerySet as recipient
    # If a recipient is User model instance then simple convert to Email Address string
    recipient_email_list = []
    for rec in recipient:
        if isinstance(rec, User):
            if rec.first_name and rec.last_name:
                recipient_email_list.append('"%s %s" <%s>' % (rec.first_name, rec.last_name, rec.email))
            elif rec.first_name:
                recipient_email_list.append('"%s" <%s>' % (rec.first_name, rec.email))
            else:
                recipient_email_list.append('%s' % rec.email)
        else:
            recipient_email_list.append(rec)

    mail.send(
        sender=sender or settings.DEFAULT_FROM_EMAIL,
        recipients=recipient_email_list,
        template=template_name,
        context=context,
        priority=PRIORITY.now
    ) 
Example 18
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_expiring_ras(cls):
        """
        Emails the supervisors of the RAs who have appointments that are about to expire.
        """
        subject = 'RA appointment expiry reminder'
        from_email = settings.DEFAULT_FROM_EMAIL

        expiring_ras = cls.expiring_appointments()
        template = get_template('ra/emails/reminder.txt')

        for raappt in expiring_ras:
            supervisor = raappt.hiring_faculty
            context = {'supervisor': supervisor, 'raappt': raappt}
            # Let's see if we have any Funding CC supervisors that should also get the reminder.
            cc = None
            fund_cc_roles = Role.objects_fresh.filter(unit=raappt.unit, role='FDCC')
            # If we do, let's add them to the CC list, but let's also make sure to use their role account email for
            # the given role type if it exists.
            if fund_cc_roles:
                people = []
                for role in fund_cc_roles:
                    people.append(role.person)
                people = list(set(people))
                cc = []
                for person in people:
                    cc.append(person.role_account_email('FDCC'))
            msg = EmailMultiAlternatives(subject, template.render(context), from_email, [supervisor.email()],
                                         headers={'X-coursys-topic': 'ra'}, cc=cc)
            msg.send()
            raappt.mark_reminded() 
Example 19
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_from(self):
        """
        Determine who the email should appear to come from: perfer to use course contact email if exists.
        """
        if self.course and self.course.taemail():
            if self.author:
                return "%s <%s> (per %s)" % (self.course.name(), self.course.taemail(), self.author.name())
            else:
                return "%s <%s>" % (self.course.name(), self.course.taemail())
        elif self.author:
            return self.author.full_email()
        else:
            return settings.DEFAULT_FROM_EMAIL
    
    # turn the source_app field into a more externally-friendly string 
Example 20
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_confirm(self, recipient):
        msg = EmailMultiAlternatives(subject=self.emailsubject(), body=self.emailbody(),
                                     from_email=settings.DEFAULT_FROM_EMAIL, to=[recipient.full_email()],
                                     headers={'X-coursys-topic': 'onlineforms'})
        msg.send() 
Example 21
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_waiting_sheets(cls):
        """
        Email those with sheets waiting for their attention.
        """
        full_url = settings.BASE_ABS_URL + reverse('onlineforms:login')
        subject = 'Waiting form reminder'
        from_email = settings.DEFAULT_FROM_EMAIL

        filler_ss = cls.waiting_sheets_by_user()
        template = get_template('onlineforms/emails/reminder.txt')
        
        for filler, sheets in filler_ss:
            # annotate with secret URL, so we can remind of that.
            sheets = list(sheets)
            for s in sheets:
                secrets = SheetSubmissionSecretUrl.objects.filter(sheet_submission=s)
                if secrets:
                    s.secret = secrets[0]
                else:
                    s.secret = None

                FormLogEntry.create(sheet_submission=s, category='MAIL',
                        description='Reminded %s of waiting sheet.' % (filler.email()))

            context = {'full_url': full_url,
                    'filler': filler, 'sheets': list(sheets), 'BASE_ABS_URL': settings.BASE_ABS_URL,
                    'CourSys': product_name(hint='forms')}
            msg = EmailMultiAlternatives(subject, template.render(context), from_email, [filler.email()],
                    headers={'X-coursys-topic': 'onlineforms'})
            msg.send() 
Example 22
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_submitted(self, request, rejected=False):
        full_url = request.build_absolute_uri(reverse('onlineforms:view_submission',
                                    kwargs={'form_slug': self.sheet.form.slug,
                                            'formsubmit_slug': self.form_submission.slug}))
        context = {'initiator': self.filler.name(), 'adminurl': full_url, 'form': self.sheet.form,
                                 'rejected': rejected}
        subject = '%s submission' % (self.sheet.form.title)
        self._send_email(request, 'sheet_submitted', subject,
                         settings.DEFAULT_FROM_EMAIL, self.sheet.form.owner.notify_emails(), context)

        FormLogEntry.create(sheet_submission=self, category='MAIL',
                description='Notified group "%s" that %s %s their sheet.' % (self.sheet.form.owner.name,
                        self.filler.full_email(), 'rejected' if rejected else 'completed')) 
Example 23
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def email_memo(self):
        """
        Emails the person to whom the booking is assigned.
        """
        subject = 'Booking notification'
        from_email = settings.DEFAULT_FROM_EMAIL
        template = get_template('space/emails/memo.txt')
        context = {'booking': self.booking_record, 'CourSys': product_name(hint='admin')}
        msg = EmailMultiAlternatives(subject, template.render(context), from_email,
                                     [self.booking_record.person.email()], headers={'X-coursys-topic': 'space'})
        msg.send()


# A stupid object to keep track of the key assignment forms for SEE/Surrey. 
Example 24
Project: coursys   Author: sfu-fas   File: panel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_test_email(email):
    try:
        send_mail('check_things test message', "This is a test message to make sure they're getting through.",
                  settings.DEFAULT_FROM_EMAIL, [email], fail_silently=False)
        return True, "Message sent to %s." % (email)
    except socket.error:
        return False, "socket error: maybe can't communicate with AMPQ for celery sending?" 
Example 25
Project: django-herald   Author: worthwhile   File: base.py    License: MIT License 5 votes vote down vote up
def get_sent_from(self):
        from_email = self.from_email

        if not from_email:
            from_email = settings.DEFAULT_FROM_EMAIL

        return from_email 
Example 26
Project: GTDWeb   Author: lanbing510   File: message.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                 connection=None, attachments=None, headers=None, cc=None,
                 reply_to=None):
        """
        Initialize a single email message (which can be sent to multiple
        recipients).

        All strings used to create the message can be unicode strings
        (or UTF-8 bytestrings). The SafeMIMEText class will handle any
        necessary encoding conversions.
        """
        if to:
            if isinstance(to, six.string_types):
                raise TypeError('"to" argument must be a list or tuple')
            self.to = list(to)
        else:
            self.to = []
        if cc:
            if isinstance(cc, six.string_types):
                raise TypeError('"cc" argument must be a list or tuple')
            self.cc = list(cc)
        else:
            self.cc = []
        if bcc:
            if isinstance(bcc, six.string_types):
                raise TypeError('"bcc" argument must be a list or tuple')
            self.bcc = list(bcc)
        else:
            self.bcc = []
        if reply_to:
            if isinstance(reply_to, six.string_types):
                raise TypeError('"reply_to" argument must be a list or tuple')
            self.reply_to = list(reply_to)
        else:
            self.reply_to = []
        self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
        self.subject = subject
        self.body = body
        self.attachments = attachments or []
        self.extra_headers = headers or {}
        self.connection = connection 
Example 27
Project: telemetry-analysis-service   Author: mozilla   File: test_tasks.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_extended_cluster_resends_expiration_mail(mailoutbox, mocker, one_hour_ago, cluster_factory):
    cluster = cluster_factory(
        expires_at=one_hour_ago,
        most_recent_status=models.Cluster.STATUS_WAITING,
    )

    # Send first expiration email
    assert len(mailoutbox) == 0
    tasks.send_expiration_mails()
    assert len(mailoutbox) == 1
    message = mailoutbox[0]
    assert message.subject == (
        '%sCluster %s is expiring soon!' %
        (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier)
    )
    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.to) == [cluster.created_by.email]
    cluster.refresh_from_db()
    assert cluster.expiration_mail_sent

    # Extend cluster lifetime
    cluster.extend(1)
    cluster.refresh_from_db()
    assert cluster.expiration_mail_sent is False

    # Send second expiration email
    tasks.send_expiration_mails()
    assert len(mailoutbox) == 2
    message = mailoutbox[1]
    assert message.subject == (
        '%sCluster %s is expiring soon!' %
        (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier)
    )
    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.to) == [cluster.created_by.email]
    cluster.refresh_from_db()
    assert cluster.expiration_mail_sent 
Example 28
Project: telemetry-analysis-service   Author: mozilla   File: test_tasks.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_send_run_alert_mails(
    client, mailoutbox, mocker, spark_job, sparkjob_provisioner_mocks
):
    mocker.patch(
        "atmo.clusters.provisioners.ClusterProvisioner.info",
        return_value={
            "creation_datetime": timezone.now(),
            "ready_datetime": None,
            "end_datetime": None,
            "state": Cluster.STATUS_TERMINATED_WITH_ERRORS,
            "state_change_reason_code": Cluster.STATE_CHANGE_REASON_BOOTSTRAP_FAILURE,
            "state_change_reason_message": "Bootstrapping steps failed.",
            "public_dns": None,
        },
    )
    spark_job.run()
    assert spark_job.latest_run.alerts.exists()
    assert len(mailoutbox) == 0
    tasks.send_run_alert_mails()
    assert len(mailoutbox) == 1
    message = mailoutbox[0]
    assert message.subject == (
        "%sRunning Spark job %s failed"
        % (settings.EMAIL_SUBJECT_PREFIX, spark_job.identifier)
    )

    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.cc) == [settings.DEFAULT_FROM_EMAIL]
    assert list(message.to) == [spark_job.created_by.email] 
Example 29
Project: telemetry-analysis-service   Author: mozilla   File: test_tasks.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def test_send_expired_mails(mailoutbox, mocker, now, spark_job):
    spark_job.expired_date = now
    spark_job.save()
    assert len(mailoutbox) == 0
    tasks.send_expired_mails()
    assert len(mailoutbox) == 1
    message = mailoutbox[0]
    assert message.subject == (
        "%sSpark job %s expired" % (settings.EMAIL_SUBJECT_PREFIX, spark_job.identifier)
    )
    assert message.from_email == settings.DEFAULT_FROM_EMAIL
    assert list(message.cc) == [settings.DEFAULT_FROM_EMAIL]
    assert list(message.to) == [spark_job.created_by.email]
    spark_job.refresh_from_db() 
Example 30
Project: anytask   Author: znick   File: send_issue_duplicate_notify.py    License: MIT License 5 votes vote down vote up
def handle(self, **options):
        start_time = time.time()

        issues_duplicates = defaultdict(list)
        domain = Site.objects.get_current().domain

        for info in Issue.objects.values("id", "student_id", "task_id"):
            key = (info["student_id"], info["task_id"])
            issues_duplicates[key].append(info["id"])

        subject = "Duplicate issue"
        message = ""
        issues_len = 0
        for key, issues_ids in issues_duplicates.iteritems():
            if len(issues_ids) > 1:
                issues_len += 1
                for issue_id in issues_ids:
                    message += u"Issue:\t{0}\n".format(domain + '/admin/issues/issue/' + str(issue_id))
                message += u"\n" + u"*" * 20 + u"\n\n"

        if message:
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, ["anytask@yandex.ru"])

        # logging to cron log
        print "Command send_issue_duplicate_notify find {0} issues and took {1} seconds" \
            .format(issues_len, time.time() - start_time)