13.4.12 移动和复制消息
一旦消息上传到服务器,便可以分别使用move()或copy()来移动或复制,而无须下载。与fetch()一样,这些方法可以处理消息ID区间。
import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
# Find the "SEEN" messages in INBOX.
c.select('INBOX')
typ,[response] = c.search(None,'SEEN')
if typ != 'OK':
raise RuntimeError(response)
msg_ids = ','.join(response.decode('utf-8').split(' '))
# Create a new mailbox,"Example.Today".
typ,create_response = c.create('Example.Today')
print('CREATED Example.Today:',create_response)
# Copy the messages.
print('COPYING:',msg_ids)
c.copy(msg_ids,'Example.Today')
# Look at the results.
c.select('Example.Today')
typ,[response] = c.search(None,'ALL')
print('COPIED:',response)
这个示例脚本在Example下创建一个新的邮箱,并把已读消息从INBOX复制到这个邮箱。
再次运行这个脚本,可以看出检查返回码的重要性。这里调用create()创建新邮箱时没有产生一个异常,而是会报告这个邮箱已经存在。