o365 special subject mail download issue - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: o365 special subject mail download issue (/thread-18384.html) |
o365 special subject mail download issue - anna - May-15-2019 Hi, I am getting specific mail in Inbox with subject 'ACTIVE DSL DUMP EPOS' on daily basis, with extension .gz. I am trying to download attachment, however I am getting error. Below is the my script, post reading some online docs. import imaplib import email import os save_path = '/home/downloads' mail = imaplib.IMAP4_SSL('outlook.office365.com') mail.login("xyz.com", "Abc1@2015") mail.select("Inbox") typ, msgs = mail.search(None, '(SUBJECT "ACTIVE DSL DUMP EPOS")') 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 not os.path_exists(save_path): os.makedirs(save_path) with open(os.path.join_path(save_path,filename), 'wb') as fp: fp.write(part.get_payload(decode=True))
RE: o365 special subject mail download issue - micseydel - May-15-2019 This is a common issue in Python 3. Your email_body variable is bytes, not a string. Bytes do not have an encoding, so if you want to use them as a string you have to take action to turn the bytes into a string with a given encoding. The way you'd do that here specifically is you'd call the decode method like so m = email.message_from_string(email_body.decode())Note that decode takes an encoding as a parameter, but it defaults to UTF-8, which is very likely fine for your purposes. Generally speaking, when you run into the "must be str not bytes" kinda stuff, you want to call decode. For the opposite, you'd use encode. RE: o365 special subject mail download issue - anna - May-16-2019 thanks, now I am facing new error now. tried with os.path_exists also.this path is already exits, if I am commenting that,getting below error whereas I am not getting error while checking indivisuallyPython 3.6.0 (default, Jan 22 2018, 15:43:08) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> save_path = '/home/anna/scripts/ohfdata/downloads' >>> print(os.path.exists(save_path)) True RE: o365 special subject mail download issue - micseydel - May-16-2019 You're not calling the same function in those cases. In one, you're using os.path.exists and in the other you're using os.path_exist (which isn't a function). Similarly, it's os.path.join, not os.path.join_path. |