Needle in a Haystack
Tutorials – Attachment Extraction
If your inbox is full of email messages with important attachments, retrieving those attachments manually can be a tedious task. The script presented in this article does this task automatically and can even save the email as a plain text file.
Do you ever find yourself urgently searching for a file that you know you received as an email attachment but do not remember who sent it or when? Has your company saved all the important documents received via email somewhere easily retrievable? Would you like to save the content of all your email messages automatically as separate, plain text files?
Being able to copy automatically, into one folder and as separate files, all the email attachments and message bodies hidden in your email archives might save your day in situations like these. This tutorial explains how to do it with one relatively simple shell script and tools available from the standard repositories of most Linux distributions. Only basic knowledge of shell scripts is necessary. Additionally, patching the script to make it save just the attachment is also very easy.
MIME and Mailbox Formats
To process email messages, you need to know how files are attached to email and how email messages are archived inside digital mailboxes. To extract attachments from one email message, you need a MIME-aware processor that can split all the email's parts into separate files. Multipurpose Internet Mail Extensions (MIME) [1] is the open standard that describes how to:
- encode non-ASCII character sets in email bodies and headers,
- format message bodies with multiple parts (e.g., content in both HTML and plain text formats), and
- encode and attach to email any non-textual content (e.g., images to generic binary files).
To archive multiple messages as one mailbox, the simplest format is MBOX, which just concatenates all messages into one plain text file. Because MBOX is as simple as it is inefficient, other formats that store each message in a separate file inside a folder were developed [2]. One of the most common formats, and the one used in this tutorial, is called Maildir, which has the internal structure shown in Figure 1.

Preliminary Work
Unless the mailbox you want to scan for attachments already is in Maildir format (or in any other format that puts every email into a separate file), you have to convert it. You can manually, but quickly, convert any mailbox to Maildir format in any Linux terminal using the Mutt email client:
1. Type:
mutt -R -m Maildir -f <YOUR MAILBOX>
2. Type T followed by the Enter key.
3. Type a semicolon ( ; ) and then s.
The -R
switch opens in read-only mode the mailbox defined with -f
, and -m
sets Maildir as the default mailbox format. By doing the second step inside Mutt, you tag all the messages in the mailbox. The third step makes Mutt ask you in which other mailbox all those messages should be saved, (i.e., copied, because the original mailbox is in read-only mode). Pass Mutt any mailbox name you want; when it has finished copying the messages, type q to exit.
If you have many mailboxes to convert, you can run Mutt from a script, as explained in an article online [3]. In any case, I recommend only working with copies of your mailbox, just to be on the safe side (not to mention that changing the access times of email files may confuse some email clients).
A Redundant, Overcautious Extractor
By default, the email extractor script that I introduce here extracts everything from email messages, not just attachments: message bodies, digital signatures, embedded images, and so on. With some very minor modifications, however, you can make it extract attachments only.
The code for this article is a shell script that contains three parts. For readability, I present them in three separate listings. The first part (Listing 1) defines all the necessary variables and folders, plus a shell function that generates unique folder names for each message.
Listing 1
Preparation
01 #! /bin/bash 02 03 MAILBOX="$1" 04 TARGET="$2" 05 TMPDIR="$HOME/extractor-tmp" 06 CNT=0 07 declare -A CHECKSUMS 08 09 emaildirname() { 10 MSGTS=`stat -c %Y $EMAIL` 11 ORIGTS=`date -d @$MSGTS '+%Y%m%d%H%M.%S'` 12 FILENAMETS=`date -d @$MSGTS '+%Y%m%d%H%M%S'` 13 MSGDATE=`grep '^Date: ' $EMAIL | cut -c7- | head -1` 14 MSGSUBJ=`grep '^Subject: ' $EMAIL | cut -c10-210 | head -1` 15 DIR=`echo $MSGDATE-$MSGSUBJ | sed -r 's/[^a-zA-Z0-9]+/-/g' | sed -r 's/-+$//'` 16 DIR="$FILENAMETS-$DIR-$CNT" 17 let "CNT=CNT+1" 18 } 19 20 rm -rf $TMPDIR $TARGET 21 mkdir -p $TMPDIR $TARGET/tmp 22 23 echo "EXTR mbox : $MAILBOX" 24 printf "EXTR contains : %s messages ( %s KBytes )\n" `find $MAILBOX -type f | wc -l ` `du -sk $MAILBOX | cut -f1` 25 echo "EXTR target : $TARGET"
I call the script "redundant" because its second part (Listing 2) does the actual job of saving all attachments and email bodies as separate files a total of four times, with four different tools. The final section (Listing 3) removes any empty or duplicate files produced by that process.
Listing 2
Extraction
26-28 <these lines only contained comments...> 29 for TOOL in mu uudeview munpack ripmime 30 do 31 mkdir -p $TMPDIR/$TOOL/ 32 printf "EXTR\nEXTR %-10s: %-9s start\n" $TOOL `date +%H:%M:%S` 33 CNT=0 34 35 for EMAIL in `find $MAILBOX/ -type f` 36 do 37 emaildirname 38 mkdir $TMPDIR/$TOOL/$DIR 39 cd $TMPDIR/$TOOL/$DIR 40 case $TOOL in 41 42 ripmime) 43 TOOLNUM=3 44 ripmime -i $EMAIL --paranoid ;; 45 46 munpack) 47 TOOLNUM=2 48 munpack -t -q $EMAIL > /dev/null ;; 49 50 uudeview) 51 TOOLNUM=1 52 uudeview +a -m -n -q -i $EMAIL ;; 53 54 mu) 55 TOOLNUM=0 56 mu extract -a $EMAIL ;; 57 esac 58 59 NUMFILES=`find . -type f | wc -l` 60 if [[ "$NUMFILES" -gt "0" ]] 61 then 62 find . -type f | cut -c3- > /tmp/file_list.txt 63 while IFS= read -r file 64 do 65 NEWNAME=`echo ${file%.*}` 66 NEWNAME=`echo $NEWNAME | sed -r 's/[^a-zA-Z0-9]+/-/g' | sed -r 's/-+$//'` 67 EXT=`echo $file | awk -F . '{print $NF}'` 68 69 if [ "$EXT" == "$NEWNAME" ] 70 then 71 EXT='probablyemailbody.txt' 72 fi 73 mv -- "$file" $FILENAMETS-$TOOLNUM-$CNT-$NEWNAME.$EXT 74 touch -t $ORIGTS $FILENAMETS-$TOOLNUM-$CNT-$NEWNAME.$EXT 75 done < /tmp/file_list.txt 76 fi 77 78 done 79 printf "EXTR %-10s: %-9s end\n" $TOOL `date +%H:%M:%S` 80 printf "EXTR %-10s: %-9s files extracted (%7s empty)\n" $TOOL `find $TMPDIR/$TOOL/ -type f | wc -l` `find $TMPDIR/$TOOL/ -type f -empty| wc -l` 81 82 find $TMPDIR/$TOOL/ -type f -exec mv -i {} $TARGET/tmp \; 83 84 done
Listing 3
Cleanup
85 86 find $TARGET/tmp -type f -empty -exec rm {} \; 87 88 printf "EXTR\nEXTR cleaning : %-9s start\n" `date +%H:%M:%S` 89 90 CNT=0 91 92 for F in `find $TARGET/tmp -type f | sort` 93 do 94 CK=`md5sum $F | sed 's/ .*$//' ` 95 if [ "${CHECKSUMS[$CK]}" == "found" ] 96 then 97 echo "DUPX: removing $F" 98 let "CNT=CNT+1" 99 else 100 echo "DUPX: keeping $F" 101 mv $F $TARGET/ 102 CHECKSUMS[$CK]='found' 103 fi 104 done 105 106 mv $TARGET/tmp $TARGET-tmp 107 108 printf "EXTR total : %-9s files found, after removing %s duplicates\n" `find $TARGET -type f | wc -l` $CNT 109 printf "EXTR cleaning : %-9s end\n" `date +%H:%M:%S` 110 >
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Direct Download
Read full article as PDF:
Price $2.95
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
News
-
KDE Plasma 6 Looks to Bring Basic HDR Support
The KWin piece of KDE Plasma now has HDR support and color management geared for the 6.0 release.
-
Bodhi Linux 7.0 Beta Ready for Testing
The latest iteration of the Bohdi Linux distribution is now available for those who want to experience what's in store and for testing purposes.
-
Changes Coming to Ubuntu PPA Usage
The way you manage Personal Package Archives will be changing with the release of Ubuntu 23.10.
-
AlmaLinux 9.2 Now Available for Download
AlmaLinux has been released and provides a free alternative to upstream Red Hat Enterprise Linux.
-
An Immutable Version of Fedora Is Under Consideration
For anyone who's a fan of using immutable versions of Linux, the Fedora team is currently considering adding a new spin called Fedora Onyx.
-
New Release of Br OS Includes ChatGPT Integration
Br OS 23.04 is now available and is geared specifically toward web content creation.
-
Command-Line Only Peropesis 2.1 Available Now
The latest iteration of Peropesis has been released with plenty of updates and introduces new software development tools.
-
TUXEDO Computers Announces InfinityBook Pro 14
With the new generation of their popular InfinityBook Pro 14, TUXEDO upgrades its ultra-mobile, powerful business laptop with some impressive specs.
-
Linux Kernel 6.3 Release Includes Interesting Features
Although it's not a Long Term Release candidate, Linux 6.3 includes features that will benefit end users.
-
Arch-Based blendOS Features Cool Trick
If you're looking for a Linux distribution that blends Linux, Android, and web apps together, blendOS might be what you're looking for.