读取邮件向imaplib 传递一个消息ID的列表。为了提取的是邮箱的主题,将字符串(BODY[HEADER.FIELDS(SUBJECT)]) 作为参数传递给imaplib
1 from imaplib import IMAP4 2 3 class SubjectLister(IMAP4): 4 def __init__(self, server, username, password): 5 IMAP4.__init__(self, server) 6 self.login(username, password) 7 8 def summarize(self, mailbox='cxiaoln'): 9 numberOfMessages = int(self._result(self.select(mailbox)))10 print ('%s message(s) in mailbox "%s":'%(numberOfMessages, mailbox))11 subjects = self._result(self.fetch('1:%d'% numberOfMessages, '(BODY[HEADER.FIELDS (SUBJECT)])'))12 for subject in subjects:13 if hasattr(subject, '__iter__'):14 subject = subject[1]15 print('', subject[:subject.find('\n')])16 17 def _result(self, result):18 status, result = result19 if status != 'OK':20 raise status(result)21 if len(result) == 1:22 result = result[0]23 return result24 25 if __name__ == '__main__':26 lister = SubjectLister('imap.163.com', 'user', 'password')27 lister.summarize()
这里的第一件事就是完成服务器的链接,然后选择邮箱中的文件夹。
由于同步的问题,这里减少了风险:self.fetch('1:%d'% numberOfMessages, '(BODY[HEADER.FIELDS (SUBJECT)])')
使用唯一ID提取消息
imap = imaplib.IMAP4('imap.163.com')
imap.login('username', 'password')
imap.select('cxiaoln')[1][0] # 选择邮箱中的文件夹 并返回文件夹中有多少邮件
uids = imap.uid('SEARCH', 'ALL') # 读取cxiaoln文件夹中的所有uid
uids = uids[1][0].split(' ') #将返回的('OK', ['1331738237 1331738238 1331738239'])的第二部分将通过空格分隔出3个uid
messageText = imap.uid('FETCH', uids[0], '(RFC822)'[1][0][1]) #读取uids[0]对应的邮件
总共四个步骤:1、连接服务器 2、选择邮箱中的文件夹 3、运行SEARCH指令,读取该文件夹的ID
4、通过FETCH指令获取邮箱的实际消息
使用IMAP4_SSL替换IAMP4,端口不是23 而是995
使用简单的socket 编程
import socketimport sysif len (sys.argv) < 3: print ('host port') sys.exit(1)hostname = sys.argv[1]port = int(sys.argv[2])sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.bind((hostname, port))sock.listen(1)print ('Waitiing for a request')request, clientAddress = sock.accept()print ('Received request from', clientAddress)request.send("xiaoln") #bytes('-=supersimpleSocketServer 3000=-\n', 'utf-8')request.send("exit") #bytes('Go away!\n', 'utf-8')request.shutdown(2)print("have handled request, stopping server.")socket.close()
在这里只是最简单的操作,也是socket中一种最简单的操作
1、sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2、sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #设置sock选项
sock.bind((hostname, port)) 绑定地址和端口号
sock.listen(1) 监听一个连接request, clientAddress = sock.accept() 阻塞等待客户端的连接
request.send("xiaoln") #bytes('-=supersimpleSocketServer 3000=-\n', 'utf-8')
request.send("exit") #bytes('Go away!\n', 'utf-8')request.shutdown(2) #断开连接socket.close() #关闭socket
客户端的连接可以使用:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((server, port))
sock.send(bytes(strData, 'utf-8'))
strRecvData = sock.recv(1024) // 最多一下子接受1024个字节
sock.close()
修改服务器,使用简单的socketserver
import socketserver
class RequestHandler(socketserver.StreamRequestHandler):
def handle(self):do something
rfile.read 读数据
wfile.write 写数据
socketserver.TCPServer(('localhost', 2000), RequestHandler).serve_forever()