Python django.core.mail.EmailMultiAlternatives() Examples

The following are 30 code examples of django.core.mail.EmailMultiAlternatives(). 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 also want to check out all available functions/classes of the module django.core.mail , or try the search function .
Example #1
Source File: receivers.py    From pythonic-news with 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 #2
Source File: models.py    From coursys with 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 #3
Source File: models.py    From coursys with 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 #4
Source File: digest.py    From open-synthesis with 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 #5
Source File: mobile_survey.py    From arches with 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 #6
Source File: models.py    From coursys with 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 #7
Source File: models.py    From coursys with 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 #8
Source File: forms.py    From GTDWeb with 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
Source File: forms.py    From bioforum with 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
Source File: utils.py    From arguman.org with 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
Source File: mail.py    From conf_site with 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
Source File: utils.py    From pasportaservo with 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
Source File: user.py    From xos with 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
Source File: mail.py    From cornerwise with 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
Source File: views.py    From hknweb with 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
Source File: views.py    From hknweb with 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
Source File: views.py    From hknweb with 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
Source File: views.py    From hknweb with 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
Source File: views.py    From hknweb with 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
Source File: models.py    From clist with 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
Source File: user.py    From xos with 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
Source File: payment_email.py    From zing with 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
Source File: mail.py    From ishare with 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
Source File: forms.py    From Hands-On-Application-Development-with-PyCharm with 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
Source File: receivers.py    From pythonic-news with 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
Source File: receivers.py    From pythonic-news with 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
Source File: helper.py    From pyconkr-2015 with 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 #28
Source File: misc.py    From happinesspackets with Apache License 2.0 5 votes vote down vote up
def send_html_mail(subject, body_txt, body_html, recipient):
    message = EmailMultiAlternatives(subject, body_txt, settings.DEFAULT_FROM_EMAIL, [recipient])
    message.attach_alternative(body_html, 'text/html')
    message.mixed_subtype = 'related'

    logo_file = open(settings.STATIC_ROOT.child('images').child('logo.png'))
    logo_mime = MIMEImage(logo_file.read())
    logo_file.close()
    logo_mime.add_header('Content-ID', '<logo.png@happinesspackets.io>')
    logo_mime.add_header('Content-Disposition', 'attachment')

    message.attach(logo_mime)
    message.send() 
Example #29
Source File: mail.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def send_mail(
    subject,
    message,
    from_email,
    recipient_list,
    fail_silently=False,
    auth_user=None,
    auth_password=None,
    connection=None,
    html_message=None,
    headers=None,
    cc=None,
    bcc=None,
):
    """Override django send_mail function to allow use of custom email headers.
    """

    connection = connection or get_connection(
        username=auth_user, password=auth_password, fail_silently=fail_silently
    )

    mail = EmailMultiAlternatives(
        subject,
        message,
        from_email,
        recipient_list,
        connection=connection,
        headers=headers,
        cc=cc,
        bcc=bcc,
    )

    if html_message:
        mail.attach_alternative(html_message, "text/html")

    return mail.send() 
Example #30
Source File: notifications.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_email(log: ProcessLogger, dst_user, subject: str, txt: str, html: str, image_dir: str, cc: Set[str] = None):
    if not dst_user.email:
        log.error('Destination user {0} has no email assigned'.format(dst_user.get_full_name()))
        return

    try:
        from apps.notifications.mail_server_config import MailServerConfig
        backend = MailServerConfig.make_connection_config()
        email = EmailMultiAlternatives(subject=subject,
                                       body=txt,
                                       cc=list(cc) if cc else None,
                                       from_email=settings.DEFAULT_FROM_EMAIL,
                                       to=['"{0}" <{1}>'.format(dst_user.get_full_name(), dst_user.email)],
                                       connection=backend)
        if html:
            images = [m.group(3) for m in RE_SRC_ATTACHMENT.finditer(html)]
            email_html = RE_SRC_ATTACHMENT.sub(r'\1cid:\3\4', html)
            email.attach_alternative(email_html, 'text/html')

            for image_fn in images:
                data = get_notification_template_resource(os.path.join(image_dir, image_fn))
                mime_type = get_predefined_mime_type(image_fn)
                try:
                    img = MIMEImage(data, _subtype=mime_type) if mime_type else MIMEImage(data)
                except TypeError as e:
                    raise RuntimeError(f"Couldn't guess MIME type for tile {image_fn}") from e
                img.add_header('Content-Id', '<' + image_fn + '>')
                img.add_header("Content-Disposition", "inline", filename=image_fn)
                email.attach(img)

        email.send(fail_silently=False)
    except Exception as caused_by:
        log.error(f'Unable to send email to user "{dst_user.get_full_name()}" (#{dst_user.pk})',
                  exc_info=caused_by)