1. #!/usr/bin/env python
2. # coding=utf-8
3. # Python 2.7.3
4. # 获取邮件内容
5. import poplib
6. from email import parser
7.
8. host = 'pop.163.com'
9. username = '[email protected]'
10. password = 'xxxxxxxxx'
11.
12. pop_conn = poplib.POP3_SSL(host)
13. pop_conn.user(username)
14. pop_conn.pass_(password)
15.
16. #Get messages from server:
17. # 获得邮件
18. messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
19. #print messages
20.
21. #print "--------------------------------------------------"
22. # Concat message pieces:
23. messages = ["\n".join(mssg[1]) for mssg in messages]
24. #print messages
25.
26. #Parse message intom an email object:
27. # 分析
28. messages = [parser.Parser().parsestr(mssg) for mssg in messages]
29. i = 0
30. for message in messages:
31. i = i + 1
32. mailName = "mail%d.%s" % (i, message["Subject"])
33. f = open(mailName + '.log', 'w');
34. print >> f, "Date: ", message["Date"]
35. print >> f, "From: ", message["From"]
36. print >> f, "To: ", message["To"]
37. print >> f, "Subject: ", message["Subject"]
38. print >> f, "Data: "
39. j = 0
40. for part in message.walk():
41. j = j + 1
42. fileName = part.get_filename()
43. contentType = part.get_content_type()
44. # 保存附件
45. if fileName:
46. data = part.get_payload(decode=True)
47. fileName = "%s.%d.%s" % (mailName, j, fileName)
48. fEx = open(fileName, 'wb')
49. fEx.write(data)
50. fEx.close()
51. elif contentType == 'text/plain' or contentType == 'text/html':
52. #保存正文
53. data = part.get_payload(decode=True)
54. print >> f, data
55.
56. f.close()
57. pop_conn.quit()