http://qs1969.pair.com?node_id=194616


in reply to Decode a mail with MIME::Parser

In my recent mail-munging experiments, I found that the easiest way to get the simple mail info was to use Mail::MboxParser. This won't directly help with the e-mail address problem (which can probably be done via regex) but it should help in most cases with the message body. I'm a novice at regexp, so I'll leave that part for someone more qualified.

The problem is that depending on the client software used, it may be possible to send a message with an HTML only message body by preference settings. Here is an example that will extract the plaintext body message if one exists. Note that this can be used to read single or multiple messages:

#!/usr/local/bin/perl use strict; use warnings; use Mail::MboxParser; my $mbox= \*STDIN; my $mb = Mail::MboxParser->new($mbox); for my $msg ($mb->get_messages) { my $to = $msg->header->{to}; my $from = $msg->header->{from}; my $cc = $msg->header->{cc} || " ", my $subject = $msg->header->{subject} || '<No Subject:>', my $body = $msg->body($msg->find_body,0); my $body_str = $body->as_string || '<No message text>'; print "To: $to\n", "From: $from\n", "Cc: $cc\n", "Subject: $subject\n", "Message Text: $body_str\n"; print "~" x 77, "\n\n"; }
Just remember to handle errors/warnings for fields that are undefined.

You might check this node for an example of how to select only text attachments when dealing with multi-part MIME messages.

Update1: After a bit of R&R (reflection & research), I figured it would be best to mention a few things about the To: field format. I probably shouldn't have mentioned using a regexp to scarf the real e-mail address. Check out the documentation for RFC822 for details about the various ways header fields can be formatted. Things like folding and multiple addresses in the To: field to name a few.

One option that may prove worth looking at is Email::Valid , from the docs:

Let's see an example of how the address may be modified: $addr = Email::Valid->address('Alfred Neuman <Neuman @ foo.bar +>'); print "$addr\n"; # prints Neuman@foo.bar
This would do what you need for a simple single address but you would still have to figure out a way to parse multiple addresses. Maybe someone else knows of another module or method for the address field problem.

Update2: Some related nodes found via Super Search.

--Jim