Python Mailgun API fails to embed images inline in emails

I’m having trouble sending emails with embedded images using the Mailgun Python API. When I try to include a PNG file as an inline attachment, it doesn’t work properly.

Here’s my current code:

image_path = "assets/header_image.png"
response = requests.post(
    "https://api.mailgun.net/v2/sandbox123.mailgun.org/messages",
    auth=("api", "key-abc123"),
    files=[("inline", open(image_path)),],
    data={"from": sender_email,
          "to": recipient_email,
          "subject": email_subject,
          "html": html_content})

The image doesn’t appear in the email. I noticed something weird when I test reading the PNG file directly with print open(image_path).read() - it shows garbled characters like �PNG instead of readable content.

However, when I test with a text file using print open('assets/sample.txt'), it displays the file contents correctly.

Why can’t Python read the PNG file properly? Is this related to my inline image problem?

yep, pngs will come out as gibberish since they’re binary. for inline images, just use the cid in your html like . just double check that the filename matches what you’re giving Mailgun. hope that helps!

The issue with reading binary files, like PNGs, showing garbled characters is completely normal; that’s just how binary data appears when printed as text. However, the embedded image issue likely stems from not using a Content-ID correctly in your HTML. When sending inline images with Mailgun, ensure you specify the filename in the files parameter and reference it in your HTML with the cid format. Update your code with files=[("inline", ("header_image.png", open(image_path, "rb")))], and ensure your HTML includes <img src="cid:header_image.png">. Always open your image files in binary mode using “rb”. The garbled output you’re seeing is not the cause of your inline image issue.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.