Excel file not attaching with Mailgun Python API

I’m having trouble sending an Excel spreadsheet through Mailgun’s API using Python. The email goes through fine but the attachment doesn’t show up. Here’s what I’m trying to do:

send_email(..., files=["/home/user/report.xlsx"])

My email function looks like this:

def send_email(title, message, sender, recipient, files=None):
    attachments = []
    if files:
        attachments.extend([("attachment", (os.path.basename(file_path), open(file_path, "rb+", encoding="utf-8"))) for file_path in files])
    
    print(attachments)
    response = requests.post(
        "https://api.mailgun.net/v3/mydomain.com/messages",
        auth=("api", "key-abc123def456ghi789jkl012mno345pqr"),
        files=attachments,
        data={
            "from": sender,
            "to": recipient, 
            "subject": title,
            "text": message
        }
    )
    return response

The request seems to work without throwing any errors but when I check my email the xlsx file is missing. What am I doing wrong here?

yeah, encoding will definitely break it, but also check your Content-Type header. mailgun sometimes needs the explicit MIME type for xlsx files. try adding ('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') to your attachment tuple. had the same issue last week - pdfs worked fine but excel files got corrupted without the proper mime type.

Had this exact same problem a few months ago - spent hours pulling my hair out! You’re opening Excel files with text encoding when they’re binary. Drop the encoding="utf-8" parameter from your open() call. Excel files are binary format, so adding text encoding messes up the file data. Change your line to open(file_path, "rb") instead of open(file_path, "rb+", encoding="utf-8"). Also close your file handles after the request finishes or you’ll get file locking issues. Learned that one the hard way when my server started throwing permission errors after sending multiple emails.