Search code examples
python-2.7emailunicodeimapemail-attachments

i want to print mail without attachments


when i run this code it prints the body along with attachment data in unicode form ,so i want to avoid printing attachments,i just want to print mail body witout attachments.

import imaplib
import email

def extract_body(payload):# "want to download withut attachments"
    if isinstance(payload,str):
        return payload
    else:
        return '\n'.join([extract_body(part.get_payload()) for part in payload])

conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
conn.login("[email protected]", "password")
conn.select(mailbox='INBOX',readonly=False)    #    [Gmail]/Spam
typ, data = conn.search(None, 'ALL')  #attributes :::UNSEEN,SEEN  ALL
f = open("Text_Email_imap1.txt","w")
try:
    for num in data[0].split():
        typ, msg_data = conn.fetch(num,'(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part,tuple):
                msg = email.message_from_string(response_part[1])
                subject=msg['subject']                   
                print(subject)
                f.write(subject+'\n\n\n\n')
                payload=msg.get_payload()
                body=extract_body(payload)
                print(body)
                f.write(body+'\n\n\n\n\n')
        #typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
    try:
        conn.close()
    except:
        pass
    conn.logout()

Solution

  • for part in mail_message.walk():        #Uses walk() method to make depth first search of mail parts/sub-parts
            content_disposition = part.get("Content-Disposition",None)   #get the value of keyword content disposition
            print content_disposition
            if content_disposition == None:
                f.write(str(part.get_payload()))
            else:
                pass