0
當我運行這段代碼時,它以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("[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()