Python使用POP3读取邮箱中的邮件,含文本及附件

读取邮件列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import poplib
import email
from email.parser import Parser

def receive_email_pop3(address, password):
# 防止报错: poplib.error_proto: line too long
poplib._MAXLINE = 1024 * 1024
pop3 = poplib.POP3('imap.exmail.qq.com', 110)
# pop3 = poplib.POP3_SSL('imap.exmail.qq.com', 995)
pop3.user(address)
pop3.pass_(password)

# 获取一些统计信息
emailMsgNum, emailSize = pop3.stat()
print 'Email number is %d and size is %d' % (emailMsgNum, emailSize)

# 遍历邮件,并打印出每封邮件的标题
for i in range(emailMsgNum):
for piece in pop3.retr(i + 1)[1]:
# print piece
if piece.startswith('Subject'):
print piece
break

# Get messages from server:
# 获得邮件
messages = [pop3.retr(i) for i in range(1, len(pop3.list()[1]) + 1)]
# print messages

# Concat message pieces:
messages = ["\n".join(msg[1]) for msg in messages]
# print messages

# Parse message intom an email object:
# 分析
# 'LazyImporter' object is not callable
# https://stackoverflow.com/questions/34348069/typeerror-lazyimporter-object-is-not-callable
# messages = [parser.Parser().parsestr(mssg) for mssg in messages]
messages = [Parser().parsestr(msg) for msg in messages]
i = 0
for index in range(0, len(messages)):
message = messages[index]
i = i + 1
subject = message.get('subject')
print subject
# h = email.Header(subject)
# dh = email.Header.decode_header(h)
# subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
mailName = "mail%d.%s" % (i, subject)
f = open('%d.log' % (i), 'w')
print >> f, "Date: ", message["Date"]
print >> f, "From: ", email.utils.parseaddr(message.get('from'))[1]
print >> f, "To: ", email.utils.parseaddr(message.get('to'))[1]
print >> f, "Subject: ", subject
print >> f, "Data: "
j = 0
for part in message.walk():
j = j + 1
fileName = part.get_filename()
contentType = part.get_content_type()
contentCharset = part.get_content_charset()
# 保存附件
if fileName:
data = part.get_payload(decode=True)
h = email.Header.Header(fileName)
dh = email.Header.decode_header(h)
fname = dh[0][0]
encodeStr = dh[0][1]
if encodeStr != None:
fname = fname.decode(encodeStr, contentCharset)
# end if
fEx = open("%s" % (fname), 'wb')
fEx.write(data)
fEx.close()
elif contentType == 'text/plain' or contentType == 'text/html': # or contentType == 'text/html':
# 保存正文
data = part.get_payload(decode=True)
email_content = str(data).decode(contentCharset).encode("utf-8")
print >> f, data
# end if
# end for
f.close()
# end for

pop3.quit()

读取最新邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import poplib
import email
from email.parser import Parser

class EmailLib():

def __init__(self):
self.pop3_server = 'imap.exmail.qq.com'
self.pop3_port = 110
self.pop3_ssl = False
pass

def receive_email_pop3(self, address, password):
# 防止报错: poplib.error_proto: line too long
poplib._MAXLINE = 1024 * 1024
if self.pop3_ssl:
pop3 = poplib.POP3_SSL(self.pop3_server, self.pop3_port)
else:
pop3 = poplib.POP3(self.pop3_server, self.pop3_port)
pop3.user(address)
pop3.pass_(password)

# 获取一些统计信息
emailMsgNum, emailSize = pop3.stat()
print 'Email number is %d and size is %d' % (emailMsgNum, emailSize)

# Get messages from server:
# 获得邮件
messages = [pop3.retr(i) for i in range(1, len(pop3.list()[1]) + 1)]

# Concat message pieces:
messages = ["\n".join(msg[1]) for msg in messages]
messages = [Parser().parsestr(msg) for msg in messages]

# 遍历邮件,并打印出每封邮件的标题
email_from = ''
email_to = ''
email_subject = ''
email_content = ''
email_date = ''
for i in range(emailMsgNum-1, -1, -1):
print '正在查询第 %d 封邮件' % (emailMsgNum-i)
message = messages[i]
email_subject = message.get('subject')
email_date = message["Date"]
email_from = email.utils.parseaddr(message.get('from'))[1]
email_to = email.utils.parseaddr(message.get('to'))[1]
for part in message.walk():
contentType = part.get_content_type()
contentCharset = part.get_content_charset()
if contentType == 'text/plain' or contentType == 'text/html':
# 保存正文
data = part.get_payload(decode=True)
email_content = str(data).decode(contentCharset).encode("utf-8")
# end if
# end for
if 'Apollo@lianlianpayglobal.com' in email_from:
break

# print email_from
# print email_to
# print email_subject
# print email_date
# print email_content

pop3.quit()
ret_email = {}
ret_email['from'] = email_from
ret_email['to'] = email_to
ret_email['subject'] = email_subject
ret_email['date'] = email_date
ret_email['content'] = email_content
print '邮件主题:' + email_subject
print '邮件内容:' + email_content
return ret_email

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :