本文整理汇总了Python中smtplib.SMTPException方法的典型用法代码示例。如果您正苦于以下问题:Python smtplib.SMTPException方法的具体用法?Python smtplib.SMTPException怎么用?Python smtplib.SMTPException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib
的用法示例。
在下文中一共展示了smtplib.SMTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: close
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [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
示例2: user_post_save
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def user_post_save(sender, instance, created, **kwargs):
if created:
User = get_user_model()
recipient_list = [item[0] for item in User.objects.filter(is_superuser=True).values_list('email')]
notification_type = NotificationType.USER_CREATED
context = {'user': instance}
if len(recipient_list) == 0:
logger.warning("No recipients for notification type '%s'" % notification_type, extra={'event': instance})
return
try:
rendered_notification = render_notification_template(notification_type, context)
except NotificationTemplateException as e:
logger.error(e, exc_info=True)
return
try:
send_mail(
rendered_notification['subject'],
rendered_notification['body'],
'noreply@%s' % Site.objects.get_current().domain,
recipient_list,
html_message=rendered_notification['html_body']
)
except SMTPException as e:
logger.error(e, exc_info=True, extra={'user': instance})
示例3: _send_notification
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def _send_notification(self, notification_type, recipient_list, request=None):
if len(recipient_list) == 0:
logger.warning("No recipients for notification type '%s'" % notification_type, extra={'event': self})
return
context = {'event': self}
try:
rendered_notification = render_notification_template(notification_type, context)
except NotificationTemplateException as e:
logger.error(e, exc_info=True, extra={'request': request})
return
try:
send_mail(
rendered_notification['subject'],
rendered_notification['body'],
'noreply@%s' % Site.objects.get_current().domain,
recipient_list,
html_message=rendered_notification['html_body']
)
except SMTPException as e:
logger.error(e, exc_info=True, extra={'request': request, 'event': self})
示例4: test_wraps_mail_server_exceptions
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def test_wraps_mail_server_exceptions(self, mailer, smtp):
import smtplib
from dallinger.notifications import MessengerError
smtp.login.side_effect = smtplib.SMTPException("Boom!")
with pytest.raises(MessengerError) as ex_info:
mailer.send(
subject="Some subject",
sender="from@example.com",
recipients=["to@example.com"],
body="Some\nbody",
)
assert ex_info.match("SMTP error")
smtp.login.side_effect = Exception("Boom!")
with pytest.raises(MessengerError) as ex_info:
mailer.send(
subject="Some subject",
sender="from@example.com",
recipients=["to@example.com"],
body="Some\nbody",
)
assert ex_info.match("Unknown error")
示例5: sender
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def sender(request, subject, template_name, context, to):
site = get_current_site(request)
context.update({'site_name': site.name,
'domain': site.domain,
'protocol': 'https' if request.is_secure() else 'http'})
message = render_to_string(template_name, context)
from_email = "%(site_name)s <%(name)s@%(domain)s>" % {'name': "noreply",
'domain': site.domain,
'site_name': site.name}
if len(to) > 1:
kwargs = {'bcc': to, }
else:
kwargs = {'to': to, }
email = EmailMessage(subject, message, from_email, **kwargs)
try:
email.send()
except SMTPException as err:
logger.error(err)
示例6: is_send_email
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def is_send_email(to_list, subject, body):
"""
Tries to send email. If email is sent successfully, returns True else False
If running app in Debug mode, do not try to send email
:param to_list:
:param subject:
:param body:
:return: Is sending email success
"""
if DEBUG:
return True
try:
send_mail(subject, body, DEFAULT_EMAIL_SENDER, to_list, fail_silently=False)
except SMTPException:
return False
return True
示例7: starttls
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def starttls(self, keyfile=None, certfile=None):
self.ehlo_or_helo_if_needed()
if not self.has_extn("starttls"):
raise smtplib.SMTPException("server doesn't support STARTTLS")
response, reply = self.docmd("STARTTLS")
if response == 220:
with ca_certs(self._ca_certs) as certs:
self.sock = ssl.wrap_socket(
self.sock,
certfile=certfile,
keyfile=keyfile,
ca_certs=certs,
cert_reqs=ssl.CERT_REQUIRED
)
cert = self.sock.getpeercert()
match_hostname(cert, self._host)
self.file = smtplib.SSLFakeFile(self.sock)
self.helo_resp = None
self.ehlo_resp = None
self.esmtp_features = {}
self.does_esmtp = 0
return response, reply
示例8: _connect
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def _connect(self, host, port, retry_interval=60.0):
server = None
while server is None:
self.log.info(u"Connecting to SMTP server {0!r} port {1}".format(host, port))
try:
server = yield idiokit.thread(
SMTP, host, port,
ca_certs=self.smtp_ca_certs,
timeout=self.smtp_connection_timeout
)
except (socket.error, smtplib.SMTPException) as exc:
self.log.error(u"Failed connecting to SMTP server: {0}".format(utils.format_exception(exc)))
else:
self.log.info(u"Connected to the SMTP server")
break
self.log.info(u"Retrying SMTP connection in {0:.2f} seconds".format(retry_interval))
yield idiokit.sleep(retry_interval)
idiokit.stop(server)
示例9: send_confirmation_email
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def send_confirmation_email(user: PolarisUser, account: PolarisStellarAccount):
"""
Sends a confirmation email to user.email
In a real production deployment, you would never want to send emails
as part of the request/response cycle. Instead, use a job queue service
like Celery. This reference server is not intended to handle heavy
traffic so we are making an exception here.
"""
args = urlencode({"token": account.confirmation_token, "email": user.email})
url = f"{settings.HOST_URL}{reverse('confirm_email')}?{args}"
try:
send_mail(
_("Reference Anchor Server: Confirm Email"),
# email body if the HTML is not rendered
_("Confirm your email by pasting this URL in your browser: %s") % url,
server_settings.EMAIL_HOST_USER,
[user.email],
html_message=render_to_string(
"confirmation_email.html",
{"first_name": user.first_name, "confirmation_url": url},
),
)
except SMTPException as e:
logger.error(f"Unable to send email to {user.email}: {e}")
示例10: test_bad_email_configuration_for_accounts_home
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def test_bad_email_configuration_for_accounts_home(self) -> None:
"""
Make sure we redirect for SMTP errors.
"""
email = self.nonreg_email('newguy')
smtp_mock = patch(
'zerver.views.registration.send_confirm_registration_email',
side_effect=smtplib.SMTPException('uh oh'),
)
error_mock = patch('logging.error')
with smtp_mock, error_mock as err:
result = self.client_post('/accounts/home/', {'email': email})
self._assert_redirected_to(result, '/config-error/smtp')
self.assertEqual(
err.call_args_list[0][0],
('Error in accounts_home: %s', 'uh oh'),
)
示例11: test_bad_email_configuration_for_create_realm
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def test_bad_email_configuration_for_create_realm(self) -> None:
"""
Make sure we redirect for SMTP errors.
"""
email = self.nonreg_email('newguy')
smtp_mock = patch(
'zerver.views.registration.send_confirm_registration_email',
side_effect=smtplib.SMTPException('uh oh'),
)
error_mock = patch('logging.error')
with smtp_mock, error_mock as err:
result = self.client_post('/new/', {'email': email})
self._assert_redirected_to(result, '/config-error/smtp')
self.assertEqual(
err.call_args_list[0][0],
('Error in create_realm: %s', 'uh oh'),
)
示例12: test_smtplib_init_fail
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def test_smtplib_init_fail(mock_smtplib):
"""
API: Test exception handling when calling smtplib.SMTP()
"""
# Disable Throttling to speed testing
plugins.NotifyBase.request_rate_per_sec = 0
obj = Apprise.instantiate(
'mailto://user:pass@gmail.com', suppress_exceptions=False)
assert isinstance(obj, plugins.NotifyEmail)
# Support Exception handling of smtplib.SMTP
mock_smtplib.side_effect = RuntimeError('Test')
assert obj.notify(
body='body', title='test', notify_type=NotifyType.INFO) is False
# A handled and expected exception
mock_smtplib.side_effect = smtplib.SMTPException('Test')
assert obj.notify(
body='body', title='test', notify_type=NotifyType.INFO) is False
示例13: _deliver
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def _deliver(self, mailfrom, rcpttos, data):
import smtplib
refused = {}
try:
s = smtplib.SMTP()
s.connect(self._remoteaddr[0], self._remoteaddr[1])
try:
refused = s.sendmail(mailfrom, rcpttos, data)
finally:
s.quit()
except smtplib.SMTPRecipientsRefused as e:
print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
refused = e.recipients
except (OSError, smtplib.SMTPException) as e:
print('got', e.__class__, file=DEBUGSTREAM)
# All recipients were refused. If the exception had an associated
# error code, use it. Otherwise,fake it with a non-triggering
# exception code.
errcode = getattr(e, 'smtp_code', -1)
errmsg = getattr(e, 'smtp_error', 'ignore')
for r in rcpttos:
refused[r] = (errcode, errmsg)
return refused
示例14: _send
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def _send(self, connection, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
from_email = sanitize_address(email_message.from_email,
email_message.encoding)
recipients = [sanitize_address(addr, email_message.encoding)
for addr in email_message.recipients()]
message = email_message.message()
try:
connection.sendmail(from_email, recipients,
message.as_bytes(linesep='\r\n'))
return 1
except smtplib.SMTPException:
self.app.logger.exception('Error while sending message',
extra={'mail': True})
return 0
示例15: send_email_report
# 需要导入模块: import smtplib [as 别名]
# 或者: from smtplib import SMTPException [as 别名]
def send_email_report(report):
from_email = gmail_login
to_email = [gmail_dest] # ['me@gmail.com', 'bill@gmail.com']
subject = "Virus Total Hunting Report - " + str(now)
text = report
message = 'Subject: {}\n\n{}'.format(subject, text)
try:
server = smtplib.SMTP_SSL(smtp_serv, smtp_port)
server.ehlo()
server.login(from_email, gmail_pass)
# Send the mail
server.sendmail(from_email, to_email, message)
server.quit()
print("[*] Report have been sent to your email!")
except smtplib.SMTPException as e:
print("[!] SMTP error: " + str(e))
sys.exit()
# Connect to VT