Extract/save a mail attachment using bash

Using normal bash tools (ie, built-ins or commonly-available command-line tools), is it

  • possible, and
  • how

to extract/save attachments on emails?

For example, say I have a nightly report which arrives via email but is a zip archive of several log files. I want to save all those zips into a backup directory. How would I accomplish that?


Solution 1:

If you're aiming for portability, beware that there are several different versions of mail(1) and mailx(1). There's a POSIX mailx command, but with very few requirements. And none of the implementations I have seem to parse attachments anyway.

You might have the mpack package. Its munpack command saves all parts of a MIME message into separate files, then all you have to do is save the interesting parts and clean up the rest.

There's also metamail. An equivalent of munpack is metamail -wy.

Solution 2:

The best program for this purpose is ripMIME.

It extracts the text and all attachments:

https://pldaniels.com/ripmime/

GitHub: inflex/ripMIME