当前位置: 首页>>代码示例>>Python>>正文


Python smtplib.SMTPServerDisconnected方法代码示例

本文整理汇总了Python中smtplib.SMTPServerDisconnected方法的典型用法代码示例。如果您正苦于以下问题:Python smtplib.SMTPServerDisconnected方法的具体用法?Python smtplib.SMTPServerDisconnected怎么用?Python smtplib.SMTPServerDisconnected使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在smtplib的用法示例。


在下文中一共展示了smtplib.SMTPServerDisconnected方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: send

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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') 
开发者ID:janeczku,项目名称:calibre-web,代码行数:27,代码来源:worker.py

示例2: close

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:smtp.py

示例3: server_smtp_reconnect

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:21,代码来源:mailer.py

示例4: retry_send_email_failures

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:zulip,项目名称:zulip,代码行数:20,代码来源:queue_processors.py

示例5: close

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:blackye,项目名称:luscan-devel,代码行数:20,代码来源:smtp.py

示例6: _send_email

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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() 
开发者ID:Teagan42,项目名称:HomeAssistantConfig,代码行数:20,代码来源:notify.py

示例7: send_mail

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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))

    # -------------------------------------------------------------------------- 
开发者ID:BaobabLims,项目名称:baobab.lims,代码行数:20,代码来源:sampleshipment.py

示例8: send_mail

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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)) 
开发者ID:BaobabLims,项目名称:baobab.lims,代码行数:18,代码来源:shipment.py

示例9: getreply

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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) 
开发者ID:vuamitom,项目名称:tornado-smtpclient,代码行数:27,代码来源:client.py

示例10: logout

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:ZYunH,项目名称:zmail,代码行数:24,代码来源:server.py

示例11: rset

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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) 
开发者ID:nylas,项目名称:sync-engine,代码行数:21,代码来源:postel.py

示例12: server_smtp_disconnect

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
def server_smtp_disconnect(self):
		"""Clean up and close the connection to the remote SMTP server."""
		if self.smtp_connection:
			self.logger.debug('closing the connection to the SMTP server')
			try:
				self.smtp_connection.quit()
			except smtplib.SMTPServerDisconnected:
				pass
			self.smtp_connection = None
			self.tab_notify_status('Disconnected from the SMTP server') 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:12,代码来源:mailer.py

示例13: _try_send_message

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:28,代码来源:mailer.py

示例14: testNotConnected

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
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') 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:11,代码来源:test_smtplib.py

示例15: test_email_sending_worker_retries

# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPServerDisconnected [as 别名]
def test_email_sending_worker_retries(self) -> None:
        """Tests the retry_send_email_failures decorator to make sure it
        retries sending the email 3 times and then gives up."""
        fake_client = self.FakeClient()

        data = {
            'template_prefix': 'zerver/emails/confirm_new_email',
            'to_emails': [self.example_email("hamlet")],
            'from_name': 'Zulip Account Security',
            'from_address': FromAddress.NOREPLY,
            'context': {},
        }
        fake_client.queue.append(('email_senders', data))

        def fake_publish(queue_name: str,
                         event: Dict[str, Any],
                         processor: Callable[[Any], None]) -> None:
            fake_client.queue.append((queue_name, event))

        with simulated_queue_client(lambda: fake_client):
            worker = queue_processors.EmailSendingWorker()
            worker.setup()
            with patch('zerver.lib.send_email.build_email',
                       side_effect=smtplib.SMTPServerDisconnected), \
                    patch('zerver.lib.queue.queue_json_publish',
                          side_effect=fake_publish), \
                    patch('logging.exception'):
                worker.start()

        self.assertEqual(data['failed_tries'], 1 + MAX_REQUEST_RETRIES) 
开发者ID:zulip,项目名称:zulip,代码行数:32,代码来源:test_queue_worker.py


注:本文中的smtplib.SMTPServerDisconnected方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。