示例#1
0
def myView(request):
    try:
        backend = EmailBackend(
          host='EMAIL_HOST',
          # Port 587 recomended for SMTP
          port=587,
          username='******',
          password='******',
          use_tls=True
        )
        backend.open()
        subject = 'My subject'
        '''
          If you want html message can do:
          from django.template.loader import render_to_string
          message = render_to_string('template.html')
        '''
        message = 'Hi!'
        sender = '*****@*****.**'
        # List of recipients
        recipients = ['*****@*****.**']
        email = EmailMessage(subject, message, sender, recipients)
        email.content_subtype = "html"
        backend.send_messages([email])
        backend.close()
    except Exception,e:
        print(e)
        return render(request, "error.html")
示例#2
0
class MultipleSMTPEmailBackend(BaseEmailBackend):
    def __init__(self, host=None, fail_silently=False, **kwargs):
        super(MultipleSMTPEmailBackend, self).__init__(fail_silently=fail_silently)

        self.bulk = SMTPEmailBackend(host=settings.EMAIL_HOST['bulk']['host'],
                port=settings.EMAIL_HOST['bulk']['port'],
                fail_silently=fail_silently, **kwargs)
        self.transactional = SMTPEmailBackend(host=settings.EMAIL_HOST['transactional']['host'],
                port=settings.EMAIL_HOST['transactional']['port'],
                fail_silently=fail_silently, **kwargs)

    def open(self):
        return self.bulk.open() and self.transactional.open()

    def close(self):
        self.bulk.close()
        self.transactional.close()

    def split_messages(self, email_messages):
        """Split messages list to send in 2 groups regarding their from_email field."""
        bulk, transactional = [], []
        for message in email_messages:
            from_email = sanitize_address(message.from_email, message.encoding)
            if settings.BULK_EMAIL_DEFAULT_FROM_EMAIL in from_email:
                bulk.append(message)
            else:
                transactional.append(message)
        return bulk, transactional

    def send_messages(self, email_messages):
        bulk_messages, transactional_messages = self.split_messages(email_messages)

        return ((self.bulk.send_messages(bulk_messages) or 0)
                + (self.transactional.send_messages(transactional_messages) or 0))
示例#3
0
def test_smtp_connection(request):
    """ Tests smtp connection """
    mail_backend = EmailBackend(
        host=request.user.email_settings.smtp_host,
        port=request.user.email_settings.smtp_port,
        password=request.user.email_settings.smtp_password,
        username=request.user.email_settings.smtp_username,
        use_tls=True,
        timeout=10,
    )
    try:
        mail_backend.open()
        mail_backend.close()
        messages.success(
            request,
            _("SMTP settings are correct. Now you are using it for email sending"
              ),
        )
    except SMTPException:
        messages.warning(
            request,
            _("SMTP settings are not correct. Please provide correct credentials \
                and make sure that your smtp is running"),
        )
    return redirect("email_settings")
    def connect(self):
        """Connect the SMTP Server"""

        from django.core.mail.backends.smtp import EmailBackend

        smtp = EmailBackend(
            host=smart_str(self.host),
            port=int(self.port),
            username=smart_str(self.user),
            password=smart_str(self.password),
            use_tls=self.tls,
            use_ssl=self.ssl,
        )
        smtp.open()

        return smtp.connection
示例#5
0
 def clean(self):
     cleaned_data = super().clean()
     smtp_email_backend = EmailBackend(
         host=cleaned_data.get('smtp_host'),
         port=cleaned_data.get('smtp_port'),
         username=cleaned_data.get('smtp_username'),
         password=cleaned_data.get('smtp_password'),
         use_tls=cleaned_data.get('smtp_use_tls'),
         fail_silently=False,
         use_ssl=cleaned_data.get('smtp_use_ssl'),
         timeout=cleaned_data.get('smtp_timeout'),
         ssl_keyfile=cleaned_data.get('smtp_ssl_keyfile'),
         ssl_certfile=cleaned_data.get('smtp_ssl_certfile'))
     try:
         smtp_email_backend.open()
     except ConnectionRefusedError:
         raise ValidationError(_('Connection refused'),
                               code='connection_refused')
     except SMTPAuthenticationError as err:
         raise ValidationError(str(err), code='auth_error')
     return cleaned_data
示例#6
0
文件: views.py 项目: zsprn123/yunqu
def test_mail_connection(request):
    host = request.data.get('host', '')
    port = request.data.get('port', '')
    username = request.data.get('username', '')
    password = request.data.get('password', '')
    use_ssl = request.data.get('use_ssl', True)
    use_tls = request.data.get('use_tls', False)
    try:
        backend = EmailBackend(host=host,
                               port=port,
                               username=username,
                               password=password,
                               use_ssl=use_ssl,
                               use_tls=use_tls,
                               fail_silently=False)
        backend.open()
    except Exception as e:
        return Response({'error_message': '' + str(e)},
                        status=status.HTTP_400_BAD_REQUEST)

    return Response({'message': ''})
示例#7
0
 def clean(self):
     cleaned_data = super().clean()
     smtp_email_backend = EmailBackend(
         host=cleaned_data.get('smtp_host'),
         port=cleaned_data.get('smtp_port'),
         username=cleaned_data.get('smtp_username'),
         password=cleaned_data.get('smtp_password'),
         use_tls=cleaned_data.get('smtp_use_tls'),
         fail_silently=False,
         use_ssl=cleaned_data.get('smtp_use_ssl'),
         timeout=cleaned_data.get('smtp_timeout'),
         ssl_keyfile=cleaned_data.get('smtp_ssl_keyfile'),
         ssl_certfile=cleaned_data.get('smtp_ssl_certfile')
     )
     try:
         smtp_email_backend.open()
     except ConnectionRefusedError:
         raise ValidationError(_('Connection refused'), code='connection_refused')
     except SMTPAuthenticationError as err:
         raise ValidationError(str(err), code='auth_error')
     return cleaned_data