Python django.core.mail.EmailMultiAlternatives() Examples

The following are 30 code examples for showing how to use django.core.mail.EmailMultiAlternatives(). 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.core.mail , or try the search function .

Example 1
Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 6 votes vote down vote up
def send_email_ticket_confirm(request, payment_info):
    """
    :param request Django request object
    :param payment_info Registration object
    """
    mail_title = u"PyCon Korea 2015 등록확인 안내(Registration confirmation)"
    product = Product()
    variables = Context({
        'request': request,
        'payment_info': payment_info,
        'amount': product.price
    })
    html = get_template('mail/ticket_registered_html.html').render(variables)
    text = get_template('mail/ticket_registered_text.html').render(variables)
    
    msg = EmailMultiAlternatives(
        mail_title,
        text,
        settings.EMAIL_SENDER,
        [payment_info.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example 2
Project: open-synthesis   Author: twschiller   File: digest.py    License: GNU General Public License v3.0 6 votes vote down vote up
def create_digest_email(user, digest_frequency, as_of):
    """Return the digest email message for user based on when they last received a digest message."""
    start = user_digest_start(user, digest_frequency, as_of)
    context = notification_digest(user, start, as_of)

    logger.debug('Digest as of %s: %s', start, context)

    if context:
        context['timestamp'] = as_of
        context['site'] = Site.objects.get_current()
        context['digest_frequency'] = digest_frequency.name

        subject = render_to_string('boards/email/email_digest_subject.txt', context=context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()

        text_body = render_to_string('boards/email/email_digest_message.txt', context=context)
        html_body = render_to_string('boards/email/email_digest_message.html', context=context)

        email = EmailMultiAlternatives(subject=subject, body=text_body, to=[user.email])
        email.attach_alternative(html_body, "text/html")
        return email
    else:
        return None 
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_user(self, text_template, html_template, context):
        offering = context['offering']
        headers = {
                'Precedence': 'bulk',
                'Auto-Submitted': 'auto-generated',
                'X-coursys-topic': 'discussion',
                'X-course': offering.slug,
                'Sender': settings.DEFAULT_SENDER_EMAIL,
                }
        to_email = context['to'].email()
        if offering.taemail():
            from_email = "%s <%s>" % (offering.name(), offering.taemail())
        else:
            from_email = settings.DEFAULT_SENDER_EMAIL
        text_content = get_template(text_template).render(context)
        html_content = get_template(html_template).render(context)
        
        msg = EmailMultiAlternatives(context['subject'], text_content, from_email, [to_email], headers=headers)
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 4
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_notify_new_owner(self, request, admin):
        plaintext = get_template('onlineforms/emails/notify_new_owner.txt')
        html = get_template('onlineforms/emails/notify_new_owner.html')

        full_url = request.build_absolute_uri(reverse('onlineforms:view_submission',
                                    kwargs={'form_slug': self.form.slug,
                                            'formsubmit_slug': self.slug}))
        email_context = {'formsub': self, 'admin': admin, 'adminurl': full_url}
        subject = '%s submission transferred' % (self.form.title)
        from_email = FormFiller.form_full_email(admin)
        to = self.owner.notify_emails()
        msg = EmailMultiAlternatives(subject=subject, body=plaintext.render(email_context),
                from_email=from_email, to=to, bcc=[admin.full_email()],
                headers={'X-coursys-topic': 'onlineforms'})
        msg.attach_alternative(html.render(email_context), "text/html")
        msg.send()

        FormLogEntry.create(form_submission=self, category='MAIL',
                    description='Notified group "%s" that form submission was transferred to them.'
                                % (self.owner.name,)) 
Example 5
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 6
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 7
Project: arches   Author: archesproject   File: mobile_survey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_mobile_survey_start(self, request, mobile_survey):
        admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
        email_context = {
            "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
            "link": request.build_absolute_uri(reverse("home")),
            "greeting": _(
                "Welcome to Arches!  You've just been added to a Mobile Survey.  \
                Please take a moment to review the mobile_survey description and mobile_survey start and end dates."
            ),
            "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
        }

        html_content = render_to_string("email/general_notification.htm", email_context)
        text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

        # create the email, and attach the HTML version as well.
        for user in self.get_mobile_survey_users(mobile_survey):
            msg = EmailMultiAlternatives(
                _("You've been invited to an {app_name} Survey!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send() 
Example 8
Project: GTDWeb   Author: lanbing510   File: forms.py    License: GNU General Public License v2.0 6 votes vote down vote up
def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send() 
Example 9
Project: bioforum   Author: reBiocoder   File: forms.py    License: MIT License 6 votes vote down vote up
def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send() 
Example 10
Project: arguman.org   Author: arguman   File: utils.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_complex_mail(subject,
                      template_txt,
                      template_html,
                      _from,
                      to=None,
                      cc=None,
                      bcc=None,
                      context=None):

    context = {} if not context else context
    subject, from_email = subject, _from
    context['BASE_URL'] = settings.BASE_DOMAIN
    text_content = render_to_string(template_txt, Context(context))
    html_content = render_to_string(template_html, Context(context))

    msg = EmailMultiAlternatives(subject,
                                 text_content,
                                 from_email,
                                 to=to,
                                 cc=cc,
                                 bcc=bcc)
    msg.attach_alternative(html_content, "text/html")
    msg.send(fail_silently=True) 
Example 11
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 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: xos   Author: open-cloud   File: user.py    License: Apache License 2.0 6 votes vote down vote up
def send_temporary_password(self):
        password = User.objects.make_random_password()
        self.set_password(password)
        subject, from_email, to = (
            "OpenCloud Account Credentials",
            "support@opencloud.us",
            str(self.email),
        )
        text_content = "This is an important message."
        userUrl = "http://%s/" % get_request().get_host()
        html_content = (
            """<p>Your account has been created on OpenCloud. Please log in <a href="""
            + userUrl
            + """>here</a> to activate your account<br><br>Username: """
            + self.email
            + """<br>Temporary Password: """
            + password
            + """<br>Please change your password once you successully login into the site.</p>"""
        )
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 14
Project: cornerwise   Author: codeforboston   File: mail.py    License: MIT License 6 votes vote down vote up
def send_template(email, subject, template_name, context=None, logger=logger):
    """Construct and send an email with subject `subject` to `email`, using the
    named email template.
    """
    context = context or {}
    html, text = render_email_body(template_name, context)

    mail = EmailMultiAlternatives(
        from_email=f"{settings.EMAIL_NAME} <{settings.EMAIL_ADDRESS}>",
        subject=subject,
        body=text,
        to=(email if isinstance(email, list) else [email]))
    mail.attach_alternative(html, "text/html")
    mail.send()
    logger.info("Sent '%s' email to %s", template_name,
                email) 
Example 15
Project: hknweb   Author: compserv   File: views.py    License: MIT License 6 votes vote down vote up
def send_request_email(self, form):
        subject = '[HKN] Confirm Officer Challenge'
        officer_email = form.instance.officer.email

        confirm_link = self.request.build_absolute_uri(
                reverse("candidate:challengeconfirm", kwargs={ 'pk' : form.instance.id }))
        html_content = render_to_string(
            'candidate/challenge_request_email.html',
            {
                'subject': subject,
                'candidate_name' : form.instance.requester.get_full_name(),
                'candidate_username' : form.instance.requester.username,
                'confirm_link' : confirm_link,
                'img_link' : get_rand_photo(),
            }
        )
        msg = EmailMultiAlternatives(subject, subject,
                'no-reply@hkn.eecs.berkeley.edu', [officer_email])
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 16
Project: hknweb   Author: compserv   File: views.py    License: MIT License 6 votes vote down vote up
def send_request_email(self, form):
        subject = '[HKN] Bit-byte request submitted'
        participant_emails = [part.email for part in form.instance.participants.all()]

        bitbyte_link = self.request.build_absolute_uri(
            reverse("candidate:bitbyte"))
        html_content = render_to_string(
            'candidate/bitbyte_request_email.html',
            {
                'subject': subject,
                'requester': self.request.user,
                'participants': form.instance.participants.all(),
                'bitbyte_link': bitbyte_link,
                'img_link': get_rand_photo(),
            }
        )
        msg = EmailMultiAlternatives(subject, subject,
                    settings.NO_REPLY_EMAIL, participant_emails)
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 17
Project: hknweb   Author: compserv   File: views.py    License: MIT License 6 votes vote down vote up
def send_challenge_confirm_email(request, challenge, confirmed):
    subject = '[HKN] Your officer challenge was reviewed'
    candidate_email = challenge.requester.email

    challenge_link = request.build_absolute_uri(
            reverse("candidate:detail", kwargs={ 'pk': challenge.id }))
    html_content = render_to_string(
        'candidate/challenge_confirm_email.html',
        {
            'subject': subject,
            'confirmed': confirmed,
            'officer_name': challenge.officer.get_full_name(),
            'officer_username': challenge.officer.username,
            'challenge_link': challenge_link,
            'img_link': get_rand_photo(),
        }
    )
    msg = EmailMultiAlternatives(subject, subject,
                settings.NO_REPLY_EMAIL, [candidate_email])
    msg.attach_alternative(html_content, "text/html")
    msg.send() 
Example 18
Project: hknweb   Author: compserv   File: views.py    License: MIT License 6 votes vote down vote up
def send_bitbyte_confirm_email(request, bitbyte, confirmed):
    subject = '[HKN] Your bit-byte request was reviewed'
    participant_emails = [part.email for part in bitbyte.participants.all()]

    bitbyte_link = request.build_absolute_uri(
        reverse("candidate:bitbyte"))
    html_content = render_to_string(
        'candidate/bitbyte_confirm_email.html',
        {
            'subject': subject,
            'confirmed': confirmed,
            'participants': bitbyte.participants.all(),
            'bitbyte_link': bitbyte_link,
            'img_link': get_rand_photo(),
        }
    )
    msg = EmailMultiAlternatives(subject, subject,
                settings.NO_REPLY_EMAIL, participant_emails)
    msg.attach_alternative(html_content, "text/html")
    msg.send() 
Example 19
Project: hknweb   Author: compserv   File: views.py    License: MIT License 6 votes vote down vote up
def send_off_waitlist_email(request, user, event):
    subject = '[HKN] You have gotten off the waitlist for your event'

    event_link = request.build_absolute_uri(
            reverse("events:detail", kwargs={ 'id': event.id }))
    html_content = render_to_string(
        'events/off_waitlist_email.html',
        {
            'subject': subject,
            'event_name': event.name,
            'event_link': event_link,
            'img_link': get_rand_photo(),
        }
    )
    msg = EmailMultiAlternatives(subject, subject,
                settings.NO_REPLY_EMAIL, [user.email])
    msg.attach_alternative(html_content, "text/html")
    msg.send() 
Example 20
Project: clist   Author: aropan   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def send_email(self, **kwargs):
        if self.is_sent:
            return
        event = self.team.event
        filepath = event.email_conf['logins-templates'][TeamStatus.labels[self.stage]]
        template = get_template(filepath)
        message = template.render({'login': self, 'team': self.team})
        subject, message = message.split('\n\n', 1)
        message = message.replace('\n', '<br>\n')
        to = []
        for m in self.team.ordered_participants:
            to.append(m.email)
        msg = EmailMultiAlternatives(
            subject,
            message,
            to=to,
            **kwargs
        )
        msg.attach_alternative(message, 'text/html')
        result = msg.send()
        if result:
            self.is_sent = True
            self.save()
        return result 
Example 21
Project: xos   Author: opencord   File: user.py    License: Apache License 2.0 6 votes vote down vote up
def send_temporary_password(self):
        password = User.objects.make_random_password()
        self.set_password(password)
        subject, from_email, to = (
            "OpenCloud Account Credentials",
            "support@opencloud.us",
            str(self.email),
        )
        text_content = "This is an important message."
        userUrl = "http://%s/" % get_request().get_host()
        html_content = (
            """<p>Your account has been created on OpenCloud. Please log in <a href="""
            + userUrl
            + """>here</a> to activate your account<br><br>Username: """
            + self.email
            + """<br>Temporary Password: """
            + password
            + """<br>Please change your password once you successully login into the site.</p>"""
        )
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 22
Project: zing   Author: evernote   File: payment_email.py    License: GNU General Public License v3.0 6 votes vote down vote up
def send(self):
        """Sends the payment email along with the invoice."""
        body = self.get_body()

        # Set non-empty body according to
        # http://stackoverflow.com/questions/14580176/confusion-with-sending-email-in-django
        mail = EmailMultiAlternatives(
            subject=self.get_subject(),
            body=strip_tags(body),
            to=self.get_recipient_list(),
            cc=self.get_cc_list(),
            bcc=self.get_bcc_list(),
        )
        mail.attach_alternative(body, "text/html")

        for attachment in self.attachments:
            mail.attach_file(attachment[0], attachment[1])

        return mail.send() 
Example 23
Project: ishare   Author: jeeyshe   File: mail.py    License: MIT License 6 votes vote down vote up
def test_mail():
    subject = '{}这是一封测试邮件,邀你共赏美文《青春》'.format(EMAIL_SUBJECT_PREFIX)
    text_content = """
    青春不是年华,而是心境;青春不是桃面、丹唇、柔膝,而是深沉的意志、恢宏的想像、炽热的感情;青春是生命的深泉涌流。

    青春气贯长虹,勇锐盖过怯弱,进取压倒苟安。如此锐气,二十后生有之,六旬男子则更多见。年岁有加,并非垂老;理想丢弃,方堕暮年。

    岁月悠悠,衰微只及肌肤;热忱抛却,颓唐必致灵魂。忧烦、惶恐、丧失自信,定使心灵扭曲,意气如灰。

    无论年届花甲,抑或二八芳龄,心中皆有生命之欢乐,奇迹之诱惑,孩童般天真久盛不衰。人的心灵应如浩淼瀚海,只有不断接纳美好、希望、欢乐、勇气和力量的百川,才能青春永驻、风华长存。

    一旦心海枯竭,锐气便被冰雪覆盖,玩世不恭、自暴自弃油然而生,即使年方二十,实已垂垂老矣;然则只要虚怀若谷,让喜悦、达观、仁爱充盈其间,你就有望在八十高龄告别尘寰时仍觉年轻。
    """
    # html_content = '<p>这是一封<strong>重要的</strong>邮件.</p>'
    msg = EmailMultiAlternatives(subject, text_content, SERVER_EMAIL, ['support@lujianxin.com'])
    # msg.attach_alternative(html_content, "text/html")
    msg.send() 
Example 24
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: forms.py    License: MIT License 6 votes vote down vote up
def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send() 
Example 25
Project: pythonic-news   Author: sebst   File: receivers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_invitation_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, Invitation):
        subject, from_email, to = 'You have been invited to %s'%(settings.SITE_DOMAIN), 'bot@python.sc', instance.invited_email_address
        text_content = """
You have been invited to news.python.sc.

Would you like to accept {inviting_user}'s invite?

Please sign up here: https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(inviting_user=instance.inviting_user.username, url=instance.get_register_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 26
Project: pythonic-news   Author: sebst   File: receivers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_verification_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, EmailVerification):
        subject, from_email, to = 'Please confirm your account on news.python.sc', 'bot@python.sc', instance.email
        text_content = """
Please confirm your email address here:

https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(url=instance.get_verify_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 27
Project: pythonic-news   Author: sebst   File: receivers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def send_password_reset_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, PasswordResetRequest):
        subject, from_email, to = 'Reset password for your account on news.python.sc', 'bot@python.sc', instance.email
        text_content = """
Please confirm your email address here:

https://news.python.sc{url}

-- 
news.python.sc - A social news aggregator for the Python community.

""".format(url=instance.get_verify_url())
        #html_content = '<p>This is an <strong>important</strong> message.</p>'
        msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
        #msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 28
Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 5 votes vote down vote up
def sendEmailToken(request, token):
    variables = Context({
        'request': request,
        'token': token,
    })
    html = get_template('mail/token_html.html').render(variables)
    text = get_template('mail/token_text.html').render(variables)

    msg = EmailMultiAlternatives(
        settings.EMAIL_LOGIN_TITLE,
        text,
        settings.EMAIL_SENDER,
        [token.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example 29
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 30
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()