本文整理匯總了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')
示例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
示例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
示例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
示例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
示例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()
示例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))
# --------------------------------------------------------------------------
示例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))
示例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)
示例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
示例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)
示例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')
示例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
示例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')
示例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)