Split this e-mail [digest] message 

Some times we receive e-mail messages in a digest format, either from mailing lists or other informational newsletters. From these messages, occasionally, I want to keep just one paragraph or one message and throw away all the rest.

So I wrote a little PERL script, called “splitdigest.pl“, for doing that and I’m using it from inside Mutt just by pressing ‘Z’. It works like this:

  1. open ~/.muttrc file and append the following two lines after its last line:

    macro index Z |’~/bin/splitdigest.pl’nd
    macro pager Z |’~/bin/splitdigest.pl’nd

    (the above lines remap the key Z to (1) filter the body of the message through splitdigest script, which is located in my ~/bin directory and (2) delete the message)

  2. create a new file with your favorite editor and insert the following lines to it (just remember to replace username with your login name):
    #!/usr/bin/perl -w
    use strict;
    use diagnostics;
    my ($outfile, $line, $i, $k);
    my (@header, @body);
    $outfile = "/var/spool/mail/username";
    open PF, ">> $outfile" or die "Couldn't open $outfile for writing: $!n";
    push @header, "From username@localhost ",scalar(localtime()),"n";
    $i = 0; $k = 0;
    foreach $line () {
    if (($i==0) && ($line !~ /^$/)) { # read header
    if ($line =~ /^Content-Type: multipart/alternative; /) {
    $line = "Content-Type: text/plain; charset=utf-8n";
    push @header, $line if
    ($line =~ /^(From|Date|Subject|To|Message-ID|Content-Type|Content-Transfer-Encoding): /i);
    # read message body
    if ($i>0) { push @body, $line if ($line !~ /^$/); }
    # flush @body and restart with a new message
    if ($line =~ /^$/) {
    if ($#body > 0) {
    print PF @header, $line; # first print header
    print PF @body, $line; # then body
    @body = (); # finally flush body
    # in case the message ends with a non-null line, write the rest
    if ($#body > 0) { print PF @header,"n",@body,"n"; }
    close PF;
    print "$k messages found and written to file [$outfile]n";

  3. Save the file as “splitdigest.pl” in your ~/bin directory (or wherever you like) and make it executable with chmod:

    chmod +x ~/bin/splitdigest.pl

That’s all!

Additional information:

  • The code above splits the digests where there is a blank line in it, i.e. the separator is the blank line. With a little tweaking you can use a different separator.
  • I know that one can edit the whole message in Mutt by ‘e’diting it. I’m using this method for its speed and convenience.

Visit The Light of the LAMP blog for more…