首页 > 解决方案 > Python:如何使用 IMAP 从收件箱中的某些电子邮件地址中提取姓名?

问题描述

我收到很多发件人看起来像这样的电子邮件:

Jenna Klopf <noreply@rentlinx.com>
Sam Smith <noreply@rentlinx.com>

我希望 Python 自动阅读我的电子邮件,如果发件人中存在“noreply@rentlinx”以提取名称“Jenna Klopf”和“Sam Smith”并将它们保存在列表中。我怎么做?截至目前,我可以搜索包含“noreply@rentlinx.com”的电子邮件,请参见下面的代码。

import imaplib, email
user = 'xxxxxxxxxxxxx@yahoo.com'
password = 'xxxxxxxxxxxxxxx'
imap_url = 'imap.mail.yahoo.com'

def auth(user,password,imap_url):
    con = imaplib.IMAP4_SSL(imap_url)
    con.login(user,password)
    return con

def get_body(msg):
    if msg.is_multipart():
        return get_body(msg.get_payload(0))
    else:
        return msg.get_payload(None, True)

def search(key,value,con):
    result, data = con.search(None,key,'"{}"'.format(value))
    return data

def get_emails(result_bytes):
    msgs = []
    for num in result_bytes[0].split():
        typ, data = con.fetch(num, '(RFC822)')
        msgs.append(data)
    return msgs

con = auth(user,password,imap_url)
con.select('INBOX')
result, data = con.fetch(b'1859','(RFC822)') #1859 is the newest email, I have 1860 emails in total
raw = email.message_from_bytes(data[0][1])
msgs = get_emails(search('FROM','noreply@rentlinx.com',con))
for msg in msgs:
    print(get_body(email.message_from_bytes(msg[0][1])))

标签: pythonemail

解决方案


推荐阅读