Python smtplib.SMTPException() Examples
The following are 30
code examples of smtplib.SMTPException().
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 |
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: email.py From BikeMaps with MIT License | 7 votes |
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)
Example #3
Source File: vthunting.py From vthunting with MIT License | 7 votes |
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
Example #4
Source File: test_notifications.py From Dallinger with MIT License | 6 votes |
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")
Example #5
Source File: smtpd.py From Imogen with MIT License | 6 votes |
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
Example #6
Source File: utils.py From server with MIT License | 6 votes |
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
Example #7
Source File: mailer.py From abusehelper with MIT License | 6 votes |
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
Example #8
Source File: mailer.py From abusehelper with MIT License | 6 votes |
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)
Example #9
Source File: models.py From linkedevents with MIT License | 6 votes |
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})
Example #10
Source File: signals.py From linkedevents with MIT License | 6 votes |
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})
Example #11
Source File: backend.py From lux with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #12
Source File: integrations.py From django-polaris with Apache License 2.0 | 6 votes |
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}")
Example #13
Source File: smtpd.py From ironpython3 with Apache License 2.0 | 6 votes |
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
Example #14
Source File: email.py From zentral with Apache License 2.0 | 6 votes |
def trigger(self, event, probe, action_config_d): email_from = self.config_d['email_from'] recipients = [] for group_name in action_config_d['groups']: for contact_d in contact_groups[group_name]: contact_email = contact_d.get('email', None) if contact_email: recipients.append(contact_email) if not recipients: return msg = MIMEText(event.get_notification_body(probe)) msg['Subject'] = ' - '.join(event.get_notification_subject(probe).splitlines()) msg['From'] = email_from msg['To'] = ",".join(recipients) try: self._open() self.conn.sendmail(email_from, recipients, msg.as_string()) self._close() except SMTPException: logger.exception("SMTP exception")
Example #15
Source File: test_signup.py From zulip with Apache License 2.0 | 6 votes |
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'), )
Example #16
Source File: mailer.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #17
Source File: admin.py From ANALYSE with GNU Affero General Public License v3.0 | 6 votes |
def send_admin_notification_callback(sender, **kwargs): """ Callback for notifying admin of a user in the 'pending' state. """ user = kwargs['user'] studio_request_email = settings.FEATURES.get('STUDIO_REQUEST_EMAIL', '') context = {'user_name': user.username, 'user_email': user.email} subject = render_to_string('emails/course_creator_admin_subject.txt', context) subject = ''.join(subject.splitlines()) message = render_to_string('emails/course_creator_admin_user_pending.txt', context) try: send_mail( subject, message, studio_request_email, [studio_request_email], fail_silently=False ) except SMTPException: log.warning("Failure sending 'pending state' e-mail for %s to %s", user.email, studio_request_email)
Example #18
Source File: test_signup.py From zulip with Apache License 2.0 | 6 votes |
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'), )
Example #19
Source File: test_email_plugin.py From apprise with MIT License | 6 votes |
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
Example #20
Source File: views.py From eventoL with GNU General Public License v3.0 | 6 votes |
def change_activity_status(request, event_slug, activity_id, status, justification=None): event = get_object_or_404(Event, event_slug=event_slug) activity = get_object_or_404(Activity, id=activity_id) activity.status = status activity.start_date = None activity.end_date = None activity.room = None activity.justification = justification activity.save() try: utils_email.send_activity_email(event, activity, justification) except SMTPException as error: logger.error(error) messages.error(request, _("The email couldn't sent successfully, \ please retry later or contact a organizer")) safe_continue = reverse("activity_detail", args=[event_slug, activity.pk]) return goto_next_or_continue(request.GET.get('next'), safe_continue)
Example #21
Source File: smtpconnection.py From smtp-email-spoofer-py with GNU General Public License v3.0 | 6 votes |
def login(self, username, password): try: return self.server.login(username, password) except smtplib.SMTPAuthenticationError: logger.error('The server did not accept the username/password combination.') return False except smtplib.SMTPNotSupportedError: logger.error('The AUTH command is not supported by the server.') exit(1) except smtplib.SMTPException: logger.error('Encountered an error during authentication.') exit(1)
Example #22
Source File: smtpd.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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
Example #23
Source File: regressiontest.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def send_email(msg): global SMTP_SERVER global SMTP_PORT global SMTP_TIMEOUT try: s = smtplib.SMTP(host=SMTP_SERVER, port=SMTP_PORT, timeout=SMTP_TIMEOUT) s.sendmail(FROM, TO, msg.as_string()) s.quit() # Catch all for SMTP exceptions except smtplib.SMTPException, e: print "Failure to send email: %s" % str(e)
Example #24
Source File: notifications.py From DLRN with Apache License 2.0 | 5 votes |
def sendnotifymail(packages, commit): config_options = getConfigOptions() details = copy.copy( [package for package in packages if package["name"] == commit.project_name][0]) email_to = details['maintainers'] if not config_options.smtpserver: logger.info("Skipping notify email to %r" % email_to) return details["logurl"] = "%s/%s" % (config_options.baseurl, commit.getshardedcommitdir()) # Render the notification template jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader([config_options.templatedir])) jinja_template = jinja_env.get_template("notification_email.j2") error_body = jinja_template.render(details=details) msg = MIMEText(error_body) msg['Subject'] = '[dlrn] %s master package build failed' % \ commit.project_name email_from = 'no-reply@delorean.com' msg['From'] = email_from msg['To'] = "packagers" logger.info("Sending notify email to %r" % email_to) try: s = smtplib.SMTP(config_options.smtpserver) s.sendmail(email_from, email_to, msg.as_string()) s.quit() except smtplib.SMTPException as e: logger.error("An issue occured when sending" "notify email to %r (%s)" % (email_to, e)) finally: s.close()
Example #25
Source File: mail.py From ctfscoreboard with Apache License 2.0 | 5 votes |
def _send_smtp(message, subject, to, to_name, sender, sender_name): """SMTP implementation of sending email.""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass
Example #26
Source File: utils.py From django-konfera with MIT License | 5 votes |
def send_email(addresses, subject, template_name, formatting_dict=None, **kwargs): formatting_dict = formatting_dict or {} template = get_email_template(template_name) text_template = getattr(template, 'text_template', '') html_template = getattr(template, 'html_template', '') if not text_template: logger.critical('Missing text template (required) for the input {}.'.format(text_template)) raise EmailTemplateError("Email template is not valid for the input.") if not html_template: logger.warning('Invalid html template (not required) for the input {}.'.format(html_template)) text_content = validate_email_template(text_template, formatting_dict) html_content = validate_email_template(html_template, formatting_dict, False) to = addresses.get('to', []) cc = addresses.get('cc', []) bcc = addresses.get('bcc', EMAIL_NOTIFY_BCC) msg = EmailMultiAlternatives(subject, text_content, to=to, cc=cc, bcc=bcc) if html_content: msg.attach_alternative(html_content, "text/html") try: msg.send() except (SMTPException, ConnectionRefusedError) as e: logger.critical('Sending email raised an exception: %s', e) else: # increase count on email_template template.add_count() if kwargs.get('verbose', 0) > 1: print(msg) return True
Example #27
Source File: regressiontest.py From NoobSec-Toolkit with GNU General Public License v2.0 | 5 votes |
def send_email(msg): global SMTP_SERVER global SMTP_PORT global SMTP_TIMEOUT try: s = smtplib.SMTP(host=SMTP_SERVER, port=SMTP_PORT, timeout=SMTP_TIMEOUT) s.sendmail(FROM, TO, msg.as_string()) s.quit() # Catch all for SMTP exceptions except smtplib.SMTPException, e: print "Failure to send email: %s" % str(e)
Example #28
Source File: elastalert.py From elastalert with Apache License 2.0 | 5 votes |
def send_notification_email(self, text='', exception=None, rule=None, subject=None, rule_file=None): email_body = text rule_name = None if rule: rule_name = rule['name'] elif rule_file: rule_name = rule_file if exception and rule_name: if not subject: subject = 'Uncaught exception in ElastAlert - %s' % (rule_name) email_body += '\n\n' email_body += 'The rule %s has raised an uncaught exception.\n\n' % (rule_name) if self.disable_rules_on_error: modified = ' or if the rule config file has been modified' if not self.args.pin_rules else '' email_body += 'It has been disabled and will be re-enabled when ElastAlert restarts%s.\n\n' % (modified) tb = traceback.format_exc() email_body += tb if isinstance(self.notify_email, str): self.notify_email = [self.notify_email] email = MIMEText(email_body) email['Subject'] = subject if subject else 'ElastAlert notification' recipients = self.notify_email if rule and rule.get('notify_email'): if isinstance(rule['notify_email'], str): rule['notify_email'] = [rule['notify_email']] recipients = recipients + rule['notify_email'] recipients = list(set(recipients)) email['To'] = ', '.join(recipients) email['From'] = self.from_addr email['Reply-To'] = self.conf.get('email_reply_to', email['To']) try: smtp = SMTP(self.smtp_host) smtp.sendmail(self.from_addr, recipients, email.as_string()) except (SMTPException, error) as e: self.handle_error('Error connecting to SMTP host: %s' % (e), {'email_body': email_body})
Example #29
Source File: email.py From alertlib with MIT License | 5 votes |
def _send_to_email(self, email_addresses, cc=None, bcc=None, sender=None): """An internal routine; email_addresses must be full addresses.""" # Make sure the email text ends in a single newline. message = self.message.rstrip('\n') + '\n' # Try using the sendgrid service first. try: self._send_to_sendgrid(message, email_addresses, cc, bcc, sender) return except (NameError, AssertionError) as why: pass # Then try sending via the appengine API. try: self._send_to_gae_email(message, email_addresses, cc, bcc, sender) return except (NameError, AssertionError) as why: pass # Finally, try using local smtp. try: self._send_to_sendmail(message, email_addresses, cc, bcc, sender) return except (NameError, smtplib.SMTPException) as why: pass logging.error('Failed sending email: %s' % why)
Example #30
Source File: test_smtpnet.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_connect_starttls(self): support.get_attribute(smtplib, 'SMTP_SSL') context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) with support.transient_internet(self.testServer): server = smtplib.SMTP(self.testServer, self.remotePort) try: server.starttls(context=context) except smtplib.SMTPException as e: if e.args[0] == 'STARTTLS extension not supported by server.': unittest.skip(e.args[0]) else: raise server.ehlo() server.quit()