Ejemplo n.º 1
0
def send_mail_with_logs(recipients: list, from_email: str, subject, template_name: str,
                        context: dict):
    try:
        if Site.objects.get_current().domain == '127.0.0.1:8000':
            new_email = '{0}@{1}'.format(DO_NOT_REPLY_USERNAME, 'example.com')
            msg = 'Changing FROM email for local development. Using {0} instead of {1}'
            LOGGER.info(msg=msg.format(new_email, from_email))
            from_email = new_email

        LOGGER.info('Setting up new email:')
        LOGGER.info(msg='SUBJECT: {0}'.format(subject))
        LOGGER.info(msg='TO: {0}'.format(recipients))
        LOGGER.info(msg='FROM: {0}'.format(from_email))
        LOGGER.info(msg='Rendering HTML email from {0}'.format(template_name))
        msg_html = render_to_string(template_name, context=context)
        LOGGER.info('Stripping tags from rendered HTML to create a plaintext email')
        msg_plain = html_to_text(msg_html)
        LOGGER.info('Sending...')
        send_mail(
            subject=subject,
            message=msg_plain,
            from_email=from_email,
            recipient_list=recipients,
            html_message=msg_html,
            fail_silently=False
        )
        num_recipients = len(recipients)
        if num_recipients == 1:
            LOGGER.info('1 email sent')
        else:
            LOGGER.info(msg='{0} emails sent'.format(num_recipients))
    except smtplib.SMTPException as exc:
        LOGGER.error(msg=('Error when sending email to user: {0}'.format(str(exc))))
 def test_whitespace_stripped(self):
     html = '\n'.join([
         '',
         '<html>',
         '    <div> Hello  </div>',
         '    ',
         '</html>',
     ])
     text = html_to_text(html)
     self.assertEqual(text, 'Hello')
 def test_empty_string(self):
     text = html_to_text('')
     self.assertEqual(text, '')
 def test_nested_tags(self):
     text = html_to_text('<div><div><p>Hello</p></div></div>')
     self.assertEqual(text, 'Hello')
 def test_simple_tag_removal(self):
     text = html_to_text('<h1>Hello</h1>')
     self.assertEqual(text, 'Hello')