發郵件
#encode=utf-8import smtplibfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartif __name__ == '__main__': fromaddr = 'BuGaoSuNi@163.com' toaddrs = ['136xxxx1475@139.com', 'xxxx@xx.com'] subject = 'smtplib test.' content = 'smtplib test: hello, smtplib ! Can you see it ?' textApart = MIMEText(content) imageFile = '/tmp/code2.png' imageApart = MIMEImage(file(imageFile, 'rb').read(), imageFile.split('.')[-1]) imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile.split('/')[-1]) m = MIMEMultipart() m.attach(textApart) m.attach(imageApart) m['Subject'] = subject server = smtplib.SMTP('smtp.163.com') server.login(fromaddr,'BuGaoSuNi') server.sendmail(fromaddr, toaddrs, m.as_string()) server.quit()
收郵件
#encoding=utf-8import poplibimport emailif __name__ == '__main__': M = poplib.POP3('pop.163.com') M.user('BuGaoSuNi@163.com') M.pass_('BuGaoSuNi') #列印有多少封信 numMessages = len(M.list()[1]) print 'num of messages', numMessages #從最老的郵件開始遍曆 for i in range(numMessages): m = M.retr(i+1) msg = email.message_from_string('\n'.join(m[1])) #allHeaders = email.Header.decode_header(msg) aimHeaderStrs = {'from':'', 'to':'', 'subject':''} for aimKey in aimHeaderStrs.keys(): aimHeaderList = email.Header.decode_header(msg[aimKey]) for tmpTuple in aimHeaderList: if tmpTuple[1] == None: aimHeaderStrs[aimKey] += tmpTuple[0] else: aimHeaderStrs[aimKey] += tmpTuple[0].decode(tmpTuple[1]) #轉成unicode for aimKey in aimHeaderStrs.keys(): print aimKey,':',aimHeaderStrs[aimKey].encode('utf-8') #轉成utf-8顯示 for part in msg.walk(): #遍曆所有payload contenttype = part.get_content_type() filename = part.get_filename() if filename: #and contenttype=='application/octet-stream': #儲存附件 data = part.get_payload(decode=True) file("mail%d.attach.%s" % (i+1,filename),'wb').write(data) elif contenttype == 'text/plain': #儲存本文 data = part.get_payload(decode=True) charset = part.get_content_charset('ios-8859-1') file('mail%d.txt' % (i+1), 'w').write(data.decode(charset).encode('utf-8'))