Python smtplib.SMTPResponseException() Examples

The following are 25 code examples of smtplib.SMTPResponseException(). 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 smtplib , or try the search function .
Example #1
Source File: test_email.py    From messages with MIT License 6 votes vote down vote up
def test_get_session_tls_raisesMessSendErr(get_email, mocker):
    """
    GIVEN an incorrect password in a valid Email object
    WHEN Email.get_session() is called
    THEN assert Exception is raised
    """
    get_tls_mock = mocker.patch.object(Email, '_get_tls')
    get_tls_mock.return_value.login.side_effect = SMTPResponseException(code=0, msg=b'')
    e = get_email
    e.port = 587
    with pytest.raises(MessageSendError):
        e._get_session()


##############################################################################
# TESTS: Email._get_ssl
############################################################################## 
Example #2
Source File: server.py    From zmail with MIT License 6 votes vote down vote up
def logout(self):
        if not self._login:
            self.log_exception('{} Logout before login!'.format(self.__repr__()))
            return

        if self.debug:
            self.log_access('logout')

        # Copied from smtplib.SMTP.__exit__
        # used for close connection.
        try:
            code, message = self.server.docmd("QUIT")
            if code != 221:
                raise smtplib.SMTPResponseException(code, message)
        except smtplib.SMTPServerDisconnected:
            pass
        finally:
            self.server.close()

        self._remove_server()

        self._login = False 
Example #3
Source File: views.py    From OnlineJudge with MIT License 6 votes vote down vote up
def post(self, request):
        if not SysOptions.smtp_config:
            return self.error("Please setup SMTP config at first")
        try:
            send_email(smtp_config=SysOptions.smtp_config,
                       from_name=SysOptions.website_name_shortcut,
                       to_name=request.user.username,
                       to_email=request.data["email"],
                       subject="You have successfully configured SMTP",
                       content="You have successfully configured SMTP")
        except smtplib.SMTPResponseException as e:
            # guess error message encoding
            msg = b"Failed to send email"
            try:
                msg = e.smtp_error
                # qq mail
                msg = msg.decode("gbk")
            except Exception:
                msg = msg.decode("utf-8", "ignore")
            return self.error(msg)
        except Exception as e:
            msg = str(e)
            return self.error(msg)
        return self.success() 
Example #4
Source File: flask_mail.py    From flask-unchained with MIT License 6 votes vote down vote up
def configure_host(self):
        if self.mail.use_ssl:
            host = smtplib.SMTP_SSL(self.mail.server, self.mail.port)
        else:
            host = smtplib.SMTP(self.mail.server, self.mail.port)

        host.set_debuglevel(int(self.mail.debug))

        if self.mail.use_tls:
            (resp, reply) = host.starttls()
            # Fix CVE-2016-0772 on old Python installations
            if resp != 200:
                raise smtplib.SMTPResponseException(resp, reply)
        if self.mail.username and self.mail.password:
            host.login(self.mail.username, self.mail.password)

        return host 
Example #5
Source File: test_smtplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #6
Source File: postel.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def _handle_sending_exception(self, err):
        if isinstance(err, smtplib.SMTPServerDisconnected):
            raise SendMailException(
                'The server unexpectedly closed the connection', 503)

        elif isinstance(err, smtplib.SMTPRecipientsRefused):
            raise SendMailException('Sending to all recipients failed', 402)

        elif isinstance(err, smtplib.SMTPResponseException):
            # Distinguish between permanent failures due to message
            # content or recipients, and temporary failures for other reasons.
            # In particular, see https://support.google.com/a/answer/3726730

            message = 'Sending failed'
            http_code = 503

            if err.smtp_code in SMTP_ERRORS:
                for stem in SMTP_ERRORS[err.smtp_code]:
                    if stem in err.smtp_error:
                        res = SMTP_ERRORS[err.smtp_code][stem]
                        http_code = res[0]
                        message = res[1]
                        break

            server_error = '{} : {}'.format(err.smtp_code, err.smtp_error)

            self.log.error('Sending failed', message=message,
                           http_code=http_code, server_error=server_error)

            raise SendMailException(message, http_code=http_code,
                                    server_error=server_error)
        else:
            raise SendMailException('Sending failed', http_code=503,
                                    server_error=str(err)) 
Example #7
Source File: mail.py    From timestrap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_messages(self, email_messages):
        """
        Override the from_email property all email messages.
        """
        if not email_messages:
            return
        with self._lock:
            for message in email_messages:
                message.from_email = get_site_setting("smtp_from_address")
        try:
            super().send_messages(email_messages)
        except (SMTPResponseException, socket_error) as e:
            # TODO: Determine how to handle failures gracefully.
            raise e 
Example #8
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_with_statement_QUIT_failure(self):
        with self.assertRaises(smtplib.SMTPResponseException) as error:
            with smtplib.SMTP(HOST, self.port) as smtp:
                smtp.noop()
                self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
        self.assertEqual(error.exception.smtp_code, 421)
        self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')

    #TODO: add tests for correct AUTH method fallback now that the
    #test infrastructure can support it.

    # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception 
Example #9
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #10
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 5 votes vote down vote up
def execute(self, host, port='', ssl='0', helo='', starttls='0', user=None, password=None, timeout='10', persistent='1'):

    with Timing() as timing:
      fp, resp = self.bind(host, port, ssl, helo, starttls, timeout=timeout)

    try:
      if user is not None and password is not None:
        with Timing() as timing:
          resp = fp.login(user, password)

      logger.debug('No error: %s' % str(resp))
      self.reset()

    except SMTPResponseException as e:
      logger.debug('SMTPResponseException: %s' % e)
      resp = e.args

    except SMTPException as e:
      logger.debug('SMTPException: %s' % e)
      resp = '1', b(str(e))

    if persistent == '0':
      self.reset()

    code, mesg = resp
    return self.Response(code, B(mesg), timing)

# }}}

# Finger {{{ 
Example #11
Source File: test_smtplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_with_statement_QUIT_failure(self):
        with self.assertRaises(smtplib.SMTPResponseException) as error:
            with smtplib.SMTP(HOST, self.port) as smtp:
                smtp.noop()
                self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
        self.assertEqual(error.exception.smtp_code, 421)
        self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')

    #TODO: add tests for correct AUTH method fallback now that the
    #test infrastructure can support it.

    # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception 
Example #12
Source File: test_smtplib.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #13
Source File: test_upstream.py    From flask-unchained with MIT License 5 votes vote down vote up
def test_configure_host_tls_failure(self):
        with mock.patch('flask_mail.smtplib.SMTP') as MockSMTP:
            mock_host = MockSMTP.return_value
            mock_host.starttls.return_value = (501, "Syntax error (testing)")
            with mock.patch.object(self.mail, "use_tls", True):
                self.assertTrue(self.mail.use_tls)
                self.assertRaises(smtplib.SMTPResponseException,
                                  Connection(self.mail).configure_host) 
Example #14
Source File: test_smtplib.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_with_statement_QUIT_failure(self):
        with self.assertRaises(smtplib.SMTPResponseException) as error:
            with smtplib.SMTP(HOST, self.port) as smtp:
                smtp.noop()
                self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
        self.assertEqual(error.exception.smtp_code, 421)
        self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')

    #TODO: add tests for correct AUTH method fallback now that the
    #test infrastructure can support it.

    # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception 
Example #15
Source File: test_smtplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_with_statement_QUIT_failure(self):
        with self.assertRaises(smtplib.SMTPResponseException) as error:
            with smtplib.SMTP(HOST, self.port) as smtp:
                smtp.noop()
                self.serv._SMTPchannel.quit_response = '421 QUIT FAILED'
        self.assertEqual(error.exception.smtp_code, 421)
        self.assertEqual(error.exception.smtp_error, b'QUIT FAILED')

    #TODO: add tests for correct AUTH method fallback now that the
    #test infrastructure can support it.

    # Issue 17498: make sure _rset does not raise SMTPServerDisconnected exception 
Example #16
Source File: test_smtplib.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #17
Source File: patator.py    From patator with GNU General Public License v2.0 5 votes vote down vote up
def execute(self, host, port='', ssl='0', helo='', starttls='0', user=None, password=None, timeout='10', persistent='1'):

    with Timing() as timing:
      fp, resp = self.bind(host, port, ssl, helo, starttls, timeout=timeout)

    try:
      if user is not None and password is not None:
        with Timing() as timing:
          resp = fp.login(user, password)

      logger.debug('No error: %s' % str(resp))
      self.reset()

    except SMTPResponseException as e:
      logger.debug('SMTPResponseException: %s' % e)
      resp = e.args

    except SMTPException as e:
      logger.debug('SMTPException: %s' % e)
      resp = '1', b(str(e))

    if persistent == '0':
      self.reset()

    code, mesg = resp
    return self.Response(code, B(mesg), timing)

# }}}

# Finger {{{ 
Example #18
Source File: test_smtplib.py    From oss-ftp with MIT License 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #19
Source File: mailproxy.py    From mailproxy with MIT License 5 votes vote down vote up
def _deliver(self, envelope):
        refused = {}
        try:
            if self._use_ssl:
                s = smtplib.SMTP_SSL()
            else:
                s = smtplib.SMTP()
            s.connect(self._host, self._port)
            if self._starttls:
                s.starttls()
                s.ehlo()
            if self._auth_user and self._auth_password:
                s.login(self._auth_user, self._auth_password)
            try:
                refused = s.sendmail(
                    envelope.mail_from,
                    envelope.rcpt_tos,
                    envelope.original_content
                )
            finally:
                s.quit()
        except (OSError, smtplib.SMTPException) as e:
            logging.exception('got %s', e.__class__)
            # All recipients were refused. If the exception had an associated
            # error code, use it.  Otherwise, fake it with a SMTP 554 status code. 
            errcode = getattr(e, 'smtp_code', 554)
            errmsg = getattr(e, 'smtp_error', e.__class__)
            raise smtplib.SMTPResponseException(errcode, errmsg.decode()) 
Example #20
Source File: mailproxy.py    From mailproxy with MIT License 5 votes vote down vote up
def handle_DATA(self, server, session, envelope):
        try:
            refused = self._deliver(envelope)
        except smtplib.SMTPRecipientsRefused as e:
            logging.info('Got SMTPRecipientsRefused: %s', refused)
            return "553 Recipients refused {}".format(' '.join(refused.keys()))
        except smtplib.SMTPResponseException as e:
            return "{} {}".format(e.smtp_code, e.smtp_error)
        else:
            if refused:
                logging.info('Recipients refused: %s', refused)
            return '250 OK'

    # adapted from https://github.com/aio-libs/aiosmtpd/blob/master/aiosmtpd/handlers.py 
Example #21
Source File: test_smtplib.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def testLineTooLong(self):
        self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
                          HOST, self.port, 'localhost', 3) 
Example #22
Source File: test_email.py    From messages with MIT License 5 votes vote down vote up
def test_get_session_ssl_raisesMessSendErr(get_email, mocker):
    """
    GIVEN an incorrect password in a valid Email object
    WHEN Email.get_session() is called
    THEN assert Exception is raised
    """
    get_ssl_mock = mocker.patch.object(Email, '_get_ssl')
    get_ssl_mock.return_value.login.side_effect = SMTPResponseException(code=0, msg=b'')
    e = get_email
    with pytest.raises(MessageSendError):
        e._get_session() 
Example #23
Source File: email_.py    From messages with MIT License 5 votes vote down vote up
def _get_session(self):
        """Start session with email server."""
        if self.port in (465, "465"):
            session = self._get_ssl()
        elif self.port in (587, "587"):
            session = self._get_tls()

        try:
            session.login(self.from_, self._auth)
        except SMTPResponseException as e:
            raise MessageSendError(e.smtp_error.decode("unicode_escape"))

        return session 
Example #24
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def send(self, lines, to_addrs):
        try:
            if self.username or self.password:
                self.smtp.login(self.username, self.password)
            msg = "".join(lines)
            # turn comma-separated list into Python list if needed.
            if is_string(to_addrs):
                to_addrs = [
                    email for (name, email) in getaddresses([to_addrs])
                ]
            self.smtp.sendmail(self.envelopesender, to_addrs, msg)
        except smtplib.SMTPResponseException:
            err = sys.exc_info()[1]
            self.environment.get_logger().error(
                "*** Error sending email ***\n"
                "*** Error %d: %s\n"
                % (err.smtp_code, bytes_to_str(err.smtp_error))
            )
            try:
                smtp = self.smtp
                # delete the field before quit() so that in case of
                # error, self.smtp is deleted anyway.
                del self.smtp
                smtp.quit()
            except:
                self.environment.get_logger().error(
                    "*** Error closing the SMTP connection ***\n"
                    "*** Exiting anyway ... ***\n"
                    "*** %s\n" % sys.exc_info()[1]
                )
            sys.exit(1) 
Example #25
Source File: SMTPTester.py    From SMTPTester with GNU General Public License v3.0 4 votes vote down vote up
def external_test(smtp_targets, port, fromaddr, recipient, data, subject, debug):
    data += "\nThis email is part of external relay and\\or spoofing test"

    for target in smtp_targets:
        LOGGER.info("[*] Checking host " + target + ':' + str(port))
        LOGGER.info("[*] Testing for mail relaying (external)")
        data += "\nVulnerable server is: %s" % target
        try:
            if fromaddr and recipient:  # checking we have both to and from addresses
                with SMTP(target, port) as current_target:
                    if debug:
                        current_target.set_debuglevel(1)
                    current_target.ehlo_or_helo_if_needed()
################
                    # Create a multipart message and set headers
                    message = MIMEMultipart()
                    message["From"] = fromaddr
                    message["To"] = recipient
                    message["Subject"] = subject
                    # message["Bcc"] = receiver_email  # Recommended for mass emails

                    # Add body to email
                    message.attach(MIMEText(data, "plain"))

                    # # Open PDF file in binary mode
                    # with open(attachment, "rb") as attached:
                    #     # Add file as application/octet-stream
                    #     # Email client can usually download this automatically as attachment
                    #     part = MIMEBase("application", "octet-stream")
                    #     part.set_payload(attached.read())
                    #
                    # # Encode file in ASCII characters to send by email
                    # encoders.encode_base64(part)
                    #
                    # # Add header as key/value pair to attachment part
                    # part.add_header(
                    #     "Content-Disposition",
                    #     "attachment; filename= {attachment}",
                    # )
                    #
                    # # Add attachment to message and convert message to string
                    # message.attach(part)
                    text = message.as_string()
##############
                    current_target.sendmail(fromaddr, recipient, text)
                    LOGGER.critical("[+] Server %s Appears to be VULNERABLE for external relay! "
                                    "email send FROM: %s TO: %s", target, fromaddr, recipient)
            else:
                LOGGER.critical("[!] Problem with FROM and/or TO address!")
                exit(1)
        except (SMTPRecipientsRefused, SMTPSenderRefused, SMTPResponseException) as e:
            LOGGER.critical("[!] SMTP Error: %s\n[-] Server: %s NOT vulnerable!", str(e), target)
        except ConnectionRefusedError:
            LOGGER.critical("[!] Connection refused by host %s", target)
        except KeyboardInterrupt:
            LOGGER.critical("[!] [CTRL+C] Stopping...")
            exit(1)
        except Exception as e:
            excptn(e)