python:从电子邮件正文中提取并下载图像

时间:2016-10-26 09:32:51

标签: python python-2.7 email

我正在尝试阅读电子邮件的内容。如果电子邮件中包含 BODY 部分中的图片,我需要将其提取并保存在本地 以下是获取正文内容的代码

def get_body(id):
    res, mail_data = connection.fetch(id, '(RFC822)')
    raw_email=mail_data[0][1]
    email_message_instance = email.message_from_string(raw_email)
    whole_body = ''
    for part in email_message_instance.walk():
        if part.get_content_type() == "text/plain": # ignore attachments/html
            body = part.get_payload(decode=True)
            whole_body += body + ' '
        else:
                                    continue
    return whole_body

1 个答案:

答案 0 :(得分:1)

找到了解决方案。

def get_body(id):
    """Get the body of the email"""
    res, mail_data = connection.fetch(id, '(RFC822)')
    raw_email=mail_data[0][1]
    email_message_instance = email.message_from_string(raw_email)
    whole_body = ''
    for part in email_message_instance.walk():
        if part.get_content_type() == "text/plain": # ignore attachments/html
            body = part.get_payload(decode=True)
            print "body" + body
            whole_body += body + ' '
        if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
            print "image content"
            image = part.get_filename().split('.')
            image_name =  image[0] + id  + "." + image[1]
            open(E: + '/' + image_name, 'wb').write(part.get_payload(decode=True))
        else:
            continue
    return whole_body