django.core.mail.EmailMultiAlternatives - python examples

Here are the examples of the python api django.core.mail.EmailMultiAlternatives taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

102 Examples 7

3 View Complete Implementation : helper.py
Copyright MIT License
Author : pythonkr
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_satLE,
        text,
        settings.EMAIL_SENDER,
        [token.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False)

3 View Complete Implementation : receivers.py
Copyright GNU Affero General Public License v3.0
Author : sebst
@receiver(post_save)
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', '[email protected]', 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()

3 View Complete Implementation : mailer.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
def send_mail(subject, message, to_emails, from_email=None, reply_to_email=None, html_message=None, attachments=None):
    to_emails = [to_emails] if isinstance(to_emails, str) else to_emails
    ok_mails = filter_whitelist_emails(to_emails)
    from_email = from_email or Config.info_email()
    if len(ok_mails) > 0:
        kwargs = {'bcc': ok_mails}
        if reply_to_email is not None:
            kwargs['reply_to'] = [reply_to_email]
        msg = EmailMultiAlternatives(subject, message, from_email, **kwargs)
        if html_message is not None:
            msg.attach_alternative(html_message, 'text/html')
        if attachments is None:
            attachments = []
        for attachment in attachments:
            msg.attach(attachment.name, attachment.read())
        print(('Mail sent to ' + ', '.join(ok_mails) + (', on whitelist' if settings.DEBUG else '')))
        mailer = import_string(Config.default_mailer())
        mailer.send(msg)

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : pablotrinidad
@task(name='send_confirmation_email', max_retries=3)
def send_confirmation_email(user_pk):
    """Send account verification link to given user."""
    user = User.objects.get(pk=user_pk)
    verification_token = gen_verification_token(user)
    subject = 'Welcome @{}! Verify your account to start using Comparte Ride'.format(user.username)
    from_email = 'Comparte Ride <[email protected]>'
    content = render_to_string(
        'emails/users/account_verification.html',
        {'token': verification_token, 'user': user}
    )
    msg = EmailMultiAlternatives(subject, content, from_email, [user.email])
    msg.attach_alternative(content, "text/html")
    msg.send()

3 View Complete Implementation : mail.py
Copyright MIT License
Author : wise-team
def send_validation(strategy, backend, code, partial_token):
    url = '{0}?verification_code={1}&partial_token={2}'.format(
        reverse('social:complete', args=(backend.name,)),
        code.code,
        partial_token
    )
    url = strategy.request.build_absolute_uri(url)
    msg = EmailMultiAlternatives(
        subject='{0} Validate your account'.format(settings.EMAIL_SUBJECT_PREFIX),
        body='Validate your account {0}'.format(url),
        from_email=settings.VALIDATION_EMAIL_SENDER,
        to=[code.email],
    )
    msg.esp_extra = {"sender_domain": settings.EMAIL_SENDER_DOMAIN}
    msg.send()

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : geekwolf
def exec_send(content_id, email_list):

    data = collections.defaultdict(dict)

    from_email = settings.DEFAULT_FROM_EMAIL
    text_content = '这是一封重要的邮件.'

    content = Content.objects.select_related().get(id=content_id)
    data['content'] = content
    data['domain'] = settings.EMAIL_DOMAIN_LINK
    subject = '【故障报告】' + str(content.satle)
    time_count(content, content.start_time, content.end_time)

    msg_html = render_to_string('mail/detail_template.html', data)
    # send_mail('Subject here', 'Here is the message.', settings.DEFAULT_FROM_EMAIL,email_list, fail_silently=False)
    msg = EmailMultiAlternatives(subject, text_content, from_email, email_list)
    msg.attach_alternative(msg_html, "text/html")
    msg.send()

3 View Complete Implementation : forms.py
Copyright MIT License
Author : rizwansoaib
    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()

3 View Complete Implementation : utils.py
Copyright MIT License
Author : coogger
def send_mail(subject, template_name, context, to):
    html_content = render_to_string(template_name, context)
    text_content = strip_tags(html_content)
    for to in [user.email for user in to if user.userprofile.email_permission]:
        msg = EmailMultiAlternatives(
            subject, text_content, settings.EMAIL_HOST_USER, [to]
        )
        msg.attach_alternative(html_content, "text/html")
        msg.send()

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : whitesmith
def send_email(user, subject, template):
    content = render_to_string(template, context={"user": user})
    email = EmailMultiAlternatives(subject, content,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [user.email])
    email.send()

3 View Complete Implementation : email.py
Copyright GNU General Public License v3.0
Author : mapeveri
    def run(self):
        # Check if the email smtp is configurated
        if (settings.EMAIL_MUSS and settings.EMAIL_HOST
                and settings.EMAIL_HOST_PastWORD):
            msg = EmailMultiAlternatives(
                self.subject, self.body, self.from_email, self.recipient_list
            )
            if self.html:
                msg.attach_alternative(self.html, "text/html")
            msg.send(self.fail_silently)

3 View Complete Implementation : utils.py
Copyright MIT License
Author : opennode
def send_mail_with_attachment(subject, body, to, from_email=None, html_message=None,
                              filename=None, attachment=None, content_type='text/plain'):
    from_email = from_email or settings.DEFAULT_FROM_EMAIL
    email = EmailMultiAlternatives(
        subject=subject,
        body=body,
        to=to,
        from_email=from_email
    )

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

    if filename:
        email.attach(filename, attachment, content_type)
    return email.send()

3 View Complete Implementation : mails.py
Copyright GNU General Public License v3.0
Author : xiongjungit
def send_notice_mail(email,data):
    try:
        subject = data['notice_satle']
        text_content = data['notice_body']+'访问地址为:'+url+data['notice_url']
        html_content = "<p>"+data['notice_body']+",<a href='"+url+data['notice_url']+"'><a>点我访问</a></p>"
        msg = EmailMultiAlternatives(subject,text_content,DEFAULT_FROM_EMAIL,[email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        return True
    except:
        return False

3 View Complete Implementation : email.py
Copyright MIT License
Author : F0RE1GNERS
def send_mail_with_bcc(subject, html_message, recipient_list, fail_silently=False):
  def divide_group(lst, k):
    return [lst[i:i + k] for i in range(0, len(lst), k)]

  for grp in divide_group(recipient_list, 100):
    try:
      connection = get_connection(
        username=None,
        pastword=None,
        fail_silently=fail_silently,
      )
      mail = EmailMultiAlternatives(subject, bcc=grp, connection=connection)
      mail.attach_alternative(html_message, 'text/html')
      mail.send()
    except:
      traceback.print_exc()
    time.sleep(30)

3 View Complete Implementation : mail.py
Copyright MIT License
Author : pik-software
    def create_email(self) -> EmailMultiAlternatives:
        email = EmailMultiAlternatives(
            subject=self.get_email_subject(),
            body=self.get_plain_email_body(),
            from_email=self._email_from,
            to=self._emails_to, cc=self._emails_cc, bcc=self._emails_bcc)

        html_body = self.get_html_email_body()
        if html_body:
            email.attach_alternative(html_body, 'text/html')

        if self._files:
            for file_wrapper in self._files:
                email.attach(
                    filename=file_wrapper.filename,
                    content=file_wrapper.content,
                    mimetype=file_wrapper.mimetype)

        return email

3 View Complete Implementation : email.py
Copyright MIT License
Author : diegojromerolopez
def warn_administrators(subject, message):
    email_subject = u"[Djanban] [Warning] {0}".format(subject)
    report_recipients = ReportRecipient.objects.filter(is_active=True, send_errors=True)
    for report_recipient in report_recipients:
        email_message = EmailMultiAlternatives(email_subject, message, settings.EMAIL_HOST_USER,
                                               [report_recipient.email])
        email_message.send()

3 View Complete Implementation : helpers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
def send_confirmation_email(request, signature):
    pesation = signature.pesation
    url = request.build_absolute_uri("/pesation/{}/confirm/{}".format(pesation.id, signature.confirmation_hash))
    html_message = render_to_string("pesation/confirmation_email.html", {'firstname': signature.first_name, 'url': url})
    message = strip_tags(html_message)
    with get_connection() as connection:
        msg = EmailMultiAlternatives(_("Confirm your signature to our pesation"),
                           message, to=[signature.email], connection=connection,
                           reply_to=[pesation.confirmation_email_reply])
        msg.attach_alternative(html_message, "text/html")
        msg.send(fail_silently=False)

3 View Complete Implementation : notify.py
Copyright MIT License
Author : ilavender
def register_email(message):
    
    register_email_plaintext = get_template('registration/email_register.txt')
    register_email_htmly     = get_template('registration/email_register.html')
    
    send_to = message['register_user_email']
    username = message['register_user_name']
    registration_link = message['registration_link']
    subject, from_email, to = message['subject'], message['from_email'], message['to_email']
    text_content = register_email_plaintext.render({ 'username': username, 'registration_link': registration_link })
    html_content = register_email_htmly.render(d)
    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

3 View Complete Implementation : receivers.py
Copyright GNU Affero General Public License v3.0
Author : sebst
@receiver(post_save)
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), '[email protected]', 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()

3 View Complete Implementation : utils.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : egorsmkv
def send_mail(to, template, context):
    html_content = render_to_string(f'accounts/emails/{template}.html', context)
    text_content = render_to_string(f'accounts/emails/{template}.txt', context)

    msg = EmailMultiAlternatives(context['subject'], text_content, settings.DEFAULT_FROM_EMAIL, [to])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()

3 View Complete Implementation : receivers.py
Copyright GNU Affero General Public License v3.0
Author : sebst
@receiver(post_save)
def send_pastword_reset_email(sender, instance, created, **kwargs):
    if created and isinstance(instance, PastwordResetRequest):
        subject, from_email, to = 'Reset pastword for your account on news.python.sc', '[email protected]', 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()

3 View Complete Implementation : tasks.py
Copyright GNU Lesser General Public License v3.0
Author : littlemo
@task(time_limit=settings.EMAIL_TIME_LIMIT)
def account_send_email_task(subject, bodies, from_email, email):
    if 'txt' in bodies:
        msg = EmailMultiAlternatives(
            subject,
            bodies['txt'],
            from_email,
            [email])
        if 'html' in bodies:
            msg.attach_alternative(bodies['html'], 'text/html')
    else:
        msg = EmailMessage(
            subject,
            bodies['html'],
            from_email,
            [email])
        msg.content_subtype = 'html'  # Main content is now text/html
    msg.send()
    log.info(_('发送账户邮件到: %s'), email)

3 View Complete Implementation : tasks.py
Copyright MIT License
Author : whitesmith
@shared_task
def send_email_notification(subject, body, email):
    email = EmailMultiAlternatives(subject, body,
                                   settings.DEFAULT_FROM_EMAIL,
                                   [email])
    email.send()

3 View Complete Implementation : payment_email.py
Copyright GNU General Public License v3.0
Author : evernote
    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()

3 View Complete Implementation : mails.py
Copyright GNU General Public License v3.0
Author : xiongjungit
def sendmails(email,data):
    '''
    data={'subject':'',
          'text_content',
          'html_content'}
    '''
    try:
        msg = EmailMultiAlternatives(data['subject'],data['text_content'],DEFAULT_FROM_EMAIL,[email])
        msg.attach_alternative(data['html_content'], "text/html")
        msg.send()
        return True
    except:
        return False

3 View Complete Implementation : misc.py
Copyright Apache License 2.0
Author : mxsasha
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', '<[email protected]>')
    logo_mime.add_header('Content-Disposition', 'attachment')

    message.attach(logo_mime)
    message.send()

3 View Complete Implementation : htmlmail.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def send_html_mail(subject, recipient, message, template='',
                   recipient_name='', sender_name='', sender=None,
                   CHARSET=CHARSET):
    html = render(message, template)
    msg = EmailMultiAlternatives(
        subject=subject,
        body=html,
        to=[named(recipient, recipient_name)],
        from_email=named(sender, sender_name),
    )
    msg.content_subtype = "html"
    msg.send()

3 View Complete Implementation : forms.py
Copyright MIT License
Author : bpgc-cte
    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()

3 View Complete Implementation : integration_test.py
Copyright MIT License
Author : datosgobar
def send_email(result: list, task: IntegrationTestTask):
    subject = u'[{}] API Series de Tiempo: Test de integración'.format(settings.ENV_TYPE)
    emails = IntegrationTestConfig.get_solo().recipients.values_list('email', flat=True)
    if not emails:
        task.log("No hay usuarios registrados para recibir los reportes del test. Mail no enviado.")
        return

    msg = "Errores en los datos de las series detectados. Ver el archivo adjunto"
    config = DynamicEmailConfiguration.get_solo()
    mail = EmailMultiAlternatives(subject, msg, from_email=config.from_email, to=emails)
    mail.attach('errors.csv', generate_errors_csv(result), 'text/csv')
    sent = mail.send()
    if not sent:
        task.log("Error mandando el reporte")

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : OkunaOrg
    def send_confirmation_email(self, user, new_email, confirm_email_token):
        mail_subject = _('Confirm your email for Openbook')
        text_content = render_to_string('openbook_auth/email/change_email.txt', {
            'name': user.profile.name,
            'confirmation_link': self.generate_confirmation_link(confirm_email_token)
        })

        html_content = render_to_string('openbook_auth/email/change_email.html', {
            'name': user.profile.name,
            'confirmation_link': self.generate_confirmation_link(confirm_email_token)
        })

        email = EmailMultiAlternatives(
            mail_subject, text_content, to=[new_email], from_email=settings.SERVICE_EMAIL_ADDRESS)
        email.attach_alternative(html_content, 'text/html')
        email.send()

0 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def post(self, request):
        showform = True
        confirmation_message = ""
        postdata = request.POST.copy()
        postdata["ts"] = int(time.time())
        form = ArchesUserCreationForm(postdata, enable_captcha=settings.ENABLE_CAPTCHA)

        if form.is_valid():
            AES = AESCipher(settings.SECRET_KEY)
            userinfo = JSONSerializer().serialize(form.cleaned_data)
            encrypted_userinfo = AES.encrypt(userinfo)
            url_encrypted_userinfo = urlencode({"link": encrypted_userinfo})

            admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
            email_context = {
                "button_text": _("Signup for Arches"),
                "link": request.build_absolute_uri(reverse("confirm_signup") + "?" + url_encrypted_userinfo),
                "greeting": _(
                    "Thanks for your interest in Arches. Click on link below \
                    to confirm your email address! Use your email address to login."
                ),
                "closing": _(
                    "This link expires in 24 hours.  If you can't get to it before then, \
                    don't worry, you can always try again with the same email address."
                ),
            }

            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.
            msg = EmailMultiAlternatives(_("Welcome to Arches!"), text_content, admin_email, [form.cleaned_data["email"]])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

            confirmation_message = _(
                "An email has been sent to <br><strong>%s</strong><br> with a link to activate your account" % form.cleaned_data["email"]
            )
            showform = False

        return render(
            request,
            "signup.htm",
            {
                "enable_captcha": settings.ENABLE_CAPTCHA,
                "form": form,
                "postdata": postdata,
                "showform": showform,
                "confirmation_message": confirmation_message,
                "validation_help": validation.pastword_validators_help_texts(),
            },
        )

0 View Complete Implementation : mobile_survey.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    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()

0 View Complete Implementation : mobile_survey.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def notify_mobile_survey_end(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": _(
                "Hi!  The Mobile Survey you were part of has ended or is temporarily suspended. \
                Please permform a final sync of your local dataset as soon as possible."
            ),
            "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(
                _("There's been a change to an {app_name} Survey that you're part of!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send()

0 View Complete Implementation : lib.py
Copyright MIT License
Author : Arx-Game
def send_templated_mail(template_name, email_context, recipients, sender=None, bcc=None, fail_silently=False, files=None):
    """
    send_templated_mail() is a warpper around Django's e-mail routines that
    allows us to easily send multipart (text/plain & text/html) e-mails using
    templates that are stored in the database. This lets the admin provide
    both a text and a HTML template for each message.

    template_name is the slug of the template to use for this message (see
        models.EmailTemplate)

    email_context is a dictionary to be used when rendering the template

    recipients can be either a string, eg '[email protected]', or a list of strings.

    sender should contain a string, eg 'My Site <[email protected]>'. If you leave it
        blank, it'll use settings.DEFAULT_FROM_EMAIL as a fallback.

    bcc is an optional list of addresses that will receive this message as a
        blind carbon copy.

    fail_silently is pasted to Django's mail routine. Set to 'True' to ignore
        any errors at send time.

    files can be a list of tuple. Each tuple should be a filename to attach, 
        along with the File objects to be read. files can be blank.

    """
    from django.conf import settings
    from django.core.mail import EmailMultiAlternatives
    from django.template import engines

    from web.helpdesk.models import EmailTemplate
    from web.helpdesk.settings import HELPDESK_EMAIL_SUBJECT_TEMPLATE
    import os

    context = dict(email_context)

    if hasattr(context['queue'], 'locale'):
        locale = getattr(context['queue'], 'locale', '')
    else:
        locale = context['queue'].get('locale', 'en')
    if not locale:
        locale = 'en'

    t = None
    try:
        t = EmailTemplate.objects.get(template_name__iexact=template_name, locale=locale)
    except EmailTemplate.DoesNotExist:
        past

    if not t:
        try:
            t = EmailTemplate.objects.get(template_name__iexact=template_name, locale__isnull=True)
        except EmailTemplate.DoesNotExist:
            from evennia.utils.logger import log_warn
            log_warn('template "%s" does not exist, no mail sent' % template_name)
            return  # just ignore if template doesn't exist

    if not sender:
        sender = settings.DEFAULT_FROM_EMAIL

    footer_file = os.path.join('helpdesk', locale, 'email_text_footer.txt')

    text_part = engines['django'].from_string(
        "%s{%% include '%s' %%}" % (t.plain_text, footer_file)
        ).render(context)

    email_html_base_file = os.path.join('helpdesk', locale, 'email_html_base.html')

    ''' keep new lines in html emails '''
    from django.utils.safestring import mark_safe

    if context.has_key('comment'):
        html_txt = context['comment']
        html_txt = html_txt.replace('\r\n', '<br>')
        context['comment'] = mark_safe(html_txt)

    html_part = engines['django'].from_string(
        "{%% extends '%s' %%}{%% block satle %%}%s{%% endblock %%}{%% block content %%}%s{%% endblock %%}" % (email_html_base_file, t.heading, t.html)
        ).render(context)

    subject_part = engines['django'].from_string(
        HELPDESK_EMAIL_SUBJECT_TEMPLATE % {
            "subject": t.subject,
        }).render(context)

    if isinstance(recipients,(str,unicode)):
        if recipients.find(','):
            recipients = recipients.split(',')
    elif type(recipients) != list:
        recipients = [recipients,]

    msg = EmailMultiAlternatives(   subject_part.replace('\n', '').replace('\r', ''),
                                    text_part,
                                    sender,
                                    recipients,
                                    bcc=bcc)
    msg.attach_alternative(html_part, "text/html")

    if files:
        for attachment in files:
            file_to_attach = attachment[1]
            file_to_attach.open()
            msg.attach(filename=attachment[0], content=file_to_attach.read())
            file_to_attach.close()

    return msg.send(fail_silently)

0 View Complete Implementation : campaign.py
Copyright GNU General Public License v3.0
Author : atexio
    def _make_email(self, target):
        """Prepare email for target"""
        # get values
        email_template = self.campaign.email_template
        landing_page = email_template.landing_page
        target_email = copy.deepcopy(email_template)
        smtp_connection = self._cache_smtp_connection

        # update cache (for helpers clast function)
        self._cache_current_target = target

        # prepare / build attachments files
        attachments = []
        for attachment in email_template.attachments.all():
            # build custom attachment
            if attachment.buildable:
                attachment_file = attachment.build(self._add_tracker(
                    TRACKER_ATTACHMENT_EXECUTED,
                    '%s: not executed' % attachment.name,
                    0
                ))

            # static file on attachment
            else:
                attachment_file = attachment.file

            attachments.append({
                'filename': attachment.attachment_name,
                'content': attachment_file.read()
            })

        # Signal for external app
        send_email.send(
            attachments=attachments, campaign=self.campaign,
            email_template=target_email, sender=self,
            target=target, smtp_connection=smtp_connection
        )

        # Add email open tracker in email
        if email_template.has_open_tracker:
            # convert txt to html if empty
            target_email.html_content = self._make_email_html(target_email)

            # add open tracker to html
            tracker = self._add_tracker(TRACKER_EMAIL_OPEN, 'not opened', 0)
            target_email.html_content = self._add_email_traker(target_email,
                                                               tracker)

        # Create landing page tracker
        if landing_page:
            self._add_tracker(TRACKER_LANDING_PAGE_OPEN, 'not opened', 0)

            # add post intecept traker
            if POST_TRACKER_ID in landing_page.html:
                self._add_tracker(TRACKER_LANDING_PAGE_POST, 'no', 0)

        # Create django email object
        mail = EmailMultiAlternatives(
            subject=self._replace_vars(target_email.email_subject),
            body=self._replace_vars(target_email.text_content),
            from_email=target_email.from_email,
            to=[target.email], connection=smtp_connection
        )

        # Add html content in email
        if target_email.html_content:
            mail.attach_alternative(
                self._replace_vars(target_email.html_content),
                'text/html'
            )

        # Add all attachments in email object
        for attachment in attachments:
            mail.attach(**attachment)

        return mail

0 View Complete Implementation : outgoing.py
Copyright MIT License
Author : Bearle
    def prepare_email_message(self):
        """
        Returns a django ``EmailMessage`` or ``EmailMultiAlternatives`` object,
        depending on whether html_message is empty.
        """
        message = self.message
        if self.template is not None:
            _context = self._get_context()
            subject = Template(self.template.subject).render(_context)
            html_message = self.template.render_html_text(_context)
        else:
            subject = self.subject
            html_message = self.html_message

        connection = connections[self.backend_alias or 'default']

        if html_message:
            msg = EmailMultiAlternatives(
                subject=subject, body=message, from_email=self.from_email,
                to=self.to, bcc=self.bcc, cc=self.cc,
                headers=self.headers, connection=connection)
            msg.attach_alternative(html_message, "text/html")
        else:
            msg = EmailMessage(
                subject=subject, body=message, from_email=self.from_email,
                to=self.to, bcc=self.bcc, cc=self.cc,
                headers=self.headers, connection=connection)

        for attachment in self.attachments.all():
            msg.attach(attachment.name, attachment.file.read(), mimetype=attachment.mimetype or None)
            attachment.file.close()

        self._cached_email_message = msg
        return msg

0 View Complete Implementation : test_integration_imap.py
Copyright MIT License
Author : Bearle
    def test_get_imap_message(self):
        text_content = 'This is some content'
        msg = EmailMultiAlternatives(
            self.arbitrary_identifier,
            text_content,
            self.test_from_email,
            [
                self.test_account,
            ]
        )
        msg.send()

        messages = self._get_new_messages(
            self.mailbox,
            condition=lambda m: m['subject'] == self.arbitrary_identifier
        )

        self.astertEqual(1, len(messages))
        self.astertEqual(messages[0].subject, self.arbitrary_identifier)
        self.astertEqual(messages[0].text, text_content)

0 View Complete Implementation : notify_email.py
Copyright GNU Affero General Public License v3.0
Author : BirkbeckCTP
def send_email(subject, to, html, journal, request, bcc=None, cc=None, attachment=None, replyto=None):

    if journal:
        from_email = setting_handler.get_setting('email', 'from_address', journal).value
        subject_setting = setting_handler.get_email_subject_setting('email_subject', subject, journal)
        subject = "[{0}] {1}".format(journal.code, subject_setting if subject_setting else subject)
        html = "{0}<br />{1}".format(html, journal.name)
    else:
        from_email = request.press.main_contact

    if isinstance(to, str):
        if settings.DUMMY_EMAIL_DOMAIN in to:
            to = []
        else:
            to = [to]
    elif isinstance(to, Iterable):
        to = [email for email in to if not settings.DUMMY_EMAIL_DOMAIN in email]

    if request and request.user and not request.user.is_anonymous():
        reply_to = [request.user.email]
        full_from_string = "{0} <{1}>".format(request.user.full_name(), from_email)
    else:
        reply_to = []
        if request:
            full_from_string = "{0} <{1}>".format(
                    sanitize_from(request.site_type.name),
                    from_email
            )
        else:
            full_from_string = from_email

    if replyto:
        reply_to = replyto

    msg = EmailMultiAlternatives(subject, strip_tags(html), full_from_string, to, bcc=bcc, cc=cc, reply_to=reply_to)
    msg.attach_alternative(html, "text/html")

    if request and request.FILES and request.FILES.getlist('attachment'):
        for file in request.FILES.getlist('attachment'):
            file.open()
            msg.attach(file.name, file.read(), file.content_type)
            file.close()

    return msg.send()

0 View Complete Implementation : models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : BulletTrainHQ
    def send_invite_mail(self):
        context = {
            "org_name": self.organisation.name,
            "invite_url": self.get_invite_uri()
        }

        html_template = get_template('users/invite_to_org.html')
        plaintext_template = get_template('users/invite_to_org.txt')

        if self.invited_by:
            invited_by_name = self.invited_by.get_full_name()
            if not invited_by_name:
                invited_by_name = "A user"
            subject = settings.EMAIL_CONFIGURATION.get('INVITE_SUBJECT_WITH_NAME') % (
                invited_by_name, self.organisation.name
            )
        else:
            subject = settings.EMAIL_CONFIGURATION.get('INVITE_SUBJECT_WITHOUT_NAME') % \
                      self.organisation.name

        to = self.email

        text_content = plaintext_template.render(context)
        html_content = html_template.render(context)
        msg = EmailMultiAlternatives(
            subject,
            text_content,
            settings.EMAIL_CONFIGURATION.get('INVITE_FROM_EMAIL'),
            [to]
        )
        msg.attach_alternative(html_content, "text/html")
        msg.send()

0 View Complete Implementation : webhooks.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : BulletTrainHQ
def send_failure_email(environment, data, status_code):
        template_data = {
            "project_name": environment.project.name,
            "environment_name": environment.name,
            "status_code": status_code,
            "data": json.dumps(
                data,
                sort_keys=True,
                indent=2,
                cls=DjangoJSONEncoder
            )
        }

        text_template = get_template('features/webhook_failure.txt')
        text_content = text_template.render(template_data)
        subject = "Bullet Train Webhook Failure"
        msg = EmailMultiAlternatives(
            subject,
            text_content,
            settings.EMAIL_CONFIGURATION.get('INVITE_FROM_EMAIL'),
            [environment.project.organisation.webhook_notification_email]
        )
        msg.content_subtype = "plain"
        msg.send()

0 View Complete Implementation : send.py
Copyright Apache License 2.0
Author : byro
def mail_send_task(
    to: str,
    subject: str,
    body: str,
    sender: str,
    cc: list = None,
    bcc: list = None,
    headers: dict = None,
    attachments: list = None,
):
    email = EmailMultiAlternatives(
        subject, body, sender, to=to, cc=cc, bcc=bcc, headers=headers
    )
    if attachments:
        from byro.docameents.models import Docameent

        for attachment in attachments:
            email.attach_file(Docameent.objects.get(pk=attachment).docameent.path)
    backend = get_connection(fail_silently=False)

    try:
        backend.send_messages([email])
    except Exception:
        logger.exception("Error sending email")
        raise SendMailException("Failed to send an email to {}.".format(to))

0 View Complete Implementation : mail.py
Copyright Apache License 2.0
Author : chrisjrn
def __send_email__(template_prefix, to, kind, **kwargs):

    current_site = Site.objects.get_current()

    ctx = {
        "current_site": current_site,
        "STATIC_URL": settings.STATIC_URL,
    }
    ctx.update(kwargs.get("context", {}))
    subject_template = os.path.join(template_prefix, "%s/subject.txt" % kind)
    message_template = os.path.join(template_prefix, "%s/message.html" % kind)
    subject = "[%s] %s" % (
        current_site.name,
        render_to_string(subject_template, ctx).strip()
    )

    message_html = render_to_string(message_template, ctx)
    message_plaintext = strip_tags(message_html)

    from_email = settings.DEFAULT_FROM_EMAIL

    try:
        bcc_email = settings.ENVELOPE_BCC_LIST
    except AttributeError:
        bcc_email = None

    email = EmailMultiAlternatives(
        subject,
        message_plaintext,
        from_email,
        to,
        bcc=bcc_email,
    )
    email.attach_alternative(message_html, "text/html")
    email.send()

0 View Complete Implementation : tasks.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
@shared_task(name="send_mast_email")
def send_mast_email(subject="", contexts=None):
    """ Construct and send a multipart/alternative email """

    if not subject or not contexts:
        return "Insufficient values"

    # Manually open connection to the SMTP server specified in settings.py
    connection = get_connection() # uses SMTP server specified in settings.py
    connection.open()

    messages = []
    for email_context in contexts:
        msg_plain = render_to_string('email/base_text_template.txt', email_context)
        msg_html = render_to_string('email/base_email_template.html', email_context)

        msg = EmailMultiAlternatives(
            subject, #Subject Line
            msg_plain, # text/plain Content
            settings.EMAIL_HOST_USER, # Sender Email (default: [email protected])
            email_context['recipient'], # Target Email
            connection=connection,
        )
        msg.attach_alternative(msg_html, "text/html")# text/html Content
        messages.append(msg)

    connection.send_messages(messages)

    return "success"

0 View Complete Implementation : notifications.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
def email_output_delta(output_delta: OutputDelta, updated_at: datetime.datetime):
    user = output_delta.user

    ctx = {
        **get_i18n_context(user=user),
        "user_name": user_display(user),
        "module_name": output_delta.module_name,
        "workflow_name": output_delta.workflow_name,
        "workflow_url": output_delta.workflow_url,
        "date": updated_at.strftime("%b %-d, %Y at %-I:%M %p"),
    }
    subject = render_to_string("notifications/new_data_version_subject.txt", ctx)
    subject = "".join(subject.splitlines())
    message = render_to_string("notifications/new_data_version.txt", ctx)
    mail = EmailMultiAlternatives(
        subject=subject,
        body=message,
        from_email=settings.DEFAULT_FROM_EMAIL,
        to=[user.email],
    )
    mail.attach_alternative(message, "text/html")
    mail.send()

0 View Complete Implementation : email.py
Copyright MIT License
Author : CodeForPoznan
def send_mail(request, templates_name, recipient_list, context=None,
              send_copy_to_admin=True):
    """Proxy for sending emails."""
    fail_silently = FAIL_SILENTLY
    auth_user = AUTH_USER
    auth_pastword = AUTH_PastWORD
    connection = CONNECTION

    context = context or {}
    context.update({
        'ANGULAR_ROOT': settings.ANGULAR_ROOT,
        'protocol': 'https' if request.is_secure() else 'http',
        'domain': get_current_site(request).domain,
    })
    text_template = get_template('emails/{}.txt'.format(templates_name))
    html_template = get_template('emails/{}.html'.format(templates_name))

    connection = connection or get_connection(
        username=auth_user,
        pastword=auth_pastword,
        fail_silently=fail_silently
    )
    if send_copy_to_admin:
        bcc = list(get_administrators_emails().values())
        # required, if omitted then no emails from BCC are send
        headers = {'bcc': ','.join(bcc)}
    else:
        bcc = []
        headers = None

    email = EmailMultiAlternatives(
        SUBJECTS[templates_name],
        text_template.render(context),
        FROM_ADDRESS,
        recipient_list,
        bcc,
        connection=connection,
        headers=headers
    )
    email.attach_alternative(html_template.render(context), 'text/html')

    return email.send()

0 View Complete Implementation : views.py
Copyright MIT License
Author : diegojromerolopez
@login_required
def send_daily_spent_times(request):
    if request.method != "POST":
        raise Http404

    current_user = request.user
    current_user_boards = get_user_boards(current_user)

    recipient_email = request.POST.get("email")
    if not re.match(r"[^@][email protected][^@]+", recipient_email):
        return JsonResponse({"message": "Invalid email"})

    daily_spent_times_filter = {}

    # Start date
    start_date_str = request.POST.get("start_date")
    start_date = None
    if start_date_str:
        try:
            start_date = datetime.datetime.strptime(start_date_str, "%Y-%m-%d")
            daily_spent_times_filter["date__gte"] = start_date
        except ValueError:
            start_date = None

    # End date
    end_date_str = request.POST.get("end_date")
    end_date = None
    if end_date_str:
        try:
            end_date = datetime.datetime.strptime(end_date_str, "%Y-%m-%d")
            daily_spent_times_filter["date__lte"] = end_date
        except ValueError:
            end_date = None

    # Week
    week = request.POST.get('week') if request.POST.get('week') and request.POST.get('week') > 0 else None
    if week:
        daily_spent_times_filter["week"] = week

    # Default filter is None
    multiboard = None
    label = None
    board = None

    # Filter spent time by multiboard
    multiboard_str = request.POST.get("multiboard")
    if multiboard_str and hasattr(current_user, "member") and\
            current_user.member.multiboards.filter(id=multiboard_str).exists():
        multiboard = current_user.member.multiboards.get(id=multiboard_str)
        daily_spent_times_filter["board__multiboards"] = multiboard
    # Filter spent time by label o board
    else:
        # Label
        label_str = request.POST.get("label")
        matches = re.match(r"all_from_board_(?P<board_id>\d+)", label_str)
        if matches and current_user_boards.filter(id=matches.group("board_id")).exists():
            label = None
            board = current_user_boards.get(id=matches.group("board_id"))
            daily_spent_times_filter["board"] = board

        elif Label.objects.filter(id=label_str).exists():
            label = Label.objects.get(id=label_str)
            board = label.board
            daily_spent_times_filter["board"] = board
            daily_spent_times_filter["card__labels"] = label

    # Member
    member = None
    if user_is_member(current_user):
        current_user_members = Member.objects.filter(Q(boards__in=current_user_boards)|Q(id=current_user.member.id)).distinct()
    else:
        current_user_members = Member.objects.filter(boards__in=current_user_boards).distinct()
    if request.POST.get("member") and current_user_members.filter(id=request.POST.get("member")).exists():
        member = current_user_members.get(id=request.POST.get("member"))
        daily_spent_times_filter["member"] = member

    daily_spent_times = DailySpentTime.objects.filter(**daily_spent_times_filter)

    replacements = {
        "email": recipient_email,
        "daily_spent_times": daily_spent_times,
        "week": week,
        "start_date": start_date,
        "end_date": end_date,
        "label": label,
        "board": board,
        "multiboard": multiboard,
        "member": member
    }

    report_subject = get_template('daily_spent_times/emails/send_daily_spent_times_subject.txt').render(replacements)

    txt_message = get_template("daily_spent_times/emails/send_daily_spent_times.txt").render(replacements)
    html_message = get_template("daily_spent_times/emails/send_daily_spent_times.html").render(replacements)

    csv_report = get_template('daily_spent_times/csv.txt').render({"spent_times": daily_spent_times})
    csv_file_name = "custom_report_for_{0}.csv".format(recipient_email)

    try:
        message = EmailMultiAlternatives(report_subject, txt_message, settings.EMAIL_HOST_USER, [recipient_email])
        message.attach_alternative(html_message, "text/html")
        message.attach(csv_file_name, csv_report, 'text/csv')
        message.send()

        if request.GET.get("ajax"):
            return JsonResponse({"message": "Spent times sent successfully"})
        return render(request, "daily_spent_times/send_daily_spent_times_ok.html", replacements)
    except Exception:
        if request.GET.get("ajax"):
            return JsonResponse({"message": "Error when sending data"}, status=500)
        return render(request, "daily_spent_times/send_daily_spent_times_error.html", replacements)

0 View Complete Implementation : daily_development_report.py
Copyright MIT License
Author : diegojromerolopez
    @staticmethod
    def send_daily_development_report(date, developer_member, daily_spent_times):

        try:
            developer_mood = developer_member.daily_member_moods.get(date=date)
        except DailyMemberMood.DoesNotExist:
            developer_mood = None

        replacements = {
            "date": date,
            "developer": developer_member,
            "developer_mood": developer_mood,
            "developer_daily_spent_times": daily_spent_times.filter(member=developer_member)
        }

        txt_message = get_template('reporter/emails/daily_development_report.txt').render(replacements)
        html_message = get_template('reporter/emails/daily_development_report.html').render(replacements)

        subject = "[Djanban][DevReports] Daily development report of {0}".format(date.strftime("%Y-%m-%d"))

        csv_report = get_template('daily_spent_times/csv.txt').render({"spent_times": daily_spent_times})

        message = EmailMultiAlternatives(subject, txt_message, settings.EMAIL_HOST_USER, [developer_member.user.email])
        message.attach_alternative(html_message, "text/html")
        message.attach('spent_times-for-day-{0}.csv'.format(date.strftime("%Y-%m-%d")), csv_report, 'text/csv')
        message.send()

0 View Complete Implementation : report_command.py
Copyright MIT License
Author : diegojromerolopez
    def send_report(self, daily_spent_times, report_recipient, subject,
                    txt_template_path, html_template_path, csv_file_name):

        week = get_iso_week_of_year(self.date)
        start_week_date = start_of_week_of_year(week, self.date.year)
        end_week_date = end_of_week_of_year(week, self.date.year)
        replacements = {
            "start_week_date": start_week_date,
            "end_week_date": end_week_date,
            "date": self.date,
            "day": self.date.day,
            "week": week,
            "month": self.date.month,
            "year": self.date.year,
            "report_recipient": report_recipient,
            "boards": report_recipient.boards.all(),
            "developer_members": Member.objects.filter(is_developer=True, on_holidays=False).order_by("trello_member_profile__username"),
            "daily_spent_times": daily_spent_times,
        }

        txt_message = get_template(txt_template_path).render(replacements)
        html_message = get_template(html_template_path).render(replacements)

        csv_report = get_template('daily_spent_times/csv.txt').render({"spent_times": daily_spent_times})

        message = EmailMultiAlternatives(subject, txt_message, settings.EMAIL_HOST_USER, [report_recipient.email])
        message.attach_alternative(html_message, "text/html")
        message.attach(csv_file_name, csv_report, 'text/csv')
        message.send()

0 View Complete Implementation : notify_work_hours_package_completions.py
Copyright MIT License
Author : diegojromerolopez
    def send_package_notification(self, package, percentage):
        # Recipient emails
        # Deletion of repeated emails using a hash
        emails = {member.user.email:True for member in package.members.exclude(user__email="")}
        if package.notification_email:
            emails[package.notification_email] = True
        emails = emails.keys()

        daily_spent_times = package.daily_spent_times

        # Preparation of email templates
        replacements = {
            "work_hours_package": package,
            "completion_datetime": package.completion_date,
            "daily_spent_times": daily_spent_times,
            "percentage": percentage
        }
        txt_message = get_template('work_hours_packages/emails/completion_notification.txt')\
            .render(replacements)
        html_message = get_template('work_hours_packages/emails/completion_notification.html')\
            .render(replacements)

        subject = "[Djanban][WorkHoursPackage] Work hours package {0} at {1}".format(package.name, percentage)

        csv_report = get_template('daily_spent_times/csv.txt').render({"spent_times": daily_spent_times})

        try:
            # Send the email
            message = EmailMultiAlternatives(subject, txt_message, settings.EMAIL_HOST_USER,
                                             bcc=emails)
            message.attach_alternative(html_message, "text/html")
            message.attach('spent_times-for-{0}.csv'.format(package.name), csv_report, 'text/csv')
            message.send()
            # Mark this work hours package as notified
            package.mark_completion_notification_as_sent(percentage)
        except Exception:
            self.stdout.write(
                self.style.ERROR(u"Notifications of {0} could not be sent successfully".format(package.name))
            )

0 View Complete Implementation : email.py
Copyright MIT License
Author : abelardopardo
def _create_single_message(
    msg_body_sbj_to: List[str],
    track_str: str,
    from_email: str,
    cc_email_list: List[str],
    bcc_email_list: List[str],
) -> Union[EmailMessage, EmailMultiAlternatives]:
    """Create either an EmailMessage or EmailMultiAlternatives object.

    :param msg_body_sbj_to: List with body, subject, to
    :param track_str: String to add to track
    :param from_email: From email
    :param cc_email_list: CC list
    :param bcc_email_list: BCC list
    :return: Either EmailMessage or EmailMultiAlternatives
    """
    if settings.EMAIL_HTML_ONLY:
        # Message only has the HTML text
        msg = EmailMessage(
            msg_body_sbj_to[1],
            msg_body_sbj_to[0] + track_str,
            from_email,
            [msg_body_sbj_to[2]],
            bcc=bcc_email_list,
            cc=cc_email_list,
        )
        msg.content_subtype = 'html'
    else:
        # Get the plain text content and bundle it together with the HTML
        # in a message to be added to the list.
        msg = EmailMultiAlternatives(
            subject=html2text.html2text(msg_body_sbj_to[0]),
            body=msg_body_sbj_to[1],
            from_email=from_email,
            to=[msg_body_sbj_to[2]],
            bcc=bcc_email_list,
            cc=cc_email_list,
        )
        msg.attach_alternative(msg_body_sbj_to[0] + track_str, 'text/html')
    return msg

0 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
@receiver(post_save, sender=UserXNotification)
def send_email_on_save(sender, instance, **kwargs):
    """Checks if a notification type needs to send an email, does so if email server exists
    """

    if instance.notif.notiftype is not None and instance.isread is False:
        if UserXNotificationType.objects.filter(user=instance.recipient, notiftype=instance.notif.notiftype, emailnotify=False).exists():
            return False

        try:
            context = instance.notif.context.copy()
            text_content = render_to_string(instance.notif.notiftype.emailtemplate, context)
            html_template = get_template(instance.notif.notiftype.emailtemplate)
            html_content = html_template.render(context)
            if context["email"] == instance.recipient.email:
                email_to = instance.recipient.email
            else:
                email_to = context["email"]
            subject, from_email, to = instance.notif.notiftype.name, "[email protected]", email_to
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            if instance.notif.notiftype.webnotify is not True:
                instance.isread = True
                instance.save()
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.warn("Email Server not correctly set up. See settings to configure.")

    return False