6 use vars qw($VERSION @EXPORT_OK);
11 @EXPORT_OK = qw(parse decode_rfc1522 encode_rfc1522 convert_to_utf8 create_mime_message);
18 use MIME::WordDecoder qw();
19 use Encode qw(decode encode encode_utf8 decode_utf8 is_utf8);
28 my $type = $entity->effective_type;
29 if ($type eq 'text/plain' or
30 ($type =~ m#text/# and $type ne 'text/html') or
31 $type eq 'application/pgp') {
32 return $entity->bodyhandle;
33 } elsif ($type eq 'multipart/alternative') {
34 # RFC 2046 says we should use the last part we recognize.
35 for my $part (reverse $entity->parts) {
36 my $ret = getmailbody($part);
40 # For other multipart types, we just pretend they're
41 # multipart/mixed and run through in order.
42 for my $part ($entity->parts) {
43 my $ret = getmailbody($part);
52 # header and decoded body respectively
53 my (@headerlines, @bodylines);
55 my $parser = new MIME::Parser;
56 mkdir "mime.tmp.$$", 0777;
57 $parser->output_under("mime.tmp.$$");
58 my $entity = eval { $parser->parse_data($_[0]) };
60 if ($entity and $entity->head->tags) {
61 @headerlines = @{$entity->head->header};
64 my $entity_body = getmailbody($entity);
65 @bodylines = $entity_body ? $entity_body->as_lines() : ();
68 # Legacy pre-MIME code, kept around in case MIME::Parser fails.
69 my @msg = split /\n/, $_[0];
72 for ($i = 0; $i <= $#msg; ++$i) {
75 while ($msg[$i + 1] =~ /^\s/) {
77 $_ .= "\n" . $msg[$i];
79 push @headerlines, $_;
82 @bodylines = @msg[$i .. $#msg];
85 rmtree "mime.tmp.$$", 0, 1;
88 shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
90 # Strip off RFC2440-style PGP clearsigning.
91 if (@bodylines and $bodylines[0] =~ /^-----BEGIN PGP SIGNED/) {
92 shift @bodylines while @bodylines and length $bodylines[0];
93 shift @bodylines while @bodylines and $bodylines[0] !~ /\S/;
94 for my $findsig (0 .. $#bodylines) {
95 if ($bodylines[$findsig] =~ /^-----BEGIN PGP SIGNATURE/) {
96 $#bodylines = $findsig - 1;
100 map { s/^- // } @bodylines;
103 return { header => [@headerlines], body => [@bodylines]};
106 =head2 create_mime_message
108 create_mime_message([To=>'don@debian.org'],$body,[$attach1, $attach2]);
110 Creates a MIME encoded message with headers given by the first
111 argument, and a message given by the second.
113 Optional attachments can be specified in the third arrayref argument.
115 Headers are passed directly to MIME::Entity::build, the message is the
118 Each of the elements of the attachment arrayref is attached as an
119 rfc822 message if it is a scalar or an arrayref; otherwise if it is a
120 hashref, the contents are passed as an argument to
125 sub create_mime_message{
126 my ($headers,$body,$attachments) = @_;
127 $attachments = [] if not defined $attachments;
129 die "The first argument to create_mime_message must be an arrayref" unless ref($headers) eq 'ARRAY';
130 die "The third argument to create_mime_message must be an arrayref" unless ref($attachments) eq 'ARRAY';
133 # MIME::Entity is stupid, and doesn't rfc1522 encode its headers, so we do it for it.
134 my $msg = MIME::Entity->build('Content-Type' => 'text/plain; charset=utf-8',
135 'Encoding' => 'quoted-printable',
136 (map{encode_rfc1522($_)} @{$headers}),
140 # Attach the attachments
141 for my $attachment (@{$attachments}) {
142 if (ref($attachment) eq 'HASH') {
143 $msg->attach(%{$attachment});
146 # This is *craptacular*, but because various MTAs
147 # (sendmail and exim4, at least) appear to eat From
148 # lines in message/rfc822 attachments, we need eat
149 # the entire From line ourselves so the MTA doesn't
150 # leave \n detrius around.
151 if (ref($attachment) eq 'ARRAY' and $attachment->[1] =~ /^From /) {
152 # make a copy so that we don't screw up anything
153 # that is expecting this arrayref to stay constant
154 $attachment = [@{$attachment}];
155 # remove the from line
156 splice @$attachment, 1, 1;
158 elsif (not ref($attachment)) {
159 # It's a scalar; remove the from line
160 $attachment =~ s/^(Received:[^\n]+\n)(From [^\n]+\n)/$1/s;
162 $msg->attach(Type => 'message/rfc822',
168 return $msg->as_string;
174 sub convert_to_utf8 {
175 my ($data, $charset) = @_;
176 # raw data just gets returned (that's the charset WordDecorder
177 # uses when it doesn't know what to do)
178 return $data if $charset eq 'raw' or is_utf8($data,1);
181 # this encode/decode madness is to make sure that the data
182 # really is valid utf8 and that the is_utf8 flag is off.
183 $result = encode("utf8",decode($charset,$data))
186 warn "Unable to decode charset; '$charset' and '$data': $@";
193 =head2 decode_rfc1522
195 decode_rfc1522('=?iso-8859-1?Q?D=F6n_Armstr=F3ng?= <don@donarmstrong.com>')
197 Turn RFC-1522 names into the UTF-8 equivalent.
202 # Set up the default RFC1522 decoder, which turns all charsets that
203 # are supported into the appropriate UTF-8 charset.
204 MIME::WordDecoder->default(new MIME::WordDecoder(
205 ['*' => \&convert_to_utf8,
209 sub decode_rfc1522 ($)
213 # unmime calls the default MIME::WordDecoder handler set up at
214 # initialization time.
215 return MIME::WordDecoder::unmime($string);
218 =head2 encode_rfc1522
220 encode_rfc1522('Dön Armströng <don@donarmstrong.com>')
222 Encodes headers according to the RFC1522 standard by calling
223 MIME::Words::encode_mimeword on distinct words as appropriate.
227 # We cannot use MIME::Words::encode_mimewords because that function
228 # does not handle spaces properly at all.
230 sub encode_rfc1522 ($) {
233 # We process words in reverse so we can preserve spacing between
234 # encoded words. This regex splits on word|nonword boundaries and
235 # nonword|nonword boundaries.
236 my @words = reverse split /(?:(?<=[\s\n])|(?=[\s\n]))/m, $rawstr;
238 my $previous_word_encoded = 0;
240 for my $word (@words) {
241 if ($word !~ m#[\x00-\x1F\x7F-\xFF]#o and $word ne ' ') {
242 $string = $word.$string;
243 $previous_word_encoded=0;
245 elsif ($word =~ /^[\s\n]$/) {
246 $string = $word.$string;
247 $previous_word_encoded = 0 if $word eq "\n";
250 my $encoded = MIME::Words::encode_mimeword($word, 'q', 'UTF-8');
251 # RFC 1522 mandates that segments be at most 76 characters
252 # long. If that's the case, we split the word up into 10
253 # character pieces and encode it. We must use the Encode
254 # magic here to avoid breaking on bit boundaries here.
255 if (length $encoded > 75) {
256 # Turn utf8 into the internal perl representation
257 # so . is a character, not a byte.
258 my $tempstr = decode_utf8($word,Encode::FB_DEFAULT);
260 # Strip it into 10 character long segments, and encode
262 # XXX It's possible that these segments are > 76 characters
263 while ($tempstr =~ s/(.{1,10})$//) {
264 # turn the character back into the utf8 representation.
265 my $tempword = encode_utf8($1);
266 # It may actually be better to eventually use
267 # the base64 encoding here, but I'm not sure
268 # if that's as widely supported as quoted
270 unshift @encoded, MIME::Words::encode_mimeword($tempword,'q','UTF-8');
272 $encoded = join(" ",@encoded);
273 # If the previous word was encoded, we must
274 # include a trailing _ that gets encoded as a
276 $encoded =~ s/\?\=$/_\?\=/ if $previous_word_encoded;
277 $string = $encoded.$string;
280 # If the previous word was encoded, we must
281 # include a trailing _ that gets encoded as a
283 $encoded =~ s/\?\=$/_\?\=/ if $previous_word_encoded;
284 $string = $encoded.$string;
286 $previous_word_encoded = 1;