我正在努力从从我的 pop3 服务器下载的电子邮件中提取链接
我正在尝试解析与传入主题行匹配的电子邮件正文。我正在使用 poplib 模块从服务器获取电子邮件,代码如下:
def pop3_return_all_messages(user="", password="", pop_address="", subject=None):
pop_conn = poplib.POP3_SSL(pop_address)
pop_conn.user(user)
pop_conn.pass_(password)
#Get messages from server:
for m in pop_conn.list()[1]:
idx = int(m.split()[0])
# we use top(), not retr(), so that the 'read'-flag isn't set
head, body = parse_email(pop_conn.top(idx, 8192)[1]) #build dict of values for head and body
if subject in head["subject"]: #if subject matches
get_link(body)
电子邮件的解析是使用 parse_email 完成的,它为电子邮件的头部和正文生成了一个字典:
def parse_email(lines):
'''Splits an email provided as a list of lines into a dictionary of
header fields and a list of body lines. Returns a (header, body)
tuple.
'''
part = 0
head = {}
body = []
for ln in lines:
if part == 0:
if not ln.strip():
part = 1
continue
i = ln.find(':')
if i <= 0:
continue
head[ln[:i].strip().lower()] = ln[i+1:].strip()
else:
body.append(ln)
return head, body
这是获取链接,它试图建立一个链接列表。
def get_link(body):
def get_line(body):
for item in body:
yield item
links = [] #empty list for links
multipart_link = [] #empty list for multiline links
for line in get_line(body):
if "http" in line: #If a link has been found
if ">" in line: #If that link ends on the same line (single line link)
links.append(line) #add to links list
else: #multiline link detected
multipart_link.append(line) #add current line
for item in xrange(1,10):
if ">" not in get_line(body):
multipart_link.append(line) #
else:
multipart_link.append(line)
print multipart_link
break #last part of multipart link, exit
multi_link = "".join(multipart_link) #join up multipart link
links.append(multi_link) #add to links
multipart_link.pop() #clear multipart links
return links
一切都在
else: #multiline link detected
我不能去上班。本质上,我想检测多行链接,这些链接跨越多个字典值,需要添加的每一行,直到链接结束。这将是在检测到 > 时。
我在这里撞到了一堵砖墙。我可以很好地获得单行链接,但我正在努力解决多部分链接,并希望得到一些帮助。显然我仍然需要清理生成的链接,但我可以稍后为此编写一个正则表达式。