Reputation: 897
i am facing an error at line 18 (m = email.message_from_string(email_body)) saying that TypeError: initial_value must be str or None, not bytes
. When I try to run it by saying print (data[0][1])
it gives me an output of the email in an encoded format.
I want to debug the error.
import imaplib
import email
import os
svdir = 'C:\\Users\\rnandipati\\Downloads'
mail = imaplib.IMAP4_SSL('outlook.office365.com',993)
mail.login("[email protected]", "R!")
mail.select("Inbox")
typ, msgs = mail.search(None, '(SUBJECT "ADP Files")')
msgs = msgs[0].split()
for emailid in msgs:
resp, data = mail.fetch(emailid, "(RFC822)")
email_body = data[0][1]
m = email.message_from_string(email_body)
if m.get_content_maintype() != 'multipart':
continue
for part in m.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename is not None:
sv_path = os.path.join(svdir, filename)
if not os.path.isfile(sv_path):
print(sv_path)
fp = open(sv_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
Upvotes: 0
Views: 1808
Reputation: 50180
The email
module includes a function message_from_bytes
. Use that instead of message_from_string
to parse a bytes
object.
m = email.message_from_bytes(email_body)
Upvotes: 1