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)
这个例子故意用错误的密码来触发这个异常。