我想打印没有附件的邮件

时间:2015-10-18 14:24:29

标签: python-2.7 email unicode imap email-attachments

当我运行此代码时,它以unicode形式打印正文和附件数据,所以我想避免打印附件,我只想打印邮件正文附件。

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("tryntest@gmail.com", "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()

1 个答案:

答案 0 :(得分:0)

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