15 June 2008

MIME-decoding email attachments

Occasionally a friend will forward a message to my gmail account, and the forwarded message ends up as a plain-text attachment in the message I receive. If the original message had an attachment, that attachment appears as a MIME-encoded section of the attachment.

If this happens to you, you could try the following. Save the attachment as a text file, and open that file in a text editor. Delete all the lines except the lines which represent the encoded attachment (don't keep the attachment headers, just the lines of text which are 76 characters wide [the last line may be shorter--keep that one, too]). Don't forget to get rid of the lines after the attachment. Save the file as encoded.txt.

Save the following to an executable file called mime_decode somewhere in your $PATH:

#!/usr/bin/perl -w

use strict;
use diagnostics;

use Carp;
use MIME::Base64;

my $usage = "$0 infile outfile";
if ( @ARGV != 2 ) {
die "usage: $usage\n";
my ( $infile, $outfile ) = @ARGV;

open my $fh, '<', $infile or croak "cannot read $infile";
my $encoded = join '', <$fh>;
close $fh;

my $decoded = decode_base64($encoded);
open $fh, '>', $outfile or croak "cannot write $outfile";
print {$fh} $decoded;
close $fh;

Then run the following command:

mime_decode encoded.txt decoded

decoded should be the original attachment.

If you know of a standard utility which does this (especially if it doesn't require the user to prune the email message), please leave a comment.


zool said...

There is a freeware program "Decode Shell Extension" by Funduc Software which deals nicely with this problem. Right click on the text file, select Decode, and release.

Alex said...

I know some interesting softwares for work with emails. But couple days ago no one of theirs couldn't help me. But I was lucky and my friend recommended me - outlook express recover deleted mail which he had been found on a simple blog. It completed my troubles within seconds and I went to bed.