use MIME::Parser; ### Create parser, and set some parsing options: my $parser = new MIME::Parser; $parser->output_under("$ENV{HOME}/mimemail"); ### Parse input: $entity = $parser->parse(\*STDIN) or die "parse failed\n"; ### Take a look at the top-level entity (and any parts it has): $entity->dump_skeleton;
Here's some code which composes and sends a MIME message containing three parts: a text file, an attached GIF, and some more text:
use MIME::Entity; ### Create the top-level, and set up the mail headers: $top = MIME::Entity->build(Type =>"multipart/mixed", From => "me\@myhost.com", To => "you\@yourhost.com", Subject => "Hello, nurse!"); ### Part #1: a simple text document: $top->attach(Path=>"./testin/short.txt"); ### Part #2: a GIF file: $top->attach(Path => "./docs/mime-sm.gif", Type => "image/gif", Encoding => "base64"); ### Part #3: some literal text: $top->attach(Data=>$message); ### Send it: open MAIL, "| /usr/lib/sendmail -t -oi -oem" or die "open: $!"; $top->print(\*MAIL); close MAIL;
For more examples, look at the scripts in the examples directory of the MIME-tools distribution.
File::Path File::Spec IPC::Open2 (optional) MIME::Base64 MIME::QuotedPrint Net::SMTP Mail::Internet, ... from the MailTools distribution.
See the Makefile.PL in your distribution for the most-comprehensive list of prerequisite modules and their version numbers.
(START HERE) results() .-----------------. \ .-------->| MIME:: | .-----------. / | Parser::Results | | MIME:: |--' `-----------------' | Parser |--. .-----------------. `-----------' \ filer() | MIME:: | | parse() `-------->| Parser::Filer | | gives you `-----------------' | a... | output_path() | | determines | | path() of... | head() .--------. | | returns... | MIME:: | get() | V .-------->| Head | etc... | .--------./ `--------' | .---> | MIME:: | | `-----| Entity | .--------. | parts() `--------'\ | MIME:: | / returns `-------->| Body |<---------' sub-entities bodyhandle() `--------' (if any) returns... | open() | returns... | V .--------. read() | IO:: | getline() | Handle | print() `--------' etc...
To illustrate, parsing works this way:
A typical multipart message containing two parts --- a textual greeting and an ``attached'' GIF file --- would be a tree of MIME::Entity objects, each of which would have its own MIME::Head. Like this:
.--------. | MIME:: | Content-type: multipart/mixed | Entity | Subject: Happy Samhaine! `--------' | `----. parts | | .--------. |---| MIME:: | Content-type: text/plain; charset=us-ascii | | Entity | Content-transfer-encoding: 7bit | `--------' | .--------. |---| MIME:: | Content-type: image/gif | Entity | Content-transfer-encoding: base64 `--------' Content-disposition: inline; filename="hs.gif"
You then give that instance a readable filehandle on which waits a MIME message. If all goes well, you will get back a MIME::Entity object (a subclass of Mail::Internet), which consists of...
If the original message was a multipart document, the MIME::Entity object will have a non-empty list of ``parts'', each of which is in turn a MIME::Entity (which might also be a multipart entity, etc, etc...).
Internally, the parser (in MIME::Parser) asks for instances of MIME::Decoder whenever it needs to decode an encoded file. MIME::Decoder has a mapping from supported encodings (e.g., 'base64') to classes whose instances can decode them. You can add to this mapping to try out new/experiment encodings. You can also use MIME::Decoder by itself.
For multipart messages, you can start by creating a top-level "multipart" entity with MIME::Entity::build(), and then use the similar MIME::Entity::attach() method to attach parts to that message. Please note: what most people think of as ``a text message with an attached GIF file'' is really a multipart message with 2 parts: the first being the text message, and the second being the GIF file.
When building MIME a entity, you'll have to provide two very important pieces of information: the content type and the content transfer encoding. The type is usually easy, as it is directly determined by the file format; e.g., an HTML file is "text/html". The encoding, however, is trickier... for example, some HTML files are "7bit"-compliant, but others might have very long lines and would need to be sent "quoted-printable" for reliability.
See the section on encoding/decoding for more details, as well as ``A MIME PRIMER'' below.
$entity->smtpsend;
Encoding: | Normally used when message contents are: ------------------------------------------------------------------- 7bit | 7-bit data with under 1000 chars/line, or multipart. 8bit | 8-bit data with under 1000 chars/line. binary | 8-bit data with some long lines (or no line breaks). quoted-printable | Text files with some 8-bit chars (e.g., Latin-1 text). base64 | Binary files.
Which encoding you choose for a given document depends largely on (1) what you know about the document's contents (text vs binary), and (2) whether you need the resulting message to have a reliable encoding for 7-bit Internet email transport.
In general, only "quoted-printable" and "base64" guarantee reliable transport of all data; the other three ``no-encoding'' encodings simply pass the data through, and are only reliable if that data is 7bit ASCII with under 1000 characters per line, and has no conflicts with the multipart boundaries.
I've considered making it so that the content-type and encoding can be automatically inferred from the file's path, but that seems to be asking for trouble... or at least, for Mail::Cap...
Debug message are only logged if you have turned ``debugging'' on in the MIME::Tools configuration.
Warning messages are only logged if $^W is set true and MIME::Tools is not configured to be ``quiet''.
Error messages are only logged if $^W is set true and MIME::Tools is not configured to be ``quiet''.
Usage messages are currently only logged if $^W is set true and MIME::Tools is not configured to be ``quiet''.
When a MIME::Parser (or one of its internal helper classes) wants to report a message, it generally does so by recording the message to the MIME::Parser::Results object immediately before invoking the appropriate function above. That means each parsing run has its own trace-log which can be examined for problems.
MIME::Tools->debugging(1);
MIME::Tools->quiet(1);
print MIME::Tools->version, "\n";
$entity = eval { $parser->parse(\*INPUT) };
Parsing is a complex process, and some components may throw exceptions if seriously-bad things happen. Since ``seriously-bad'' is in the eye of the beholder, you're better off catching possible exceptions instead of asking me to propagate "undef" up the stack. Use of exceptions in reusable modules is one of those religious issues we're never all going to agree upon; thankfully, that's what "eval{}" is good for.
$entity = $parser->parse(\*STDIN); $entity->print(\*STDOUT);
If you're using MIME::Tools to process email, remember to save the data you parse if you want to send it on unchanged. This is vital for things like PGP-signed email.
=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?=
To be consistent with the existing Mail::Field classes, MIME::Tools does not automatically unencode these strings, since doing so would lose the character-set information and interfere with the parsing of fields (see ``decode_headers'' in MIME::Parser for a full explanation). That means you should be prepared to deal with these encoded strings.
The most common question then is, how do I decode these encoded strings? The answer depends on what you want to decode them to: ASCII, Latin1, UTF-8, etc. Be aware that your ``target'' representation may not support all possible character sets you might encounter; for example, Latin1 (ISO-8859-1) has no way of representing Big5 (Chinese) characters. A common practice is to represent ``untranslateable'' characters as ``?''s, or to ignore them completely.
To unencode the strings into some of the more-popular Western byte representations (e.g., Latin1, Latin2, etc.), you can use the decoders in MIME::WordDecoder (see MIME::WordDecoder). The simplest way is by using "unmime()", a function wrapped around your ``default'' decoder, as follows:
use MIME::WordDecoder; ... $subject = unmime $entity->head->get('subject');
One place this is done automatically is in extracting the recommended filename for a part while parsing. That's why you should start by setting up the best ``default'' decoder if the default target of Latin1 isn't to your liking.
An attempt has been made to allow the parser to handle both CRLF and newline-terminated input.
The "binary" decoder (default if no encoding specified) still outputs stuff verbatim... so a MIME message with CRLFs and no explicit encoding will be output as a text file that, on many systems, will have an annoying ^M at the end of each line... but this is as it should be.
From - Wed Mar 22 02:13:18 2000 Return-Path: <eryq@zeegee.com> Subject: Hello
The parser simply ignores such stuff quietly. Perhaps it shouldn't, but most people seem to want that behavior.
Content-type: multipart/mixed; boundary="xyz"\n Subject: This message (#1) has an empty preamble\n \n --xyz\n ... Content-type: multipart/mixed; boundary="xyz"\n Subject: This message (#2) also has an empty preamble\n \n \n --xyz\n ...
In both cases, the first completely-empty line (after the ``Subject'') marks the end of the header.
But we should clearly ignore the second empty line in message #2, since it fills the role of ``the newline which is only there to make sure that the boundary is at the beginning of a line''. Such newlines are never part of the content preceding the boundary; thus, there is no preamble ``content'' in message #2.
However, it seems clear that message #1 also has no preamble ``content'', and is in fact merely a compact representation of an empty preamble.
As of the released 5.3xx, MIME::Parser gets by with only one temp file open per parser. This temp file provides a sort of infinite scratch space for dealing with the current message part. It's fast and lightweight, but you should know about it anyway.
I agree in principle, but RFC 2045 says otherwise. RFC 2045 [MIME] headers are a syntactic subset of RFC-822 [email] headers. Perhaps a better name for these modules would have been RFC1521:: instead of MIME::, but we're a little beyond that stage now.
When I originally wrote these modules for the CPAN, I agonized for a long time about whether or not they really should subclass from Mail::Internet (then at version 1.17). Thanks to Graham Barr, who graciously evolved MailTools 1.06 to be more MIME-friendly, unification was achieved at MIME-tools release 2.0. The benefits in reuse alone have been substantial.
In our system, an attachment is just a MIME::Entity under the top-level entity, probably one of its parts.
A body is represented by an instance of MIME::Body. You get the body of an entity by sending it a bodyhandle() message.
Since a body part is just a kind of entity, it's represented by an instance of MIME::Entity.
An entity is represented by an instance of MIME::Entity. There are instance methods for recovering the header (a MIME::Head) and the body (a MIME::Body).
There currently is no explicit package for ``messages''; under MIME::, messages are streams of data which may be read in from files or filehandles. You can think of the MIME::Entity returned by the MIME::Parser as representing the full message.
At the time of this writing, the MIME-tools homepage was http://www.mimedefang.org/static/mime-tools.php. Check there for updates and support.
The MIME format is documented in RFCs 1521-1522, and more recently in RFCs 2045-2049.
The MIME header format is an outgrowth of the mail header format documented in RFC 822.
See ChangeLog file for full details.
Copyright (c) 1998, 1999 by ZeeGee Software Inc (www.zeegee.com). Copyright (c) 2004 by Roaring Penguin Software Inc (www.roaringpenguin.com)
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See the COPYING file in the distribution for details.
Gisle Aas The MIME encoding/decoding modules. Laurent Amon Bug reports and suggestions. Graham Barr The new MailTools. Achim Bohnet Numerous good suggestions, including the I/O model. Kent Boortz Initial code for RFC-1522-decoding of MIME headers. Andreas Koenig Numerous good ideas, tons of beta testing, and help with CPAN-friendly packaging. Igor Starovoitov Bug reports and suggestions. Jason L Tibbitts III Bug reports, suggestions, patches.
Not to mention the Accidental Beta Test Team, whose bug reports (and comments) have been invaluable in improving the whole:
Phil Abercrombie Mike Blazer Brandon Browning Kurt Freytag Steve Kilbane Jake Morrison Rolf Nelson Joel Noble Michael W. Normandin Tim Pierce Andrew Pimlott Dragomir R. Radev Nickolay Saukh Russell Sutherland Larry Virden Zyx
Please forgive me if I've accidentally left you out. Better yet, email me, and I'll put you in.
See the COPYING file for more details.