第十二章:email-mailbox:管理email归档-imaplib:IMAP4客户库-连接服务器(认证失败)

13.4.2 连接服务器
要建立与一个IMAP服务器的连接,有2个步骤。首先,建立套接字连接本身。其次,用服务器上的一个账户认证为用户。下面的示例代码会从一个配置文件读取服务器和用户信息。

import imaplib
import configparser
import os

def open_connection(verbose=False):
    # Read the config file.
    config = configparser.ConfigParser()
    config.read([os.path.expanduser('~/.pymotw')])

    # Connect to the server.
    hostname = config.get('server','hostname')
    if verbose:
        print('Connecting to',hostname)
    connection = imaplib.IMAP4_SSL(hostname)

    # Log in to our account.
    username = config.get('account','username')
    password = config.get('account','password')
    if verbose:
        print('Logging in as',username)
    connection.login(username,password)
    return connection

if __name__ == '__main__':
    with open_connection(verbose=True) as c:
        print(c)

运行时,open_connection()从用户主目录中的一个文件读取配置信息,然后打开IMAP4_SSL连接并认证客户。

这一节的其他例子还会重用这个模块,以避免重复代码。

13.4.2.1 认证失败
如果建立了连接,但是认证失败,那么便会产生一个异常。

import imaplib
import configparser
import os

# Read the config file.
config = configparser.ConfigParser()
config.read([os.path.expanduser('~/.pymotw')])

# Connect to the server.
hostname = config.get('server','hostname')
print('Connecting to',hostname)
connection = imaplib.IMAP4_SSL(hostname)

# Log in to our account.
username = config.get('account','username')
password = 'this_is_the_wrong_password'
print('Logging in as',username)
try:
    connecton.login(username,password)
except Exception as err:
    print('ERROR:',err)

这个例子故意用错误的密码来触发这个异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值