utils.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:PythonGuru 作者: aronekob34 项目源码 文件源码
def send_mail(subject_template_name, email_template_name, to_email, context=None,
              html_email_template_name=None, from_email=settings.DEFAULT_FROM_EMAIL,
              bcc=None, connection=None):

    try:
        subject = loader.render_to_string(subject_template_name, context)
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        if not isinstance(to_email, list):
            to_email = [to_email]

        if settings.DEBUG and settings.LIVE_EMAIL:

            email_message = EmailMultiAlternatives(
                subject, body, from_email, [settings.RECIPIENT_TEST_EMAIL], connection=connection
            )

        else:

            email_message = EmailMultiAlternatives(
                subject, body, from_email, to_email, bcc, connection=connection
            )

        if settings.TEST_TEXT_EMAIL:
            email_message.send()

        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()

    except SMTPRecipientsRefused as e:
        logger.error(e)

    except Exception as e:
        message = 'Failed to send email to {}, Subject: {}, Exception: {}'.format(
            to_email, subject_template_name, e)
        logger.exception(message)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号