This blogpost is propably only useful to people with no to little knowledge of regex. In it’s center stands a big shell command which I will explain most of the post.

~/.mailcap is a file which describes how programs should handle files with a certain MIME-type. It’s essentially a list of all handled MIME-types, semicolon seperated by the according command for opening the file. %s stands for the filename:

application/pdf; evince %s;

My mailprogram depends on ~/.mailcap for opening attachments. At first, I had a hard time repeatingly discovering a new MIME-type, handling it in .mailcap and running into another unhandled one again, until I decided to solve the problem once for ever by using grep.

My mails are stored in a directory called ~/Mail/, but for this tutorial it is only important to have it in plaintext somewhere. By finding all the MIME-types mentioned in my mail, I generated the most complete mailcap file I can think of. The shell command for doing it is the following:

grep -Ehor '\b((?:application|audio|example|font|image|'\
'message|model|multipart|text|video|chemical)/[a-z-]+?)\b' \
Mail/ | sort -u > ~/.mailcap

Command explained

The command above greps through all mail for MIME-types, sorts them and makes the list consist only of unique entries and writes it into .mailcap. Please note that that command will overwrite your existing .mailcap file. Find the command tree below.

Regex explained

According to Wikipedia, MIME-types start with a prefix describing the category, followed by a slash and ended with the exact type (consisting only of the letters a-z and -). The prefix must be one of the following:

The shell command uses the following regex, which matches against this definition. Again, it is stretched over two lines:

\b((?:application|audio|example|font|image|
message|model|multipart|text|video|chemical)/[a-z]+?)\b

What follows is kind of the abstract syntax tree of the regex. Please note, that it is an extended regular expression.

This defines how a MIME-type looks like. The resulting list should only consist of all the well-formed MIME-types found in your mail. All you have to do is to complement the entries with their corresponding applications as in

application/pdf; evince %s;

Have a look at this for further understanding of mailcap.