Search code examples
pythonemailgzipsmtplib

charmap codec can't decode byte error with gzipped file in python


I am attempting to send an email that includes a file in gzip format as an attachment using python.

But I'm getting an error when I try to send the file. This is the exception I'm getting:

Exception:  'charmap' codec can't decode byte 0x90 in position 75: character maps to <undefined>

This is what I'm doing in my code:

import gzip
destination = 'path/to/file'
to_addr = input("Enter the recipient's email address: ")
from_addr = 'cloudops@noreply.company.com'
subject = "Commpany AWS Billing Info "
content = "email to the user about the file"
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = subject
body = MIMEText(content, 'html')
msg.attach(body)
server = smtplib.SMTP('smtpout.us.companyworld.company.com', 25)
filename = destination
try:
    with open(filename, 'r') as f:
        part = MIMEApplication(f.read(), Name=basename(filename))
        part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename))
        msg.attach(part)
        server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr])
    print("Email was sent to: %s" %  to_addr)
except Exception as e:
    print("Exception: ", e)
    print("Email was not sent.")

The file I am trying to send was created in another function in these lines:

    import pandas
    read_sql = 'select * from somedb'
    mydb = mysql.connector.connect(user='x', password='x',host='x',database='aws_bill')
    results = pandas.read_sql_query(read_sql, mydb)
    results.to_csv(destination, index=False, encoding='utf8', compression='gzip')

How can I correct this problem and send the attachment?


Solution

  • The problem is this line:

    with open(filename, 'r') as f:
    

    You are opening the gzipped file in text mode, so Python is trying to decode it; gzipped files should be opened in binary mode, like this:

    with open(filename, 'rb') as f: