fetch_mail.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from email.parser import Parser
  4. from email.header import decode_header
  5. from email.utils import parseaddr
  6. import poplib
  7. # 输入邮件地址, 口令和POP3服务器地址:
  8. email = input('Email: ')
  9. password = input('Password: ')
  10. pop3_server = input('POP3 server: ')
  11. def guess_charset(msg):
  12. charset = msg.get_charset()
  13. if charset is None:
  14. content_type = msg.get('Content-Type', '').lower()
  15. pos = content_type.find('charset=')
  16. if pos >= 0:
  17. charset = content_type[pos + 8:].strip()
  18. return charset
  19. def decode_str(s):
  20. value, charset = decode_header(s)[0]
  21. if charset:
  22. value = value.decode(charset)
  23. return value
  24. def print_info(msg, indent=0):
  25. if indent == 0:
  26. for header in ['From', 'To', 'Subject']:
  27. value = msg.get(header, '')
  28. if value:
  29. if header=='Subject':
  30. value = decode_str(value)
  31. else:
  32. hdr, addr = parseaddr(value)
  33. name = decode_str(hdr)
  34. value = u'%s <%s>' % (name, addr)
  35. print('%s%s: %s' % (' ' * indent, header, value))
  36. if (msg.is_multipart()):
  37. parts = msg.get_payload()
  38. for n, part in enumerate(parts):
  39. print('%spart %s' % (' ' * indent, n))
  40. print('%s--------------------' % (' ' * indent))
  41. print_info(part, indent + 1)
  42. else:
  43. content_type = msg.get_content_type()
  44. if content_type=='text/plain' or content_type=='text/html':
  45. content = msg.get_payload(decode=True)
  46. charset = guess_charset(msg)
  47. if charset:
  48. content = content.decode(charset)
  49. print('%sText: %s' % (' ' * indent, content + '...'))
  50. else:
  51. print('%sAttachment: %s' % (' ' * indent, content_type))
  52. # 连接到POP3服务器:
  53. server = poplib.POP3(pop3_server)
  54. # 可以打开或关闭调试信息:
  55. server.set_debuglevel(1)
  56. # 可选:打印POP3服务器的欢迎文字:
  57. print(server.getwelcome().decode('utf-8'))
  58. # 身份认证:
  59. server.user(email)
  60. server.pass_(password)
  61. # stat()返回邮件数量和占用空间:
  62. print('Messages: %s. Size: %s' % server.stat())
  63. # list()返回所有邮件的编号:
  64. resp, mails, octets = server.list()
  65. # 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
  66. print(mails)
  67. # 获取最新一封邮件, 注意索引号从1开始:
  68. index = len(mails)
  69. resp, lines, octets = server.retr(index)
  70. # lines存储了邮件的原始文本的每一行,
  71. # 可以获得整个邮件的原始文本:
  72. msg_content = b'\r\n'.join(lines).decode('utf-8')
  73. # 稍后解析出邮件:
  74. msg = Parser().parsestr(msg_content)
  75. print_info(msg)
  76. # 可以根据邮件索引号直接从服务器删除邮件:
  77. # server.dele(index)
  78. # 关闭连接:
  79. server.quit()