Python smtplib 模块,SMTPSenderRefused() 实例源码

我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用smtplib.SMTPSenderRefused()

项目:notifiers    作者:liiight    | 项目源码 | 文件源码
def _send_notification(self, data: dict) -> Response:
        response_data = {
            'provider_name': self.provider_name,
            'data': data
        }
        try:
            configuration = self._get_configuration(data)
            if not self.configuration or not self.smtp_server or self.configuration != configuration:
                self._connect_to_server(data)
            email = self._build_email(data)
            self.smtp_server.sendmail(data['from'], data['to'], email.as_string())
        except (
                SMTPServerDisconnected, SMTPSenderRefused, socket.error, OSError, IOError, SMTPAuthenticationError
        ) as e:
            response_data['errors'] = [str(e)]
        return create_response(**response_data)
项目:TCP-IP    作者:JackZ0    | 项目源码 | 文件源码
def notify(subject, whom, what):
    """Send email notification.

    Try to notify the addressee (``whom``) by e-mail, with Subject:
    defined by ``subject`` and message body by ``what``.

    """
    msg = email.message_from_string(what)
    msg.add_header("From", "Certbot renewal agent <root>")
    msg.add_header("To", whom)
    msg.add_header("Subject", subject)
    msg = msg.as_string()
    try:
        lmtp = smtplib.LMTP()
        lmtp.connect()
        lmtp.sendmail("root", [whom], msg)
    except (smtplib.SMTPHeloError, smtplib.SMTPRecipientsRefused,
            smtplib.SMTPSenderRefused, smtplib.SMTPDataError, socket.error):
        # We should try using /usr/sbin/sendmail in this case
        try:
            proc = subprocess.Popen(["/usr/sbin/sendmail", "-t"],
                                    stdin=subprocess.PIPE)
            proc.communicate(msg)
        except OSError:
            return False
    return True
项目:certbot    作者:nikoloskii    | 项目源码 | 文件源码
def notify(subject, whom, what):
    """Send email notification.

    Try to notify the addressee (``whom``) by e-mail, with Subject:
    defined by ``subject`` and message body by ``what``.

    """
    msg = email.message_from_string(what)
    msg.add_header("From", "Certbot renewal agent <root>")
    msg.add_header("To", whom)
    msg.add_header("Subject", subject)
    msg = msg.as_string()
    try:
        lmtp = smtplib.LMTP()
        lmtp.connect()
        lmtp.sendmail("root", [whom], msg)
    except (smtplib.SMTPHeloError, smtplib.SMTPRecipientsRefused,
            smtplib.SMTPSenderRefused, smtplib.SMTPDataError, socket.error):
        # We should try using /usr/sbin/sendmail in this case
        try:
            proc = subprocess.Popen(["/usr/sbin/sendmail", "-t"],
                                    stdin=subprocess.PIPE)
            proc.communicate(msg)
        except OSError:
            return False
    return True
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test__rest_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '451 Requested action aborted'
        self.serv._SMTPchannel.disconnect = True
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)

    # Issue 5713: make sure close, not rset, is called if we get a 421 error
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_421_from_mail_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.mail_response = '421 closing connection'
        with self.assertRaises(smtplib.SMTPSenderRefused):
            smtp.sendmail('John', 'Sally', 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
项目:cobra    作者:wufeifei    | 项目源码 | 文件源码
def send_mail(target, filename, receiver):
    host = Config('email', 'host').value
    port = Config('email', 'port').value
    username = Config('email', 'username').value
    password = Config('email', 'password').value
    sender = Config('email', 'sender').value
    is_ssl = to_bool(Config('email', 'ssl').value)

    if is_ssl:
        server = smtplib.SMTP_SSL(host=host, port=port)
    else:
        server = smtplib.SMTP(host=host, port=port)

    s_sid = filename.split('.')[0]
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = '?? {sid} ?? Cobra ????'.format(sid=s_sid)

    msg.attach(MIMEText('?????{t}\n?????'.format(t=target), 'plain', 'utf-8'))

    with open(filename, 'rb') as f:
        attachment = MIMEApplication(f.read())
        attachment.add_header('Content-Disposition', 'attachment', filename=os.path.split(filename)[1])
        msg.attach(attachment)

    try:
        server.login(user=username, password=password)
        server.sendmail(from_addr=sender, to_addrs=receiver, msg=msg.as_string())
        server.quit()
        logger.info('[EMAIL] Email delivered successfully.')
        return True
    except smtplib.SMTPRecipientsRefused:
        logger.critical('[EMAIL] Email delivery rejected.')
        return False
    except smtplib.SMTPAuthenticationError:
        logger.critical('[EMAIL] SMTP authentication error.')
        return False
    except smtplib.SMTPSenderRefused:
        logger.critical('[EMAIL] SMTP sender refused.')
        return False
    except smtplib.SMTPException as error:
        logger.critical(error)
        return False
项目:mes    作者:osess    | 项目源码 | 文件源码
def send_all():
    """
    Send all eligible messages in the queue.
    """

    lock = FileLock("send_mail")

    logging.debug("acquiring lock...")
    try:
        lock.acquire(LOCK_WAIT_TIMEOUT)
    except AlreadyLocked:
        logging.debug("lock already in place. quitting.")
        return
    except LockTimeout:
        logging.debug("waiting for the lock timed out. quitting.")
        return
    logging.debug("acquired.")

    start_time = time.time()

    dont_send = 0
    deferred = 0
    sent = 0

    try:
        for message in prioritize():
            if DontSendEntry.objects.has_address(message.to_address):
                logging.info("skipping email to %s as on don't send list " % message.to_address.encode("utf-8"))
                MessageLog.objects.log(message, 2) # @@@ avoid using literal result code
                message.delete()
                dont_send += 1
            else:
                try:
                    logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8")))
                    core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address])
                    MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
                    message.delete()
                    sent += 1
                except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err:
                    message.defer()
                    logging.info("message deferred due to failure: %s" % err)
                    MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
                    deferred += 1
    finally:
        logging.debug("releasing lock...")
        lock.release()
        logging.debug("released.")

    logging.info("")
    logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send))
    logging.info("done in %.2f seconds" % (time.time() - start_time))
项目:authserver    作者:jdelic    | 项目源码 | 文件源码
def sendmail(self, from_addr: str, to_addrs: Sequence[str], msg: bytes, mail_options: List[str]=[],
                 rcpt_options: List[str]=[]) -> Union[str, None]:
        """
        Wraps smtplib.sendmail and handles all the exceptions it can throw.
        :return: a SMTP return string or None
        """
        with smtplib.SMTP(self.external_ip, self.external_port) as smtp:
            try:
                smtp.sendmail(from_addr, to_addrs, msg, mail_options, rcpt_options)
            except smtplib.SMTPSenderRefused as e:
                if isinstance(e.smtp_error, bytes):
                    errorstr = e.smtp_error.decode("utf-8", errors="ignore")
                else:
                    errorstr = str(e.smtp_error)
                _log.info("Downstream server refused sender: %s (%s %s)", e.sender, e.smtp_code, errorstr)
                return "%s %s" % (e.smtp_code, e.smtp_error)
            except smtplib.SMTPResponseException as e:
                # This exception baseclass is for all exceptions that have a SMTP response code.
                # Return the downstream error code upstream
                if isinstance(e.smtp_error, bytes):
                    errorstr = e.smtp_error.decode("utf-8", errors="ignore")
                else:
                    errorstr = str(e.smtp_error)
                _log.info("Unexpected response from server (passed upstream): %s %s", e.smtp_code, errorstr)
                return "%s %s" % (e.smtp_code, errorstr)
            except smtplib.SMTPRecipientsRefused as e:
                _log.info("Some recipients where refused by the downstream server: %s", ", ".join(e.recipients.keys()))
                if self.internal_ip and self.internal_port:
                    with smtplib.SMTP(self.internal_ip, self.internal_port) as smtp_r:
                        try:
                            smtp_r.sendmail(
                                "<>",
                                [from_addr],
                                self._format_denied_recipients(msg, list(e.recipients.keys()))
                            )
                        except smtplib.SMTPException as ex:
                            _log.exception("Error while sending denied recipients reply: %s", str(ex))
                return None
            except smtplib.SMTPServerDisconnected as e:
                _log.info("Downstream server unexpectedly disconnected: %s", str(e))
                return "421 Possible network problem. Please try again."
            return None


# patch the SMTP channel implementation to pass us a reference to the channel
# and use sane logging
项目:idealoom    作者:conversence    | 项目源码 | 文件源码
def process_notification(notification):
    from ..models.notification import (
        NotificationDeliveryStateType, UnverifiedEmailException,
        MissingEmailException)
    import smtplib
    import socket
    from assembl.lib import config

    assert notification
    sys.stderr.write(
        "process_notification called with notification %d, state was %s" % (
            notification.id, notification.delivery_state))
    if notification.delivery_state not in \
            NotificationDeliveryStateType.getRetryableDeliveryStates():
        sys.stderr.write(
            "Refusing to process notification %d because its delivery state is: %s" % (
                notification.id, notification.delivery_state))
        return
    try:
        email = notification.render_to_message()
        # sys.stderr.write(email_str)
        recipient = notification.get_to_email_address()
        wait_if_necessary(recipient)
        notify_process_mailer.send_immediately(email, fail_silently=False)

        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_IN_PROGRESS
        email_was_sent(recipient)
    except UnverifiedEmailException as e:
        sys.stderr.write("Not sending to unverified email: "+repr(e))
        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_TEMPORARY_FAILURE
    except MissingEmailException as e:
        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_TEMPORARY_FAILURE
        sys.stderr.write("Missing email! :"+repr(e))
    except (smtplib.SMTPConnectError,
            socket.timeout, socket.error,
            smtplib.SMTPHeloError) as e:
        sys.stderr.write("Temporary failure: "+repr(e))
        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_TEMPORARY_FAILURE
    except smtplib.SMTPRecipientsRefused as e:
        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_FAILURE
        sys.stderr.write("Recepients refused: "+repr(e))
    except smtplib.SMTPSenderRefused as e:
        notification.delivery_state = \
            NotificationDeliveryStateType.DELIVERY_TEMPORARY_FAILURE
        sys.stderr.write("Invalid configuration! :"+repr(e))

    mark_changed()
    sys.stderr.write(
        "process_notification finished processing %d, state is now %s"
        % (notification.id, notification.delivery_state))