zerone has asked for the wisdom of the Perl Monks concerning the following question:

Can anybody give me a few good tips on how to get a email then get the body and writing the body to a textfile? Thanks, Zerone

Replies are listed 'Best First'.
Re: Mimetools
by mpolo (Chaplain) on May 14, 2001 at 12:57 UTC
    As your title implies, MIME-tools will help with getting the information out of the email once you have received it. You will need to get your hands on the email first, of course. If your mail lives on a POP3 server, use Net::POP3 to get it.

    I will now assume that your mail is sitting in a text file named incoming.

    #!/usr/bin/perl -w use strict; use MIME::Parser; my $parser=new MIME::Parser; $parser->output_dir("mime"); open FILE, "incoming" ||die "could not open\n"; my $email=$parser->read(\*FILE)||die "could not parse\n"; close FILE; ## Now $email is a MIME::Entity. if (!$email->parts) { my $bodyh=$email->bodyhandle; my $IO = $body->open("r") || die "open body: $!"; open OUTFILE, ">body"; while(defined($_ = $IO->getline)) { print OUTFILE; } $IO->close; close OUTFILE; } else { print "This is a multipart MIME message, and I need to do more work +to be able to read it.\n"; } $email->purge;

    Hopefully that gets you started... No guarantees against typos in the code...

Re: Mimetools
by dws (Chancellor) on May 14, 2001 at 19:39 UTC
    If you're doing this as part of a procmail replacement, considier Mail::Audit. It exposes the hooks you will need to save a message body.

Re: Mimetools (code)
by deprecated (Priest) on May 14, 2001 at 19:51 UTC
    The aforementioned Net::POP3 is a good module, although I prefer Mail::POP3Client. Here is a sample of its interface:
    # taken from perldoc Mail::POP3Client... use Mail::POP3Client; $pop = new Mail::POP3Client( USER => "me", PASSWORD => "mypassword", HOST => "pop3.do.main" ); for( $i = 1; $i <= $pop->Count(); $i++ ) { foreach( $pop->Head( $i ) ) { /^(From|Subject):\s+/i && print $_, "\n"; } }
    There are ample scripts about the monastery which deal with reading email and writing the file. You would do something like add this line to the above text:
    open FILE, "filename" or die "no file! $!"; print FILE $pop -> Body( $i ); close FILE or warn "$!";

    --
    Laziness, Impatience, Hubris, and Generosity.