'Error while decoding UTF-8 encoded csv file

first time posting here :)

I have an issue while trying to download all the attachments from an email Inbox. I download them, then write them into a file, which I specify the path to. It works perfectly well for .png files, which are directly dowloaded to the file, but when it comes to a .csv file, it gives me this error message :

OSError: [Errno 22] Invalid argument: 'C:\Users\antoi\OneDrive\Bureau\python_secge\=?UTF-8?B?RXh0cmFjdCBzZXggZ8OpIHB1YmxpYy0yMDIyLTAzLTI2LTAwLTAwLTI2LmNzdg==?='

I think it does not decode well the name of the csv file, but I don't know why.

Thanks for your help!

If you want to look at my code below :

import smtplib
import imaplib
import base64
import os
import email

smtp_address = 'smtp.gmail.com'
smtp_port = 465
email_user = 'XXXX'
email_pass = 'XXXXX'

mail = imaplib.IMAP4_SSL('imap.gmail.com',993)
mail.login(email_user, email_pass)
mail.select('Inbox')
type, data = mail.search(None, 'ALL')
mail_ids=data[0]
idlist=mail_ids.split()


for num in data[0].split():
    typ, data = mail.fetch(num, '(RFC822)' )
    raw_email = data[0][1]
# converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)
# downloading attachments
    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        
        if bool(fileName):
            filePath = os.path.join(r'C:\Users\antoi\OneDrive\Bureau\python_secge', fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
            subject = str(email_message).split("Subject: ", 1)

I tried to change the name of the csv file, which downloaded well, but the content of it was as if it was not decoded :

              #   #*%%*525EE\ÿ ¿ A"  ÿÄ7 ÿÚ  iÙWúßóÓ ÅIq«‚ÙÊŸ§ˆ˜²‚6`ض p²#áíîŸÐà ¼ïDù÷.ŽéCÅ >ªþ®|…dÕË' <å8
!õÑàäH¬


Solution 1:[1]

Stolen from Encoded-word Syntax1:

import re
import base64
import quopri

def encoded_words_to_text(encoded_words):
    encoded_word_regex = r'=\?{1}(.+)\?{1}([B|Q])\?{1}(.+)\?{1}='
    charset, encoding, encoded_text = re.match(encoded_word_regex,
                                               encoded_words).groups()
    if encoding == 'B':
        byte_string = base64.b64decode(encoded_text)
    elif encoding == 'Q':
        byte_string = quopri.decodestring(encoded_text)
    return byte_string.decode(charset)

Apply as follows:

filename = '=?UTF-8?B?RXh0cmFjdCBzZXggZ8OpIHB1YmxpYy0yMDIyLTAzLTI2LTAwLTAwLTI2LmNzdg==?='
encoded_words_to_text(filename)
'Extract sex gé public-2022-03-26-00-00-26.csv'

1 and eliminated SyntaxWarning: "is" with a literal. Did you mean "=="?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JosefZ