#!/usr/bin/perl -w # $Id: mime-forward,v 1.6 2004/03/15 21:42:29 bmc Exp $ # Copyright (C) 2004 - Brian Caswell =head1 NAME mime-forward - forward attachments elsewhere, while passing just the plain text =head1 SYNOPSIS mime-forward [-mode ] =head1 DESCRIPTION :0 f * ^Content-Type: multipart/mixed; | mime-forward bmc@shmoo.com =head1 OPTIONS =over =item -mode Set the mode for handling attachments. Default is forward =over B =over pass the attachments to procmail, forwarding a stripped email to the provided address =back B =over pass the stripped email to procmail, forwarding attachments to the provided address =back B =over pass the email to procmail, forwarding any emails with text after stripping the attachments =back =back =back =head1 NOTES If no attachments are found, then the email is handled normally. =head1 AUTHOR Brian Caswell C =cut use strict; use Pod::Usage; use Mail::Send; use MIME::Parser; use Getopt::Long; use Data::Dumper; my $mode = 'forward'; my ($help); GetOptions('help|?' => \$help, 'mode=s' => \$mode) or pod2usage(2); pod2usage() if $help; pod2usage({-message => "Invalid mode"}) if $mode !~ /^forward|store|phone$/; my $to = $ARGV[0] || pod2usage(1); my $parser = new MIME::Parser; $parser->tmp_recycling(1); $parser->extract_nested_messages(0); $parser->output_to_core(1); my $email = $parser->parse(\*STDIN) || die "Ack, couldn't parse"; my $attachments = $email->dup; my $plain_email = $email->dup; my $sent; # strip all but the first plain text message... my $text = undef; my @just_text = grep { first_text($_) } $plain_email->parts; $plain_email->parts(\@just_text); # strip the first plain text message... $text = undef; my @just_attachments = grep { all_but_first_text($_) } $attachments->parts; $attachments->parts(\@just_attachments); # if we saw attachments, deal with em. otherwise, just print what we got if ($mode eq 'forward') { forward($attachments); save($plain_email); } elsif ($mode eq 'store') { forward($plain_email); save($attachments); } elsif ($mode eq 'phone') { if ($text) { forward($plain_email); } save($email); } sub save { my ($mail) = @_; $mail->print(\*STDOUT); } sub forward { my ($mail) = @_; my $sender = new Mail::Send; foreach ($mail->head->tags) { $sender->set($_, map {chomp $_; $_} $mail->head->get($_)); } $sender->set('To',$to); my $fh = $sender->open('sendmail'); $mail->print_body($fh); $fh->close; } sub first_text { my $entry = shift; my @parts = $entry->parts; if (@parts) { # multipart... map { first_text($_) } @parts; } else { # single part... if (!defined($text) && $entry->head->mime_type eq "text/plain") { $text++; return 1; } } return 0; } sub all_but_first_text { my $entry = shift; my @parts = $entry->parts; if (@parts) { # multipart... map { all_but_first_text($_) } @parts; } else { # single part... if (!defined($text) && $entry->head->mime_type eq "text/plain") { $text++; return 0; } } return 1; }