【问题标题】:python: extract and download an image from the body of the emailpython:从电子邮件正文中提取和下载图像
【发布时间】:2016-11-04 15:10:07
【问题描述】:

我正在尝试阅读电子邮件的内容。如果电子邮件在 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

【问题讨论】:

  • @AriGold 它不会是附件,它会直接在正文中。整个图像将在身体上
  • 你已经知道如何获取尸体了吗?
  • @AriGold 使用提取正文的代码编辑了问题
  • @AriGold 增加了正文中图片的返回类型。

标签: python python-2.7 email


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2018-07-19
    • 2010-11-18
    • 1970-01-01
    • 2019-01-09
    • 2011-05-15
    相关资源
    最近更新 更多