Skip to content

mimetypes

The Python mimetypes module provides tools to map filenames to MIME types and vice versa. It’s useful for determining the type of data a file contains based on its filename extension.

Here’s an example:

Language: Python
>>> import mimetypes
>>> mimetypes.guess_type("example.txt")
('text/plain', None)

Key Features

  • Maps file extensions to MIME types
  • Supports both standard and custom MIME types
  • Provides functions to guess MIME types and extensions

Frequently Used Classes and Functions

Object Type Description
mimetypes.guess_type() Function Guesses the MIME type of a file based on its filename
mimetypes.guess_extension() Function Guesses the file extension for a given MIME type
mimetypes.add_type() Function Adds a mapping between a MIME type and extension
mimetypes.guess_file_type() Function Guesses the MIME type of a file based on its path (preferred over guess_type() for paths since Python 3.13)

Since Python 3.13, prefer mimetypes.guess_file_type() when working with filesystem paths, and reserve guess_type() for URLs.

Examples

Guessing the MIME type of a file:

Language: Python
>>> import mimetypes
>>> mimetypes.guess_type("document.pdf")
('application/pdf', None)

Guessing the file extension for a MIME type:

Language: Python
>>> mimetypes.guess_extension("image/jpeg")
'.jpg'

Adding a custom MIME type:

Language: Python
>>> mimetypes.add_type("application/x-custom_app", ".ca")
>>> mimetypes.guess_type("file.ca")
('application/x-custom_app', None)

Common Use Cases

  • Determining the MIME type of files for HTTP responses
  • Associating file extensions with MIME types in web applications
  • Extending MIME type support with custom types and extensions

Real-World Example

Suppose you’re building a web application and need to determine the MIME type of uploaded files to process them correctly. Here’s how you can use the mimetypes module:

Language: Python
>>> import mimetypes

>>> def get_file_mime_type(filename):
...     mime_type, _ = mimetypes.guess_type(filename)
...     return mime_type or "application/octet-stream"
...

>>> get_file_mime_type("upload.docx")
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

This code snippet helps identify the MIME type of an uploaded file, ensuring the web application processes it appropriately based on its content type.

Tutorial

Sending Emails With Python

In this tutorial, you'll learn how to send emails using Python. Find out how to send plain-text and HTML messages, add files as attachments, and send personalized emails to multiple people.

intermediate web-dev

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 21, 2026