Python smtplib.SMTPException() Examples

The following are 30 code examples for showing how to use smtplib.SMTPException(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module smtplib , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: smtp.py    License: GNU General Public License v2.0 7 votes vote down vote up
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
Project: linkedevents   Author: City-of-Helsinki   File: signals.py    License: MIT License 6 votes vote down vote up
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 3
Project: linkedevents   Author: City-of-Helsinki   File: models.py    License: MIT License 6 votes vote down vote up
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 4
Project: Dallinger   Author: Dallinger   File: test_notifications.py    License: MIT License 6 votes vote down vote up
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
Project: BikeMaps   Author: SPARLab   File: email.py    License: MIT License 6 votes vote down vote up
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 6
Project: server   Author: project-travel-mate   File: utils.py    License: MIT License 6 votes vote down vote up
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
Project: abusehelper   Author: abusesa   File: mailer.py    License: MIT License 6 votes vote down vote up
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
Project: abusehelper   Author: abusesa   File: mailer.py    License: MIT License 6 votes vote down vote up
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
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 6 votes vote down vote up
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 10
Project: zulip   Author: zulip   File: test_signup.py    License: Apache License 2.0 6 votes vote down vote up
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 11
Project: zulip   Author: zulip   File: test_signup.py    License: Apache License 2.0 6 votes vote down vote up
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 12
Project: apprise   Author: caronc   File: test_email_plugin.py    License: MIT License 6 votes vote down vote up
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 13
Project: Fluid-Designer   Author: Microvellum   File: smtpd.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: Imogen   Author: CedricGuillemet   File: smtpd.py    License: MIT License 6 votes vote down vote up
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 15
Project: lux   Author: quantmind   File: backend.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 16
Project: ironpython3   Author: IronLanguages   File: smtpd.py    License: Apache License 2.0 6 votes vote down vote up
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 17
Project: vthunting   Author: fr0gger   File: vthunting.py    License: MIT License 6 votes vote down vote up
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 18
Project: zentral   Author: zentralopensource   File: email.py    License: Apache License 2.0 6 votes vote down vote up
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 19
Project: ANALYSE   Author: jruiperezv   File: admin.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 20
Project: eventoL   Author: eventoL   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: Jtyoui   Author: jtyoui   File: qq.py    License: MIT License 5 votes vote down vote up
def send_qq_mail(from_addr, password, to_addr, content, subject='', files=None, host=('smtp.qq.com', 465)):
    """这个一个邮箱发送函数.默认是qq邮箱

    :param from_addr: 发送方邮箱
    :param password: 填入发送方邮箱的授权码
    :param to_addr: 收件人为多个收件人,通过;为间隔的字符串,比如: xx@qq.com;yy@qq.com
    :param content: 正文
    :param subject: 主题
    :param files: 附加
    :param host: 邮件传输协议
    :return: bool类型.打印成功和失败
    """
    text = MIMEText(content, _charset='utf-8')
    m = MIMEMultipart()
    if files:
        import os
        from email import encoders
        file_name = os.path.basename(files)  # 获得文件名字
        file = MIMEApplication(open(files, 'rb').read())
        file.add_header('Content-Disposition', 'attachment', filename=('GBK', '', file_name))
        encoders.encode_base64(file)  # 解决文件名乱码问题
        m.attach(file)
    m['Subject'] = subject
    m['From'] = from_addr
    m['To'] = to_addr
    m.attach(text)
    server = None
    try:
        server = smtplib.SMTP_SSL(*host)  # 安全模式
        server.login(from_addr, password)  # 登陆
        server.sendmail(from_addr, to_addr, m.as_string())  # 发送
        return True
    except smtplib.SMTPException as e:
        print(e)
        return False
    finally:
        if not server:
            server.quit()


# jfciwswgxlmedjei9 
Example 22
Project: GSIL   Author: FeeiCN   File: notification.py    License: GNU General Public License v3.0 5 votes vote down vote up
def notification(self, html):
        """
        Send notification use by mail
        :param html:
        :return:
        """
        # 随机挑选一个邮箱来发送,避免由于发送量过大导致被封
        mails = get('mail', 'mails').split(',')
        mail = random.choice(mails)
        msg = MIMEMultipart()
        msg['Subject'] = self.subject
        msg['From'] = '{0} <{1}>'.format(mail, get('mail', 'from'))
        # 支持多用户接收邮件
        msg['To'] = self.to
        msg['Cc'] = self.cc

        text = MIMEText(html, 'html', 'utf-8')
        msg.attach(text)
        host = get('mail', 'host').strip()
        port = get('mail', 'port').strip()

        try:
            if port == '465':
                port = int(port)
                s = smtplib.SMTP_SSL(host, port)
            else:
                s = smtplib.SMTP(host, port)
                s.ehlo()
                s.starttls()
            s.ehlo()
            s.login(mail, get('mail', 'password'))
            s.sendmail(mail, self.to.split(',')+self.cc.split(','), msg.as_string())
            s.quit()
            return True
        except SMTPException:
            logger.critical('Send mail failed')
            traceback.print_exc()
            return False 
Example 23
Project: GTDWeb   Author: lanbing510   File: smtp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def open(self):
        """
        Ensures we have a connection to the email server. Returns whether or
        not a new connection was required (True or False).
        """
        if self.connection:
            # Nothing to do if the connection is already open.
            return False

        connection_class = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP
        # If local_hostname is not specified, socket.getfqdn() gets used.
        # For performance, we use the cached FQDN for local_hostname.
        connection_params = {'local_hostname': DNS_NAME.get_fqdn()}
        if self.timeout is not None:
            connection_params['timeout'] = self.timeout
        if self.use_ssl:
            connection_params.update({
                'keyfile': self.ssl_keyfile,
                'certfile': self.ssl_certfile,
            })
        try:
            self.connection = connection_class(self.host, self.port, **connection_params)

            # TLS/SSL are mutually exclusive, so only attempt TLS over
            # non-secure connections.
            if not self.use_ssl and self.use_tls:
                self.connection.ehlo()
                self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile)
                self.connection.ehlo()
            if self.username and self.password:
                self.connection.login(self.username, self.password)
            return True
        except smtplib.SMTPException:
            if not self.fail_silently:
                raise 
Example 24
Project: GTDWeb   Author: lanbing510   File: smtp.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _send(self, 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:
            self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
        except smtplib.SMTPException:
            if not self.fail_silently:
                raise
            return False
        return True 
Example 25
Project: king-phisher   Author: rsmusllp   File: mailer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 26
Project: atomic-reactor   Author: containerbuildsystem   File: exit_sendmail.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _send_mail(self, receivers_list, subject, body, log_files=None):
        """Sends a mail with `subject` and `body` and optional log_file attachments
        to all members of `receivers_list`."""
        if not receivers_list:
            self.log.info('no valid addresses in requested addresses. Doing nothing')
            return

        self.log.info('sending notification to %s ...', receivers_list)

        if log_files:
            msg = MIMEMultipart()
            msg.attach(MIMEText(body))
            for entry in log_files:
                log_mime = MIMEBase('application', "octet-stream")
                log_file = entry[0]  # Output.file
                log_file.seek(0)
                log_mime.set_payload(log_file.read())
                encoders.encode_base64(log_mime)
                log_mime.add_header('Content-Disposition',
                                    'attachment; filename="{}"'.format(entry[1]['filename']))
                msg.attach(log_mime)
        else:
            msg = MIMEText(body)
        msg['Subject'] = subject
        msg['From'] = self.from_address
        msg['To'] = ', '.join([x.strip() for x in receivers_list])

        s = None
        try:
            s = get_smtp_session(self.workflow, self.smtp_fallback)
            s.sendmail(self.from_address, receivers_list, msg.as_string())
        except (socket.gaierror, smtplib.SMTPException):
            self.log.error('Error communicating with SMTP server')
            raise
        finally:
            if s is not None:
                s.quit() 
Example 27
Project: atomic-reactor   Author: containerbuildsystem   File: test_sendmail.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_send_mail(self, throws_exception):
        class WF(object):
            exit_results = {}
            plugin_workspace = {}

        workflow = WF()
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {}

        smtp_map = {
            'from_address': 'foo@bar.com',
            'host': 'smtp.bar.com',
        }
        workflow.plugin_workspace[ReactorConfigPlugin.key] = {}
        workflow.plugin_workspace[ReactorConfigPlugin.key][WORKSPACE_CONF_KEY] =\
            ReactorConfig({'version': 1, 'smtp': smtp_map})
        add_koji_map_in_workflow(workflow, hub_url='/', root_url='',
                                 ssl_certs_dir='/certs')

        p = SendMailPlugin(None, workflow, from_address='foo@bar.com', smtp_host='smtp.spam.com')

        class SMTP(object):
            def sendmail(self, from_addr, to, msg):
                pass

            def quit(self):
                pass

        smtp_inst = SMTP()
        flexmock(smtplib).should_receive('SMTP').and_return(smtp_inst)
        sendmail_chain = (flexmock(smtp_inst).should_receive('sendmail').
                          with_args('foo@bar.com', ['spam@spam.com'], str))
        if throws_exception:
            sendmail_chain.and_raise(smtplib.SMTPException, "foo")
        flexmock(smtp_inst).should_receive('quit')

        if throws_exception:
            with pytest.raises(SMTPException) as e:
                p._send_mail(['spam@spam.com'], 'subject', 'body')
            assert str(e.value) == 'foo'
        else:
            p._send_mail(['spam@spam.com'], 'subject', 'body') 
Example 28
Project: WLANThermo_v2   Author: WLANThermo   File: wlt_2_comp.py    License: GNU General Public License v3.0 5 votes vote down vote up
def alarm_email(SERVER,USER,PASSWORT,STARTTLS,FROM,TO,SUBJECT,MESSAGE):
    logger.info(u'Send mail!')
    
    from smtplib import SMTP 
    from smtplib import SMTPException 
    from email.mime.text import MIMEText as text
    if STARTTLS:
        port=587
    else:
        port=25
    try:
        s = SMTP(SERVER,port)
        if STARTTLS:
            s.starttls()
        
        s.login(USER,PASSWORT)
        

        m = text(MESSAGE, 'plain', 'UTF-8')

        m['Subject'] = SUBJECT
        m['From'] = FROM
        m['To'] = TO


        s.sendmail(FROM,TO, m.as_string())
        s.quit()
        logger.debug(u'Alert Email has been sent!')
    except SMTPException as error:
        sendefehler = u'Error: unable to send email: {err}'.format(err=error)
        logger.error(sendefehler)
    except:
        #TODO err undefined!
        sendefehler = u'Error: unable to resolve host (no internet connection?) :  {err}'
        logger.error(sendefehler) 
Example 29
Project: sndlatr   Author: Schibum   File: gmail.py    License: Apache License 2.0 5 votes vote down vote up
def safe_smtp_quit(self, smtp):
        try:
            smtp.quit()
        except (smtplib.SMTPException, IOError):
            logging.warn('error during smtp.quit(), ignoring', exc_info=True)
            # ignore
            pass 
Example 30
Project: privacyidea   Author: privacyidea   File: test_lib_smtpserver.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_02_send_email(self):
        r = add_smtpserver(identifier="myserver", server="1.2.3.4", tls=False)
        self.assertTrue(r > 0)

        with self.assertRaises(ResourceNotFoundError):
            get_smtpserver(None)

        server = get_smtpserver("myserver")
        smtpmock.setdata(response={"recp@example.com": (200, "OK")},
                         support_tls=False)
        r = server.send_email(["recp@example.com"], "Hallo", "Body")
        self.assertEqual(r, True)

        smtpmock.setdata(response={"recp@example.com": (550,
                                                        "Message rejected")},
                         support_tls=False)
        r = server.send_email(["recp@example.com"], "Hallo", "Body")
        self.assertEqual(r, False)

        # Use TLS
        r = add_smtpserver(identifier="myserver", server="1.2.3.4", tls=True)
        self.assertTrue(r > 0)
        server = get_smtpserver("myserver")
        smtpmock.setdata(response={"recp@example.com": (200, "OK")},
                         support_tls=True)
        r = server.send_email(["recp@example.com"], "Hallo", "Body")
        self.assertEqual(r, True)

        # If we configure TLS but the server does not support this, we raise
        # an error
        smtpmock.setdata(response={"recp@example.com": (200, "OK")},
                         support_tls=False)
        self.assertRaises(SMTPException, server.send_email,
                          ["recp@example.com"], "Hallo", "Body")

        delete_smtpserver("myserver")