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

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

项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:gitwatch    作者:datamachines    | 项目源码 | 文件源码
def send_smtp_email(email_to, email_subject, email_body):
    logtime = datetime.now().isoformat()
    num_recepients = len(email_to)
    if num_recepients > conf['smtp_max_recepients_per_email']:
        print(logtime, 'ERROR - Too many recepients.')
        return 0
    msg = MIMEText(email_body, 'html')
    msg['Subject'] = email_subject
    msg['From'] = conf['smtp_from']
    msg['To'] = ','.join(email_to)
    email_message = msg.as_string()
    try:
        smtp = smtplib.SMTP_SSL()
        smtp.connect(conf['smtp_server'],int(conf['smtp_port']))
        smtp.login(conf['smtp_username'], conf['smtp_password'])
        smtp.sendmail(conf['smtp_from'], email_to, email_message)
        smtp.close()
        log("Emails sent to: " + msg['to'])
    except smtplib.SMTPConnectError:
        log("ERROR - Unable to connect to SMTP server.")
        return 0
    except smtplib.SMTPAuthenticationError:
        log("ERROR - SMTP authentication error.")
        return 0
    return 1

###############################################################################
# Program start

# Set up configuraiton
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:ctfscoreboard    作者:google    | 项目源码 | 文件源码
def send(message, subject, to, to_name=None, sender=None, sender_name=None):
    sender = sender or app.config.get('MAIL_FROM')
    sender_name = sender_name or app.config.get('MAIL_FROM_NAME')
    host = app.config.get('MAIL_HOST')

    try:
        server = smtplib.SMTP(host)
    except smtplib.SMTPConnectError as ex:
        app.logger.error('Unable to send mail: %s', str(ex))
        raise MailFailure()

    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 as ex:
        app.logger.error('Unable to send mail: %s', str(ex))
        raise MailFailure()
    finally:
        try:
            server.quit()
        except smtplib.SMTPException:
            pass
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def testFailingHELO(self):
        self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
                            HOST, self.port, 'localhost', 3)
项目:SPF    作者:Exploit-install    | 项目源码 | 文件源码
def validate_email_address(email_to, email_from, debug=False):
    # find the appropiate mail server
    domain = email_to.split('@')[1]
    remote_server = get_mx_record(domain)

    if (remote_server is None):
        print "No valid email server could be found for [%s]!" % (email_to)
        return False

    # Login into the mail exchange server
    try:
        smtp = smtplib.SMTP()
        smtp.connect(remote_server)
        if debug:
            smtp.set_debuglevel(True)
    except smtplib.SMTPConnectError, e:
        print e
        return False

    try:
        smtp.ehlo_or_helo_if_needed()
    except Exception, e:
        print e
        return False

    # First Try to verify with VRFY
    # 250 is success code. 400 or greater is error.
    v_code, v_message = smtp.verify(email_to)
    if v_code and v_code != 250:
        f_code, f_message = smtp.mail(email_from)
        # Then use RCPT to verify
        if f_code and f_code == 250:
            r_code, r_message = smtp.rcpt(email_to)
            if r_code and r_code == 250:
                return True, r_message
            if r_code and r_code == 550:
                return False, r_message
        else:
            return False
    else:
        return True, v_message

    smtp.quit()
    return False
项目:grical    作者:wikical    | 项目源码 | 文件源码
def notify_users_when_wanted( event = None ):
    """ notifies users if *event* matches a filter of a user and the
    user wants to be notified for the matching filter """
    from grical.events.models import Event, Filter
    if isinstance(event, Event):
        pass
    elif isinstance(event, int) or isinstance(event, long):
        event = Event.objects.get(pk = event)
    else:
        event = Event.objects.get(pk = int(event))
    # TODO: the next code iterate throw all users but this is not workable
    # for a big number of users: implement a special data structure which
    # saves filters and can look up fast filters matching an event
    # TODO: show a diff of the changes
    users = User.objects.all()
    for user in users:
        user_filters = Filter.objects.filter( user = user ).filter(
                email = True)
        for fil in user_filters:
            if not fil.matches_event( event ):
                continue
            context = {
                'username': user.username,
                'event': event,
                'filter': fil,
                'site_name': Site.objects.get_current().name,
                'site_domain': Site.objects.get_current().domain, }
            # TODO: create the subject from a text template
            subject = _(u'filter match: ') + event.title
            # TODO: use a preferred language setting for users to send
            # emails to them in this language
            message = render_to_string( 'mail/event_notice.txt', context )
            from_email = settings.DEFAULT_FROM_EMAIL
            if subject and message and from_email and user.email:
                try:
                    if ( not settings.DEBUG ) or user.username in \
                            settings.USERNAMES_TO_MAIL_WHEN_DEBUGGING:
                        send_mail( subject, message, from_email,
                            [user.email,], fail_silently = False )
                except (BadHeaderError, SMTPConnectError), err:
                    logger.error(u'SMTP error while trying to send '
                            'notificationsemail - %s'%err)
                except:
                    logger.error(u'Unexpected error while trying to send '
                            'notifications - %s'%traceback.format_exc())
            else:
                # FIXME: do something meaningfull, e.g. error log
                pass
项目:vit_acad_web_api    作者:piyushrungta25    | 项目源码 | 文件源码
def send_mail(subject,body,reciever):


    with open(config_file) as fp:
        lines = fp.readlines()
    first_line_to_read = [i for i, line in enumerate(lines) if 'MAILING_DETAILS:' in line][0] + 1
    last_line_to_read = [i for i, line in enumerate(lines) if 'EOF' in line][0]

    for name in lines[first_line_to_read:last_line_to_read]:
        name=name.split(':')
        if name[0]=='SENDER_USERNAME':
            sender=name[1].split('\n')[0]
        elif name[0]=='SENDER_PASS':
            password=name[1].split('\n')[0]

    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = reciever
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))


    try:
        smtpObj = smtplib.SMTP('smtp.gmail.com:587')
        smtpObj.starttls()
        smtpObj.login(sender,password)
        smtpObj.sendmail(sender, reciever, msg.as_string())

    except smtplib.SMTPConnectError:
        msg='Mailing Error : error occured during connection with server.'


    except smtplib.SMTPAuthenticationError:
        msg='Mailing Error: Invalid username and/or password'


    except smtplib.socket.gaierror:
        msg='Mailing Error : Check Internet connection.'

    except Exception as e:
        msg='Mailing Error: Try again'

    else:
        msg="Admin has been successfully notified of the error via email."
        smtpObj.quit()
项目: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))