It was Tuesday, January 04, 2005 when Simon Wistow took the soap box, saying:
: I'm not sure what advantage parts() yeilds. I am writing a function
: which extracts all the text in a message. My first attempt went as
: follows:
: sub get_mime_text
: {
:   my $this = shift;
:   my $text = '';
:   my @subparts = $this->parts;
: 
:   if( $this->content_type =~ m#^text/#i ) {
:     $text = $this->body;
:   } else {
:     foreach my $part ( @subparts ) {
:       # Recursively look at each part
:       $text .= get_mime_text( $part );
:     }
:   }
: 
:   return $text;
: }

This can be solved with the use of Email::MIME::Modifier and
walk_parts().

  use Email::MIME::Modifier;
  my $mime = Email::MIME->new(join '', <>);

  my $text = '';
  $mime->walk_parts(sub {
      my $part = shift;
      $text .= $part->body if $part->content_type =~ m[text/];
  });


: subparts will also avoid the memory leak issue reported by
: http://rt.cpan.org/NoAuth/Bug.html?id=7007

That issue has been fixed. When it comes to recursing parts, I highly
suggest using walk_parts() from Email::MIME::Modifer. Here is an
example of walking only your children.

  $mime->walk_parts(sub {
      my $part = shift;
      return if $part == $mime; # top-level parent

      # ... do the rest
  });

This will do nothing in the case of a single-part message.

  Casey West

-- 
Shooting yourself in the foot with Ada 
If you are dumb enough to actually use this language, the United
States Department of Defense will kidnap you, stand you up in front of
a firing squad and tell the soldiers, "Shoot at the feet." 

Reply via email to