Python smtplib.SMTPServerDisconnected() Examples

The following are 30 code examples of smtplib.SMTPServerDisconnected(). 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: smtp.py    From GTDWeb with GNU General Public License v2.0 9 votes vote down vote up
def close(self):
        """Closes the connection to the email server."""
        if self.connection is None:
            return
        try:
            try:
                self.connection.quit()
            except (ssl.SSLError, smtplib.SMTPServerDisconnected):
                # This happens when calling quit() on a TLS connection
                # sometimes, or when the connection was already disconnected
                # by the server.
                self.connection.close()
            except smtplib.SMTPException:
                if self.fail_silently:
                    return
                raise
        finally:
            self.connection = None 
Example #2
Source File: worker.py    From calibre-web with GNU General Public License v3.0 7 votes vote down vote up
def send(self, strg):
        """Send `strg' to the server."""
        log.debug('send: %r', strg[:300])
        if hasattr(self, 'sock') and self.sock:
            try:
                if self.transferSize:
                    lock=threading.Lock()
                    lock.acquire()
                    self.transferSize = len(strg)
                    lock.release()
                    for i in range(0, self.transferSize, chunksize):
                        if isinstance(strg, bytes):
                            self.sock.send((strg[i:i+chunksize]))
                        else:
                            self.sock.send((strg[i:i + chunksize]).encode('utf-8'))
                        lock.acquire()
                        self.progress = i
                        lock.release()
                else:
                    self.sock.sendall(strg.encode('utf-8'))
            except socket.error:
                self.close()
                raise smtplib.SMTPServerDisconnected('Server not connected')
        else:
            raise smtplib.SMTPServerDisconnected('please run connect() first') 
Example #3
Source File: sampleshipment.py    From baobab.lims with GNU General Public License v3.0 7 votes vote down vote up
def send_mail(self, sender, receiver, subject="", body=""):
        """Send email from sender to receiver
        """
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = sender
        mime_msg['To'] = receiver
        msg_txt = MIMEText(body, 'plain')
        mime_msg.attach(msg_txt)
        try:
            host = getToolByName(self, 'MailHost')
            host.send(mime_msg.as_string(), immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg))

    # -------------------------------------------------------------------------- 
Example #4
Source File: notify.py    From HomeAssistantConfig with MIT License 7 votes vote down vote up
def _send_email(self, msg, recipients):
        """Send the message."""
        mail = self.connect()
        for _ in range(self.tries):
            try:
                mail.sendmail(self._sender, recipients, msg.as_string())
                break
            except smtplib.SMTPServerDisconnected:
                _LOGGER.warning(
                    "SMTPServerDisconnected sending mail: retrying connection")
                mail.quit()
                mail = self.connect()
            except smtplib.SMTPException:
                _LOGGER.warning(
                    "SMTPException sending mail: retrying connection")
                mail.quit()
                mail = self.connect()
        mail.quit() 
Example #5
Source File: queue_processors.py    From zulip with Apache License 2.0 6 votes vote down vote up
def retry_send_email_failures(
        func: Callable[[ConcreteQueueWorker, Dict[str, Any]], None],
) -> Callable[['QueueProcessingWorker', Dict[str, Any]], None]:

    @wraps(func)
    def wrapper(worker: ConcreteQueueWorker, data: Dict[str, Any]) -> None:
        try:
            func(worker, data)
        except (smtplib.SMTPServerDisconnected, socket.gaierror, socket.timeout,
                EmailNotDeliveredException) as e:
            error_class_name = e.__class__.__name__

            def on_failure(event: Dict[str, Any]) -> None:
                logging.exception("Event %r failed due to exception %s", event, error_class_name)

            retry_event(worker.queue_name, data, on_failure)

    return wrapper 
Example #6
Source File: mailer.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _try_send_message(self, *args, **kwargs):
		message_sent = False
		while not message_sent and not self.should_stop.is_set():
			for i in range(0, 3):
				try:
					self.send_message(*args, **kwargs)
					message_sent = True
					break
				except smtplib.SMTPServerDisconnected:
					self.logger.warning('failed to send message, the server has been disconnected')
					self.tab_notify_status('Failed to send message, the server has been disconnected')
					self.tab_notify_status('Sleeping for 5 seconds before attempting to reconnect')
					if self._sleep(5):
						break
					self.smtp_connection = None
					self.server_smtp_reconnect()
				except smtplib.SMTPException as error:
					self.tab_notify_status("Failed to send message (exception: {0})".format(error.__class__.__name__))
					self.logger.warning("failed to send message (exception: smtplib.{0})".format(error.__class__.__name__))
					self._sleep((i + 1) ** 2)
			if not message_sent:
				self.server_smtp_disconnect()
				if not self.process_pause(True):
					return False
				self.server_smtp_reconnect()
		return True 
Example #7
Source File: mailer.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def server_smtp_reconnect(self):
		"""
		Disconnect from the remote SMTP server and then attempt to open
		a new connection to it.

		:return: The reconnection status.
		:rtype: bool
		"""
		if self.smtp_connection:
			try:
				self.smtp_connection.quit()
			except smtplib.SMTPServerDisconnected:
				pass
			self.smtp_connection = None
		while self.server_smtp_connect() != ConnectionErrorReason.SUCCESS:
			self.tab_notify_status('Failed to reconnect to the SMTP server')
			if not self.process_pause(True):
				return False
		return True 
Example #8
Source File: postel.py    From sync-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
def rset(self):
        """Wrap rset() in order to correctly surface SMTP exceptions.
        SMTP.sendmail() does e.g.:
            # ...
            (code, resp) = self.data(msg)
            if code != 250:
                self.rset()
                raise SMTPDataError(code, resp)
            # ...
        But some servers will disconnect rather than respond to RSET, causing
        SMTPServerDisconnected rather than SMTPDataError to be raised. This
        basically obfuscates the actual server error.

        See also http://bugs.python.org/issue16005
        """
        try:
            smtplib.SMTP.rset(self)
        except smtplib.SMTPServerDisconnected:
            log.warning('Server disconnect during SMTP rset', exc_info=True) 
Example #9
Source File: postel.py    From sync-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
def rset(self):
        """Wrap rset() in order to correctly surface SMTP exceptions.
        SMTP.sendmail() does e.g.:
            # ...
            (code, resp) = self.data(msg)
            if code != 250:
                self.rset()
                raise SMTPDataError(code, resp)
            # ...
        But some servers will disconnect rather than respond to RSET, causing
        SMTPServerDisconnected rather than SMTPDataError to be raised. This
        basically obfuscates the actual server error.

        See also http://bugs.python.org/issue16005
        """
        try:
            smtplib.SMTP_SSL.rset(self)
        except smtplib.SMTPServerDisconnected:
            log.warning('Server disconnect during SMTP rset', exc_info=True) 
Example #10
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 #11
Source File: smtp.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def close(self):
        """Closes the connection to the email server."""
        if self.connection is None:
            return
        try:
            try:
                self.connection.quit()
            except (ssl.SSLError, smtplib.SMTPServerDisconnected):
                # This happens when calling quit() on a TLS connection
                # sometimes, or when the connection was already disconnected
                # by the server.
                self.connection.close()
            except:
                if self.fail_silently:
                    return
                raise
        finally:
            self.connection = None 
Example #12
Source File: client.py    From tornado-smtpclient with MIT License 6 votes vote down vote up
def getreply(self):

        resp = []
        while True:
            try:

                response = yield self.stream.read_until(CRLF)

            except socket.error as e:
                logger.exception(e)
                raise smtplib.SMTPServerDisconnected("Connection unexpectedly closed")
            resp.append(response[4:])
            code = response[0:3]
            try:
                code= int(code)
            except ValueError:
                code = -1
                break

            if response[3] in b' \r\n':
                break


        msg = b'\n'.join(resp)
        return (code,msg) 
Example #13
Source File: shipment.py    From baobab.lims with GNU General Public License v3.0 6 votes vote down vote up
def send_mail(self, sender, receiver, subject="", body=""):
        """Send email from sender to receiver
        """
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = sender
        mime_msg['To'] = receiver
        msg_txt = MIMEText(body, 'plain')
        mime_msg.attach(msg_txt)
        try:
            host = getToolByName(self, 'MailHost')
            host.send(mime_msg.as_string(), immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg)) 
Example #14
Source File: test_smtplib.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def testNotConnected(self):
        # Test various operations on an unconnected SMTP object that
        # should raise exceptions (at present the attempt in SMTP.send
        # to reference the nonexistent 'sock' attribute of the SMTP object
        # causes an AttributeError)
        smtp = smtplib.SMTP()
        self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
        self.assertRaises(smtplib.SMTPServerDisconnected,
                          smtp.send, 'test msg') 
Example #15
Source File: test_email_notification.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def test_smtp_sendmail_failed_connection_once(self, mock_smtp):
        """Email that fails on smtp_connect once
        """

        metrics = []
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo1', 'service': 'bar1'}}
        metrics.append(metric_data)
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo2', 'service': 'bar2'}}
        metrics.append(metric_data)

        mock_log = mock.MagicMock()
        mock_log.warn = self.trap.append
        mock_log.error = self.trap.append
        mock_log.debug = self.trap.append
        mock_log.info = self.trap.append
        mock_log.exception = self.trap.append

        mock_smtp.SMTP.return_value = mock_smtp
        mock_smtp.sendmail.side_effect = [smtplib.SMTPServerDisconnected, None]

        # There has to be a better way to preserve exception definitions when
        # we're mocking access to a library
        mock_smtp.SMTPServerDisconnected = smtplib.SMTPServerDisconnected
        mock_smtp.SMTPException = smtplib.SMTPException

        email = email_notifier.EmailNotifier(mock_log)

        email.config()

        alarm_dict = alarm(metrics)

        notification = Notification(0, 'email', 'email notification',
                                    'me@here.com', 0, 0, alarm_dict)

        self.trap.append(email.send_notification(notification))

        self.assertIn("SMTP server disconnected. Will reconnect and retry message.", self.trap)
        self.assertIn("Sent email to %s, notification %s"
                      % (notification.address, notification.to_json()), self.trap) 
Example #16
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def testNotConnected(self):
        # Test various operations on an unconnected SMTP object that
        # should raise exceptions (at present the attempt in SMTP.send
        # to reference the nonexistent 'sock' attribute of the SMTP object
        # causes an AttributeError)
        smtp = smtplib.SMTP()
        self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
        self.assertRaises(smtplib.SMTPServerDisconnected,
                          smtp.send, 'test msg') 
Example #17
Source File: test_smtp.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handle_disconnect(monkeypatch, smtp_port):
    def simulate_disconnect(self):
        raise smtplib.SMTPServerDisconnected()
    monkeypatch.setattr('smtplib.SMTP.rset', simulate_disconnect)
    monkeypatch.setattr('smtplib.SMTP.mail', lambda *args: (550, 'NOPE'))
    conn = SMTPConnection(account_id=1,
                          email_address='inboxapptest@gmail.com',
                          smtp_username='inboxapptest@gmail.com',
                          auth_type='password',
                          auth_token='secret_password',
                          smtp_endpoint=('smtp.gmail.com', smtp_port),
                          ssl_required=True,
                          log=get_logger())
    with pytest.raises(smtplib.SMTPSenderRefused):
        conn.sendmail(['test@example.com'], 'hello there') 
Example #18
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def connection_closed(patch_token_manager, monkeypatch):
    monkeypatch.setattr('inbox.sendmail.smtp.postel.SMTPConnection',
                        erring_smtp_connection(smtplib.SMTPServerDisconnected)) 
Example #19
Source File: emails.py    From SPF with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_mx(server, domain):
    try:
        if server in MX_RECORD_CACHE:
            return MX_RECORD_CACHE[server]
        smtp = smtplib.SMTP(timeout=10)
        smtp.connect(server)
        status, _ = smtp.helo()
        if status != 250:
            smtp.quit()
            print("%s answer: %s - %s" % (server, status, _))
        smtp.mail('')
        status, _ = smtp.rcpt("invalid@"+domain)
        if status == 250:
            smtp.quit()
            MX_RECORD_CACHE[server] = True
            return True
        print("%s answer: %s - %s" % (server, status, _))
        smtp.quit()
    except smtplib.SMTPServerDisconnected as e:  # Server not permits verify user
        print("%s disconnected. [%s]" % (server, e))
    except smtplib.SMTPConnectError as e:
        print("Unable to connect to %s. [%s]" % (server, e))
    except socket.timeout as e:
        print("Timedout connecting to %s. [%s]" % (server, e))
    MX_RECORD_CACHE[server] = False
    return False        

# Lookup a domain and get its mailserver 
Example #20
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 #21
Source File: test_smtplib.py    From android_universal with MIT License 5 votes vote down vote up
def test_with_statement(self):
        with smtplib.SMTP(HOST, self.port) as smtp:
            code, message = smtp.noop()
            self.assertEqual(code, 250)
        self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo')
        with smtplib.SMTP(HOST, self.port) as smtp:
            smtp.close()
        self.assertRaises(smtplib.SMTPServerDisconnected, smtp.send, b'foo') 
Example #22
Source File: test_email_notification.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def test_smtp_sendmail_failed_connection_once_then_email(self, mock_smtp):
        """Email that fails on smtp_connect once then email
        """

        metrics = []
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo1', 'service': 'bar1'}}
        metrics.append(metric_data)
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo2', 'service': 'bar2'}}
        metrics.append(metric_data)

        mock_log = mock.MagicMock()
        mock_log.warn = self.trap.append
        mock_log.error = self.trap.append
        mock_log.debug = self.trap.append
        mock_log.info = self.trap.append
        mock_log.exception = self.trap.append

        mock_smtp.SMTP.return_value = mock_smtp

        mock_smtp.sendmail.side_effect = [smtplib.SMTPServerDisconnected,
                                          smtplib.SMTPException]

        # There has to be a better way to preserve exception definitions when
        # we're mocking access to a library
        mock_smtp.SMTPServerDisconnected = smtplib.SMTPServerDisconnected
        mock_smtp.SMTPException = smtplib.SMTPException

        email = email_notifier.EmailNotifier(mock_log)

        email.config()

        alarm_dict = alarm(metrics)

        notification = Notification(0, 'email', 'email notification',
                                    'me@here.com', 0, 0, alarm_dict)

        self.trap.append(email.send_notification(notification))

        self.assertIn("SMTP server disconnected. Will reconnect and retry message.", self.trap)
        self.assertIn("Error sending Email Notification", self.trap)
        self.assertNotIn("Unable to connect to email server.", self.trap) 
Example #23
Source File: client.py    From tornado-smtpclient with MIT License 5 votes vote down vote up
def _rset(self):
        """Internal 'rset' command which ignores any SMTPServerDisconnected error.
        """
        try:
            yield self.rset()
        except smtplib.SMTPServerDisconnected:
            pass 
Example #24
Source File: client.py    From tornado-smtpclient with MIT License 5 votes vote down vote up
def ehlo(self, name=''):
        self.esmtp_features = {}
        yield self.putcmd(self.ehlo_msg,  name or self.local_hostname)
        (code, msg) = yield self.getreply()

        self.ehlo_resp = msg
        if code == -1 and len (msg) == 0 :
            self.close()
            raise smtplib.SMTPServerDisconnected("Server not connected")

        if code != 250:
            return (code, msg)
        self.does_esmtp =1

        #parse the ehlo response -ddm
        resp=self.ehlo_resp.split(b'\n')
        del resp[0]
        for each in resp:
            val = each.decode()
            auth_match = smtplib.OLDSTYLE_AUTH.match(val)
            if auth_match:
                # This doesn't remove duplicates, but that's no problem
                self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \
                        + " " + auth_match.groups(0)[0]
                continue

            # RFC 1869 requires a space between ehlo keyword and parameters.
            # It's actually stricter, in that only spaces are allowed between
            # parameters, but were not going to check for that here.  Note
            # that the space isn't present if there are no parameters.
            m= re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?',val)
            if m:
                feature=m.group("feature").lower()
                params=m.string[m.end("feature"):].strip()
                if feature == "auth":
                    self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
                            + " " + params
                else:
                    self.esmtp_features[feature]=params
        return (code,msg) 
Example #25
Source File: test_sending.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def connection_closed(patch_token_manager, monkeypatch):
    monkeypatch.setattr('inbox.sendmail.smtp.postel.SMTPConnection',
                        erring_smtp_connection(smtplib.SMTPServerDisconnected)) 
Example #26
Source File: email_client.py    From FudgeC2 with GNU General Public License v3.0 5 votes vote down vote up
def test_conn_open(self, conn):
        try:
            status = conn.noop()[0]
        except:  # smtplib.SMTPServerDisconnected
            status = -1
        return True if status == 250 else False

    # Should require admin privs. returns True, msg || False msg 
Example #27
Source File: test_smtp.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_handle_disconnect(monkeypatch, smtp_port):
    def simulate_disconnect(self):
        raise smtplib.SMTPServerDisconnected()
    monkeypatch.setattr('smtplib.SMTP.rset', simulate_disconnect)
    monkeypatch.setattr('smtplib.SMTP.mail', lambda *args: (550, 'NOPE'))
    conn = SMTPConnection(account_id=1,
                          email_address='inboxapptest@gmail.com',
                          smtp_username='inboxapptest@gmail.com',
                          auth_type='password',
                          auth_token='secret_password',
                          smtp_endpoint=('smtp.gmail.com', smtp_port),
                          ssl_required=True,
                          log=get_logger())
    with pytest.raises(smtplib.SMTPSenderRefused):
        conn.sendmail(['test@example.com'], 'hello there') 
Example #28
Source File: sender.py    From yagmail with MIT License 5 votes vote down vote up
def close(self):
        """ Close the connection to the SMTP server """
        self.is_closed = True
        try:
            self.smtp.quit()
        except (TypeError, AttributeError, smtplib.SMTPServerDisconnected):
            pass 
Example #29
Source File: sender.py    From yagmail with MIT License 5 votes vote down vote up
def _attempt_send(self, recipients, msg_string):
        attempts = 0
        while attempts < 3:
            try:
                result = self.smtp.sendmail(self.user, recipients, msg_string)
                self.log.info("Message sent to %s", recipients)
                self.num_mail_sent += 1
                return result
            except smtplib.SMTPServerDisconnected as e:
                self.log.error(e)
                attempts += 1
                time.sleep(attempts * 3)
        self.unsent.append((recipients, msg_string))
        return False 
Example #30
Source File: test_email_notification.py    From monasca-notification with Apache License 2.0 5 votes vote down vote up
def test_smtp_sendmail_failed_exception(self, mock_smtp):
        """Email that fails on exception
        """

        metrics = []
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo1', 'service': 'bar1'}}
        metrics.append(metric_data)
        metric_data = {'name': 'cpu.percent', 'dimensions': {'hostname': 'foo2', 'service': 'bar2'}}
        metrics.append(metric_data)

        mock_log = mock.MagicMock()
        mock_log.warn = self.trap.append
        mock_log.error = self.trap.append
        mock_log.debug = self.trap.append
        mock_log.info = self.trap.append
        mock_log.exception = self.trap.append

        mock_smtp.SMTP.return_value = mock_smtp
        mock_smtp.sendmail.side_effect = smtplib.SMTPException

        # There has to be a better way to preserve exception definitions when
        # we're mocking access to a library
        mock_smtp.SMTPServerDisconnected = smtplib.SMTPServerDisconnected
        mock_smtp.SMTPException = smtplib.SMTPException

        email = email_notifier.EmailNotifier(mock_log)

        email.config()

        alarm_dict = alarm(metrics)

        notification = Notification(0, 'email', 'email notification',
                                    'me@here.com', 0, 0, alarm_dict)

        self.trap.append(email.send_notification(notification))

        self.assertNotIn("SMTP server disconnected. Will reconnect and retry message.", self.trap)
        self.assertIn("Error sending Email Notification", self.trap)