As part of a script, I want to take a file containing an email and extract a header, e.g., the subject header. The following almost works:

formail -c -x subject < FILE

But it does not decode headers encoded using the MIME encoded-word syntax (aka RFC2047), e.g., =?UTF-8?B?w6lsw6ltZW50?=.

What's a nice way to extract an email header while taking care of decoding MIME encoded-word parts?

Related question: https://stackoverflow.com/questions/39457380/retrieve-email-subject-from-file-via-bash

  • Maybe munpack can help. linux.die.net/man/1/munpack – nobody Nov 23 '19 at 16:16
  • Thanks, but are you sure? munpack seems to be about decoding MIME parts of messages, not headers. – a3nm Nov 23 '19 at 16:34
  • I am not sure, but it is worth trying. – nobody Nov 24 '19 at 15:08
  • Sure, but trying what? I looked at the man, nothing seems relevant. – a3nm Nov 24 '19 at 18:09

pipe it to:


formail -c -x Subject < FILE | \
python -c "from email.header import decode_header;
import sys;
text, encoding = decode_header(sys.stdin.read())[0];
print text.decode(encoding)"


formail -c -x Subject < FILE | \
  php -r 'echo iconv_mime_decode(stream_get_contents(STDIN),1,"utf-8");'

or if you're sure that the header will be =?UTF-8?B?… then you can easily do:

formail -c -x Subject < FILE | \
  awk -F '[?]' '{print $4}' | \
  openssl enc -base64 -d -A

python should be probably most universal, since it is in probably all systems by default and even the email module is present.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.