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

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

项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def send(self, request):
        if (not self.last_email) or self.last_email + timedelta(hours=12) < now():  # TODO: TIMEDELTA mit config
            old_lang = translation.get_language()
            translation.activate(self.user.language)
            link = reverse('poll_vote', args=(self.poll.url,))  # TODO: hier direkt das poll oder das Vote?
            email_content = render_to_string('invitations/mail_invite.txt', {
                'receiver': self.user.username,
                'creator': self.creator.username,
                'link': link
            })
            try:
                send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email])
                self.last_email = now()
                self.save()
            except SMTPRecipientsRefused:
                translation.activate(old_lang)
                messages.error(
                    request, _("The mail server had an error sending the notification to {}".format(self.user.username))
                )
            translation.activate(old_lang)
        else:
            messages.error(
                request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username))
            )
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def _send_mail_or_error_page(subject, content, address, request):
    try:
        send_mail(subject, content, None, [address])
        if settings.DEBUG:
            print(u"VALIDATION MAIL to {0}\nSubject: {1}\n{2}".format(
                address, subject, content))
    except SMTPRecipientsRefused as e:
        wrong_email, (error_code, error_msg) = e.recipients.items()[0]
        unknown = 'User unknown' in error_msg
        if not unknown:
            error_email_content = u'{0}: {1}'.format(e.__class__.__name__,
                                                     repr(e.recipients))
            send_mail(
                    _('Registration: Sending mail failed: {}'.format(address)),
                    error_email_content,
                    None,
                    [settings.TEAM_EMAIL])
        return TemplateResponse(request, 'registration/email_error.html', {
            'unknown': unknown,
            'error_code': error_code,
            'error_msg': error_msg,
            'recipient': wrong_email
        })

    return redirect('registration_request_successful', address)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def send_rfc822(self, rfc822_mail):
        """
        Send rfc822 mail as fetched via imap. To and from addresses are
        extracted from the rfc822 envolope.
        Returns the rfc message id of the sent message.
        """
        rewriter = MailSendRewriter(rfc822_mail)
        receivers = rewriter.get_receivers()
        rewriter.rewrite()
        if not receivers:
            raise InvalidEmail('no to address')
            # TODO: check for any rejected recepient. Fail if any fails?
        try:
            self.client.sendmail(rewriter.get_from(), receivers,
                                 rewriter.message_as_str())
        except smtplib.SMTPRecipientsRefused:
            raise InvalidEmail('server rejected recepients')
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:baobab.lims    作者:SANBI-SA    | 项目源码 | 文件源码
def send_mail(self, sender, receiver, subject="", body=""):
        """Send email from sender to receiver
        """
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = sender
        mime_msg['To'] = receiver
        msg_txt = MIMEText(body, 'plain')
        mime_msg.attach(msg_txt)
        try:
            host = getToolByName(self, 'MailHost')
            host.send(mime_msg.as_string(), immediate=True)
        except SMTPServerDisconnected as msg:
            logger.warn("SMTPServerDisconnected: %s." % msg)
        except SMTPRecipientsRefused as msg:
            raise WorkflowException(str(msg))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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 (socket.error, 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
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:opskins_bot    作者:craked5    | 项目源码 | 文件源码
def send_email_new_item(self, FROM, TO, TEXT, item_name):

        SUBJECT = 'New potencial item: %s' % item_name
        try:
            message = """\From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
            self.server.sendmail(FROM, TO, message)
            self.email_number += 1
            print 'Email number '+ str(self.email_number) + ' was sent for the item ' + item_name

        except smtplib.SMTPRecipientsRefused:
            print 'The email was not sent, the target refused'
            return False
        except smtplib.SMTPServerDisconnected:
            print 'The server is disconnected.'
            return False
        except:
            print 'SHIT HAPPENED DEAL WITH IT'
            return False
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:aiosmtpd    作者:aio-libs    | 项目源码 | 文件源码
def _deliver(self, mail_from, rcpt_tos, data):
        refused = {}
        try:
            s = smtplib.SMTP()
            s.connect(self._hostname, self._port)
            try:
                refused = s.sendmail(mail_from, rcpt_tos, data)
            finally:
                s.quit()
        except smtplib.SMTPRecipientsRefused as e:
            log.info('got SMTPRecipientsRefused')
            refused = e.recipients
        except (OSError, smtplib.SMTPException) as e:
            log.exception('got %s', e.__class__)
            # 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 rcpt_tos:
                refused[r] = (errcode, errmsg)
        return refused
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
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, e:
            print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
            refused = e.recipients
        except (socket.error, smtplib.SMTPException), e:
            print >> DEBUGSTREAM, 'got', e.__class__
            # 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
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def send(self, request, vote: Vote):
        old_lang = translation.get_language()
        translation.activate(self.user.language)
        link = reverse('poll', args=(self.poll.url,))
        if vote.anonymous:
            username = _("Annonymus")
        elif vote.user:
            username = vote.user.username
        else:
            username = vote.name
        email_content = render_to_string('poll/mail_watch.txt', {
            'receiver': self.user.username,
            'user': username if self.poll.show_results == "complete" else _("by an user"),
            'poll': self.poll.title,
            'link': link,
            'hide_participants': self.poll.hide_participants  # TODO: simplify merge with usernameshadowing above
        })
        try:
            send_mail(_("New votes for {}".format(self.poll.title)), email_content, None,
                      [self.user.email])
        except SMTPRecipientsRefused:
            translation.activate(old_lang)
            messages.error(
                request, _("The mail server had an error sending the notification to {}".format(
                    self.user.username))
            )
        translation.activate(old_lang)
项目: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_rcpt_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
        with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
            smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
        self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_421_from_rcpt_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
        with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
            smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
        self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
项目:nav    作者:UNINETT    | 项目源码 | 文件源码
def send(self, address, alert, language='en'):
        message = self.get_message(alert, language, 'email')

        # Extract the subject
        subject = message.splitlines(1)[0].lstrip('Subject:').strip()
        # Remove the subject line
        message = '\n'.join(message.splitlines()[1:])

        headers = {
            'X-NAV-alert-netbox': alert.netbox,
            'X-NAV-alert-device': alert.device,
            'X-NAV-alert-subsystem': alert.source,
        }

        try:
            if not address.DEBUG_MODE:
                email = EmailMessage(subject=subject, body=message,
                                     to=[address.address])
                email.send(fail_silently=False)
            else:
                _logger.debug('alert %d: In testing mode, would have sent '
                              'email to %s', alert.id, address.address)

        except SMTPException as err:
            msg = 'Could not send email: %s" ' % err
            if (isinstance(err, SMTPRecipientsRefused) or
                (hasattr(err, "smtp_code") and
                 str(err.smtp_code).startswith('5'))):
                raise FatalDispatcherException(msg)

            # Reraise as DispatcherException so that we can catch it further up
            raise DispatcherException(msg)
项目:PythonGuru    作者:aronekob34    | 项目源码 | 文件源码
def send_mail(subject_template_name, email_template_name, to_email, context=None,
              html_email_template_name=None, from_email=settings.DEFAULT_FROM_EMAIL,
              bcc=None, connection=None):

    try:
        subject = loader.render_to_string(subject_template_name, context)
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        if not isinstance(to_email, list):
            to_email = [to_email]

        if settings.DEBUG and settings.LIVE_EMAIL:

            email_message = EmailMultiAlternatives(
                subject, body, from_email, [settings.RECIPIENT_TEST_EMAIL], connection=connection
            )

        else:

            email_message = EmailMultiAlternatives(
                subject, body, from_email, to_email, bcc, connection=connection
            )

        if settings.TEST_TEXT_EMAIL:
            email_message.send()

        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()

    except SMTPRecipientsRefused as e:
        logger.error(e)

    except Exception as e:
        message = 'Failed to send email to {}, Subject: {}, Exception: {}'.format(
            to_email, subject_template_name, e)
        logger.exception(message)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_421_from_rcpt_cmd(self):
        smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
        smtp.noop()
        self.serv._SMTPchannel.rcpt_response = ['250 accepted', '421 closing']
        with self.assertRaises(smtplib.SMTPRecipientsRefused) as r:
            smtp.sendmail('John', ['Sally', 'Frank', 'George'], 'test message')
        self.assertIsNone(smtp.sock)
        self.assertEqual(self.serv._SMTPchannel.rset_count, 0)
        self.assertDictEqual(r.exception.args[0], {'Frank': (421, b'closing')})
项目:tvgrabpyAPI    作者:tvgrabbers    | 项目源码 | 文件源码
def send_mail(self, message, mail_address, subject=None):
        try:
            if isinstance(message, (list,tuple)):
                msg = u''.join(message)

            elif isinstance(message, (str,unicode)):
                msg = unicode(message)

            else:
                return

            if subject == None:
                subject = 'Tv_grab_nl3_py %s' % datetime.datetime.now().strftime('%Y-%m-%d %H:%M')

            msg = MIMEText(msg, _charset='utf-8')
            msg['Subject'] = subject
            msg['From'] = mail_address
            msg['To'] = mail_address
            try:
                mail = smtplib.SMTP(self.config.opt_dict['mailserver'], self.config.opt_dict['mailport'])

            except:
                sys.stderr.write(('Error mailing message: %s\n' % sys.exc_info()[1]).encode(self.local_encoding, 'replace'))
                return

            mail.sendmail(mail_address, mail_address, msg.as_string())

        except smtplib.SMTPRecipientsRefused:
            sys.stderr.write(('The mailserver at %s refused the message\n' % self.config.opt_dict['mailserver']).encode(self.local_encoding, 'replace'))

        except:
            sys.stderr.write('Error mailing message\n'.encode(self.local_encoding, 'replace'))
            sys.stderr.write(traceback.format_exc())

        mail.quit()
    # send_mail()

# end Logging
项目: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))