2016-10-26 15 views
0

私は電子メールの内容を読もうとしています。電子メールはBODY部分に画像が含まれている場合、私はここで地元 でそれを抽出して保存する必要が解決策を見つけたpython:電子メールの本文から画像を抽出してダウンロードします

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 
+0

[Pythonのファイルオブジェクトへの取得、メールの添付ファイル](http://stackoverflow.com/questions/4067937/getting-mail-attachment-to-python-file-object) –

+0

の可能性の重複は、それがする@AriGoldそれは身体の中に直接になるアタッチメントではありません。全体像は体にある – user3125261

+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 
関連する問題