Python,解析poplib电子邮件中的链接

时间:2016-06-06 17:37:05

标签: python email pop3 poplib

我很难从我的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

我无法上班。基本上我想要检测多行链接,这些链接在多个字典值上运行,每行需要添加,直到链接结束。这将是一个&gt;被检测到。

我在这里碰了一堵砖墙。我可以很好地获得单线链接,但我会努力争取一些帮助。显然我仍然需要清理生成的链接,但我可以稍后写一个正则表达式。

0 个答案:

没有答案