本文整理匯總了Python中smtplib.SMTPResponseException方法的典型用法代碼示例。如果您正苦於以下問題:Python smtplib.SMTPResponseException方法的具體用法?Python smtplib.SMTPResponseException怎麽用?Python smtplib.SMTPResponseException使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類smtplib
的用法示例。
在下文中一共展示了smtplib.SMTPResponseException方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_get_session_tls_raisesMessSendErr
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
##############################################################################
示例2: configure_host
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
示例3: post
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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()
示例4: logout
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [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
示例5: send
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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)
示例6: _get_session
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
示例7: test_get_session_ssl_raisesMessSendErr
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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()
示例8: testLineTooLong
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
def testLineTooLong(self):
self.assertRaises(smtplib.SMTPResponseException, smtplib.SMTP,
HOST, self.port, 'localhost', 3)
示例9: handle_DATA
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
示例10: _deliver
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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())
示例11: execute
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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 {{{
示例12: test_with_statement_QUIT_failure
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
示例13: test_configure_host_tls_failure
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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)
示例14: send_messages
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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
示例15: _handle_sending_exception
# 需要導入模塊: import smtplib [as 別名]
# 或者: from smtplib import SMTPResponseException [as 別名]
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))