NAME
MIME::Lite - low-calorie MIME generator
WARNING: This is Alpha code. I have not yet fully tested it, and I can't guarantee that the interface won't change in the next few releases in a non-backwards-compatible manner. It is being provided to the community for suggestions and in the hopes that it will be useful.
SYNOPSIS
use MIME::Lite;
Create a single-part message:
# Create a new single-part message, to send a GIF file:
$msg = new MIME::Lite
From =>'me@myhost.com',
To =>'you@yourhost.com',
Cc =>'some@other.com, some@more.com',
Subject =>'Helloooooo, nurse!',
Type =>'image/gif',
Encoding =>'base64',
Path =>'hellonurse.gif';
Create a multipart message (i.e., one with attachments):
# Create a new multipart message:
$msg = new MIME::Lite
From =>'me@myhost.com',
To =>'you@yourhost.com',
Cc =>'some@other.com, some@more.com',
Subject =>'A message with 2 parts...',
Type =>'multipart/mixed';
# Add parts (each "attach" has same arguments as "new"):
attach $msg
Type =>'TEXT',
Data =>"Here's the GIF file you wanted";
attach $msg
Type =>'image/gif',
Path =>'aaa000123.gif',
Filename =>'logo.gif';
Output a message:
# As a string...
$str = $msg->as_string;
# To a filehandle (say, a "sendmail" stream)...
$msg->print(\*SENDMAIL);
DESCRIPTION
In the never-ending quest for great taste with fewer calories, we proudly present: MIME::Lite.
MIME::Lite is intended as a simple, standalone module for generating (not parsing!) MIME messages... specifically, it allows you to output a simple, decent single- or multi-part message with text or binary attachments. It does not require that you have the Mail:: or MIME:: modules installed.
You can specify each message part as either the literal data itself (in a scalar or array), or as a string which can be given to open() to get a readable filehandle (e.g., "<filename" or "somecommand|").
You don't need to worry about encoding your message data: this module will do that for you. It handles the 5 standard MIME encodings.
If you need more sophisticated behavior, please get the MIME-tools package instead. I will be more likely to add stuff to that toolkit over this one.
MORE EXAMPLES
Create a multipart message exactly as above, but using the "attach to singlepart" hack:
# Create a new multipart message:
$msg = new MIME::Lite
From =>'me@myhost.com',
To =>'you@yourhost.com',
Cc =>'some@other.com, some@more.com',
Subject =>'A message with 2 parts...',
Type =>'TEXT',
Data =>"Here's the GIF file you wanted";
# Attach a part:
attach $msg
Type =>'image/gif',
Path =>'aaa000123.gif',
Filename =>'logo.gif';
Output a message to a filehandle:
# Write it to a filehandle:
$msg->print(\*STDOUT);
# Write just the header:
$msg->print_header(\*STDOUT);
# Write just the encoded body:
$msg->print_body(\*STDOUT);
Get a message as a string:
# Get entire message as a string:
$str = $msg->as_string;
# Get just the header:
$str = $msg->header_as_string;
# Get just the encoded body:
$str = $msg->body_as_string;
# Send a message (Unix systems only!):
# Send it!
$msg->send;
PUBLIC INTERFACE
Construction
- new [PARAMHASH]
-
Class method, constructor. Create a new message object.
If any arguments are given, they are passed into
build()
; otherwise, just the empty object is created. - attach [OBJECT|PARAMHASH]
-
Instance method. Add a new part to this message, and return the new part.
You can attach a MIME::Lite OBJECT, or have it create one by specifying a PARAMHASH that will be automatically given to
new()
.One of the possibly-quite-useful hacks thrown into this is the "attach-to-singlepart" hack: if you attempt to attach a part (let's call it "part 1") to a message that isn't a multipart message (the "self" object in this case), the following happens:
A new part (call it "part 0") is made.
The MIME attributes and data (but not the other headers) are cut from the "self" message, and pasted into "part 0".
The "self" is turned into a "multipart/mixed" message.
The new "part 0" is added to the "self", and then "part 1" is added.
One of the nice side-effects is that you can create a text message and then add zero or more attachments to it, much in the same way that a user agent like Netscape allows you to do.
- build [PARAMHASH]
-
Class/instance method, initiallizer. Create (or initiallize) a MIME message object. PARAMHASH can contain the following keys:
- (fieldname)
-
Any field you want placed in the message header, taken from the standard list of header fields (you don't need to worry about case):
Bcc Encrypted Received Sender Cc From References Subject Comments Keywords Reply-To To Content-* Message-ID Resent-* X-* Date MIME-Version Return-Path Organization
To give experienced users some veto power, these fields will be set after the ones I set... so be careful: don't set any MIME fields (like
Content-type
) unless you know what you're doing!To specify a fieldname that's not in the above list, even one that's identical to an option below, just give it with a trailing
":"
, like"My-field:"
. When in doubt, that always signals a mail field (and it sort of looks like one too). - Data
-
Alternative to "Path". The actual message data. This may be a scalar or a ref to an array of strings; if the latter, the message consists of a simple concatenation of all the strings in the array.
- Disposition
-
Optional. The content disposition,
"inline"
or"attachment"
. The default is"inline"
. - Encoding
-
Optional. The content transfer encoding that should be used to encode your data. The default is
"binary"
, which means "no encoding": this is generally not suitable for sending anything but ASCII text files with short lines, so consider using one of the following values instead:Use encoding: If your message contains: ------------------------------------------------------------ 7bit Only 7-bit text, all lines <1000 characters 8bit 8-bit text, all lines <1000 characters quoted-printable 8-bit text or long lines (MUCH more reliable than "8bit") base64 Largely binary data: a GIF, a tar file, etc.
Be sure to pick an appropriate encoding. In the case of "7bit"/"8bit", long lines are automatically chopped to legal length; in the case of "7bit", all 8-bit characters are automatically removed. This may not be what you want, so pick your encoding well! There's a "A MIME PRIMER" in this document with more info.
- Filename
-
Optional. The name of the attachment. You can use this to supply a filename if the one in the Path is inadequate, or if you're using the Data argument.
- Length
-
Optional. Set the content length explicitly. Normally, this header is automatically computed, but only under certain circumstances (see "Limitations").
- Path
-
Alternative to "Data". Path to a file containing the data... actually, it can be any open()able expression. If it looks like a path, the last element will automatically be treated as the filename. Ignored if "Data" is present. See "ReadNow" also.
- ReadNow
-
Optional, for use with "Path". If true, will open the path and slurp the contents into core now. This is useful if the Path points to a command and you don't want to run the command over and over if outputting the message several times. Fatal exception raised if the open fails.
- Top
-
Optional. If defined, indicates whether or not this is a "top-level" MIME message. The parts of a multipart message are not top-level. Default is true.
- Type
-
Optional. The MIME content type, or one of these special values (case-sensitive):
"TEXT" means "text/plain" "BINARY" means "application/octet-stream"
The default is
"TEXT"
.
A picture being worth 1000 words (which is of course 2000 bytes, so it's probably more of an "icon" than a "picture", but I digress...), here are some examples:
$msg = build MIME::Lite From => 'yelling@inter.com', To => 'stocking@fish.net', Subject => "Hi there!", Type => 'TEXT', Encoding => '7bit', Data => "Just a quick note to say hi!"; $msg = build MIME::Lite From => 'dorothy@emerald-city.oz', To => 'gesundheit@edu.edu.edu', Subject => "A gif for U" Type => 'image/gif', Path => "/home/httpd/logo.gif"; $msg = build MIME::Lite From => 'laughing@all.of.us', To => 'scarlett@fiddle.dee.de', Subject => "A gzipp'ed tar file", Type => 'x-gzip', Path => "gzip < /usr/inc/somefile.tar |", ReadNow => 1, Filename => "somefile.tgz";
To show you what's really going on, that last example could also have been written:
$msg = new MIME::Lite; $msg->build(Type => 'x-gzip', Path => "gzip < /usr/inc/somefile.tar |", ReadNow => 1, Filename => "somefile.tgz"); $msg->add(From => "laughing@all.of.us"); $msg->add(To => "scarlett@fiddle.dee.de"); $msg->add(Subject => "A gzipp'ed tar file");
Setting/getting headers and attributes
- add TAG,VALUE
-
Add field TAG with the given VALUE to the end of the header. The TAG will be converted to all-lowercase, and the VALUE will be made "safe" (returns will be given a trailing space).
Beware: any MIME fields you "add" will override any MIME attributes I have when it comes time to output those fields. Normally, you will use this method to add non-MIME fields:
$msg->add("Subject" => "Hi there!");
Giving VALUE an arrayref will cause all those values to be added:
$msg->add("Received" => ["here", "there", "everywhere"]
Note: add() is probably going to be more efficient than
replace()
, so you're better off using it for most applications.Note: the name comes from Mail::Header.
- attr ATTR,[VALUE]
-
Set MIME attribute ATTR to the string VALUE. ATTR is converted to all-lowercase. This method is normally used to set/get MIME attributes:
$msg->attr("content-type" => "text/html"); $msg->attr("content-type.charset" => "US-ASCII"); $msg->attr("content-type.name" => "homepage.html");
This would cause the final output to look something like this:
Content-type: text/html; charset=US-ASCII; name="homepage.html"
Note that the special empty sub-field tag indicates the anonymous first sub-field.
Giving VALUE as undefined will cause the contents of the named subfield to be deleted.
Supplying no VALUE argument just returns the attribute's value:
$type = $msg->attr("content-type"); # returns "text/html" $name = $msg->attr("content-type.name"); # returns "homepage.html"
- delete TAG
-
Delete field TAG with the given VALUE to the end of the header. The TAG will be converted to all-lowercase.
$msg->delete("Subject");
Note: the name comes from Mail::Header.
- fields
-
Return the full header for the object, as a ref to an array of
[TAG, VALUE]
pairs.Any fields that the user has explicitly set will override the corresponding MIME fields that we would generate. So: don't say:
$msg->set("Content-type" => "text/html; charset=US-ASCII");
unless you mean it!
Note: I called this "fields" because the header() method of Mail::Header returns something different, but similar enough to be confusing.
- filename [FILENAME]
-
Set the filename which this data will be reported as. This actually sets both "standard" attributes.
With no argument, returns the filename as dictated by the content-disposition.
- get_length
-
Recompute the content length for the message if the process is trivial, setting the "content-length" attribute as a side-effect:
$msg->get_length;
Returns the length, or undefined if not set.
Note: the content length can be difficult to compute, since it involves assembling the entire encoded body and taking the length of it (which, in the case of multipart messages, means freezing all the sub-parts, etc.).
This method only sets the content length to a defined value if the message is a singlepart with
"binary"
encoding, and the body is available either in-core or as a simple file. Otherwise, the content length is set to the undefined value.Since content-length is not a standard MIME field anyway (that's right, kids: it's not in the MIME RFCs, it's an HTTP thing), this seems pretty fair.
- replace TAG,VALUE
-
Delete all occurences of fields named TAG, and add a new field with the given VALUE. TAG is converted to all-lowercase.
Beware: any MIME fields you "replace" will override any MIME attributes I have when it comes time to output those fields. Normally, you will use this method to set non-MIME fields:
$msg->replace("Subject" => "Hi there!");
Giving VALUE as undefined will simply cause the contents of the named field to be deleted. Giving VALUE as an arrayref will cause all the values in the array to be added.
Note: the name comes from Mail::Header.
Setting/getting message data
- binmode [OVERRIDE]
-
With no argument, returns whether or not it thinks that the data (as given by the "Path" argument of
build()
) should be read using binmode() (for example, whenread_now()
is invoked).The default behavior is that any content type other than
text/*
ormessage/*
is binmode'd; this should in general work fine.With a defined argument, this method sets an explicit "override" value. An undefined argument unsets the override. The new current value is returned.
- data [DATA]
-
Get/set the literal DATA of the message. The DATA may be either a scalar, or a reference to an array of scalars (which will simply be joined).
Warning: setting the data causes the "content-length" attribute to be recomputed (possibly to nothing).
- path [PATH]
-
Get/set the PATH to the message data.
Warning: setting the path recomputes any existing "content-length" field, and re-sets the "filename" (to the last element of the path if it looks like a simple path, and to nothing if not).
- read_now [PATH]
-
Force the path to be read into core immediately. With optional argument, sets the
path()
first; otherwise, the current path (such as given during abuild()
) will be used.Note that the in-core data will always be used if available.
Be aware that everything is slurped into a giant scalar: you may not want to use this if sending tar files! The benefit of not reading in the data is that very large files can be handled by this module if left on disk until the message is output via
print()
orprint_body()
. - sign PARAMHASH
-
Sign the message. This forces the message to be read into core, after which the signature is appended to it.
- Data
-
As in
build()
: the literal signature data. Can be either a scalar or a ref to an array of scalars. - Path
-
As in
build()
: the path to the file.
If no arguments are given, the default is:
Path => "$ENV{HOME}/.signature"
The content-length is recomputed.
Output
- print [OUTHANDLE]
-
Instance method. Print the message to the given output handle, or to the currently-selected filehandle if none was given.
All OUTHANDLE has to be is a filehandle (possibly a glob ref), or any object that responds to a print() message.
- print_body [OUTHANDLE]
-
Instance method. Print the body of the message to the given output handle, or to the currently-selected filehandle if none was given.
All OUTHANDLE has to be is a filehandle (possibly a glob ref), or any object that responds to a print() message.
Fatal exception raised if unable to open any of the input files, or if a part contains no data, or if an unsupported encoding is encountered.
- print_header [OUTHANDLE]
-
Instance method. Print the header of the message to the given output handle, or to the currently-selected filehandle if none was given.
All OUTHANDLE has to be is a filehandle (possibly a glob ref), or any object that responds to a print() message.
- as_string
-
Instance method. Return the entire message as a string, with a header and an encoded body.
- body_as_string
-
Instance method. Return the encoded body as a string.
Note: actually prepares the body by "printing" to a scalar. Proof that you can hand the
print*()
methods any blessed object that responds to aprint()
message. - header_as_string
-
Instance method. Return the header as a string.
Sending
- send
-
Instance method. Sends the message.
Right now, this is done by piping it into the "sendmail" command as given by
sendmail()
. It probably will only work on Unix systems.Returns false if sendmail seems to have failed, true otherwise. Fatal exception raised if the open fails.
- sendmail COMMAND...
-
Class method. Set up the "sendmail" command used by
send()
. You may supply it as either a single string, or an array of path-to-command-plus-arguments:sendmail MIME::Lite "/usr/lib/sendmail", "-t", "-oi", "-oem";
What you see above is the default.
Miscellaneous
- quiet ONOFF
-
Class method. Suppress/unsuppress all warnings coming from this module.
quiet MIME::Lite 1; # I know what I'm doing
I recommend that you include that comment as well. And while you type it, say it out loud: if it doesn't feel right, then maybe you should reconsider the whole line.
;-)
NOTES
Limitations
This is "lite", after all...
There's no parsing. Get MIME-tools if you need to parse MIME messages.
MIME::Lite messages are currently not interchangeable with either Mail::Internet or MIME::Entity objects. This is a completely separate module.
A content-length field is only inserted if the encoding is binary, the message is a singlepart, and all the document data is available at
build()
time by virtue of residing in a simple path, or in-core. Since content-length is not a standard MIME field anyway (that's right, kids: it's not in the MIME RFCs, it's an HTTP thing), this seems pretty fair.MIME::Lite alone cannot help you lose weight. You must supplement your use of MIME::Lite with a healthy diet and exercise.
Cheap and easy mailing
I thought putting in a sendmail invocation wasn't too bad an idea, since a lot of Perlers are on UNIX systems. The default arguments to sendmail (which you can change) are:
-t Scan message for To:, Cc:, Bcc:, etc.
-oi Do NOT treat a single "." on a line as a message terminator.
As in, "-oi vey, it truncated my message... why?!"
-oem On error, mail back the message (I assume to the
appropriate address, given in the header).
When mail returns, circle is complete. Jai guru deva -oem.
Under the hood
This class treats a MIME header in the most abstract sense, as being a collection of high-level attributes. The actual RFC-822-style header fields are not constructed until it's time to actually print the darn thing.
WARNINGS
Important: the MIME attributes are stored and manipulated separately from the message header fields; when it comes time to print the header out, any explicitly-given header fields override the ones that would be created from the MIME attributes. That means that this:
### DANGER ### DANGER ### DANGER ### DANGER ### DANGER ###
$msg->add("Content-type", "text/html; charset=US-ASCII");
will set the exact "Content-type"
field in the header I write, regardless of what the actual MIME attributes are.
This feature is for experienced users only, as an escape hatch in case the code that normally formats MIME header fields isn't doing what you need. And, like any escape hatch, it's got an alarm on it: MIME::Lite will warn you if you attempt to set()
or replace()
any MIME header field. Use attr()
instead.
A MIME PRIMER
Content types
The "Type" parameter of build()
is a content type. This is the actual type of data you are sending. Generally this is a string of the form "majortype/minortype"
.
Here are the major MIME types. A more-comprehensive listing may be found in RFC-2046.
- application
-
Data which does not fit in any of the other categories, particularly data to be processed by some type of application program.
application/octet-stream
,application/gzip
,application/postscript
... - audio
-
Audio data.
audio/basic
... - image
-
Graphics data.
image/gif
,image/jpeg
... - message
-
A message, usually another mail or MIME message.
message/rfc822
... - multipart
-
A message containing other messages.
multipart/mixed
,multipart/alternative
... - text
-
Textual data, meant for humans to read.
text/plain
,text/html
... - video
-
Video or video+audio data.
video/mpeg
...
Content transfer encodings
The "Encoding" parameter of build()
. This is how the message body is packaged up for safe transit.
Here are the 5 major MIME encodings. A more-comprehensive listing may be found in RFC-2045.
- 7bit
-
Basically, no real encoding is done. However, this label guarantees that no 8-bit characters are present, and that lines do not exceed 1000 characters in length.
- 8bit
-
Basically, no real encoding is done. The message might contain 8-bit characters, but this encoding guarantees that lines do not exceed 1000 characters in length.
- binary
-
No encoding is done at all. Message might contain 8-bit characters, and lines might be longer than 1000 characters long.
The most liberal, and the least likely to get through mail gateways. Use sparingly, or (better yet) not at all.
- base64
-
Like "uuencode", but very well-defined. This is how you should send essentially binary information (tar files, GIFs, JPEGs, etc.).
- quoted-printable
-
Useful for encoding messages which are textual in nature, yet which contain non-ASCII characters (e.g., Latin-1, Latin-2, or any other 8-bit alphabet).
CHANGE LOG
Current version: $Id: Lite.pm,v 1.123 1998/05/01 16:40:18 eryq Exp $
- Version 1.122
-
MIME::Base64 and MIME::QuotedPrint are used if available.
The 7bit encoding no longer does "escapes"; it merely strips 8-bit characters.
- Version 1.121
-
Filename attribute is now no longer ignored by build(). Thanks to Ian Smith for finding and patching this bug.
- Version 1.120
-
Efficiency hack to speed up MIME::Lite::IO_Scalar. Thanks to David Aspinwall for the patch.
- Version 1.116
-
Small bug in our private copy of encode_base64() was patched. Thanks to Andreas Koenig for pointing this out.
New, prettier way of specifying mail message headers in
build()
.New quiet method to turn off warnings.
Changed "stringify" methods to more-standard "as_string" methods.
- Version 1.112
-
Added
read_now()
, andbinmode()
method for our non-Unix-using brethren: file data is now read using binmode() if appropriate. Thanks to Xiangzhou Wang for pointing out this bug. - Version 1.110
-
Fixed bug in opening the data filehandle.
- Version 1.102
-
Initial release.
- Version 1.101
-
Baseline code.
TERMS AND CONDITIONS
Copyright (c) 1997 by Eryq. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
This software comes with NO WARRANTY of any kind. See the COPYING file in the distribution for details.
NUTRITIONAL INFORMATION
For some reason, the US FDA says that this is now required by law on any products that bear the name "Lite"...
Serving size: 1 module
Servings per container: 1
Calories: 0
Fat: 0g
Saturated Fat: 0g
Warning: for consumption by hardware only! May produce
indigestion in humans if taken internally.
AUTHOR
Eryq. President, Zero G Inc. eryq@zeegee.com / http://www.zeegee.com.
Created: 11 December 1996. Ho ho ho.