- my $b_h = $entity->bodyhandle;
- my $IO = $b_h->open("r");
- while (defined($_ = $IO->getline)) {
- $i--;
- last if $i < 0;
- $body .= '> '. $_;
+ my $b_h;
+ # Default to UTF-8.
+ my $charset="utf-8";
+ ## find the first part which has a defined body handle and appears
+ ## to be text
+ if (defined $entity->bodyhandle) {
+ my $this_charset =
+ $entity->head->mime_attr("content-type.charset");
+ $charset = $this_charset if
+ defined $this_charset and
+ length $this_charset;
+ $b_h = $entity->bodyhandle;
+ } elsif ($entity->parts) {
+ my @parts = $entity->parts;
+ while (defined(my $part = shift @parts)) {
+ if ($part->parts) {
+ push @parts,$part->parts;
+ }
+ if (defined $part->bodyhandle and
+ $part->effective_type =~ /text/) {
+ my $this_charset =
+ $part->head->mime_attr("content-type.charset");
+ $charset = $this_charset if
+ defined $this_charset and
+ length $this_charset;
+ $b_h = $part->bodyhandle;
+ last;
+ }
+ }
+ }
+ if (defined $b_h) {
+ eval {
+ my $IO = $b_h->open("r");
+ while (defined($_ = $IO->getline)) {
+ $i--;
+ last if $i < 0;
+ $body .= '> '. convert_to_utf8($_,$charset);
+ }
+ $IO->close();
+ };