Mail::M...::Field(3)
π NAME π
Okay bestie, welcome to Mail::Message::Field(3) β straight out of the User Contributed Perl Documentation section, and it does exactly one iconic thing:
Mail::Message::Field β one line of a message header π
πΈ INHERITANCE πΈ
The family tree, no cap:
Mail::Message::Field
is a Mail::Reporter
Mail::Message::Field is extended by
Mail::Message::Field::Fast
Mail::Message::Field::Flex
Mail::Message::Field::Full
π SYNOPSIS π
The whole vibe in one block, slay:
my $field = Mail::Message::Field->new(From => 'fish@tux.aq');
print $field->name;
print $field->body;
print $field->comment;
print $field->content; # body & comment
$field->print(\*OUT);
print $field->string;
print "$field\n";
print $field->attribute('charset') || 'us-ascii';
π¦ DESCRIPTION π¦
So this implementation follows the guidelines of rfc2822 as close as possible, which means it may produce a different output than implementations based on the obsolete rfc822. But don't stress β the old output will still be accepted. π«Ά
These objects each store one header line, and they hand you access routines to all the info hiding inside it. Also, you may want to peek at the added methods of a message:
my @from = $message->from;
my $sender = $message->sender;
my $subject = $message->subject;
my $msgid = $message->messageId;
my @to = $message->to;
my @cc = $message->cc;
my @bcc = $message->bcc;
my @dest = $message->destinations;
my $other = $message->get('Reply-To');
Extends "DESCRIPTION" in Mail::Reporter.
β¨ OVERLOADED β¨
π overload: '""' stringification
Produces the unfolded body of the field, which may be exactly what you expect. This is the thing that makes the field object seem like a simple string, iykyk. The string is produced by unfoldedBody().
Β» example β¨:
print $msg->get('subject'); # via overloading
print $msg->get('subject')->unfoldedBody; # same
my $subject = $msg->get('subject') || 'your mail';
print "Re: $subject\n";
π overload: '0+' numification
When the field is numeric, the value gets returned. The result is produced by toInt(). If the value is not correct, a 0 is produced β purely to simplify your calculations, bestie. π
π overload: '<='> numeric comparison
Compares the integer field contents with something else.
Β» example β¨:
if($msg->get('Content-Length') > 10000) ...
if($msg->size > 10000) ... ; # same, but better
π overload: bool boolean
Always "true", so you can literally just say if($field). Periodt.
π overload: cmp string comparison
Compares the unfolded body of a field with another field or a string, using the buildin cmp.
π METHODS π
Extends "METHODS" in Mail::Reporter.
π§Έ Constructors
Extends "Constructors" in Mail::Reporter.
π« $obj->clone()
Makes a copy of this field object. Dupe it, own it. π
π« $class->new($data)
See Mail::Message::Field::Fast::new(), Mail::Message::Field::Flex::new(), and Mail::Message::Field::Full::new(). By default, a "Fast" field is produced. Improves base, see "Constructors" in Mail::Reporter.
π§Έ Attributes
Extends "Attributes" in Mail::Reporter.
π« $obj->Name()
Returns the name of this field in original casing. See name() as well.
π« $obj->body()
Heads up: this method may not be what you want β foldedBody() and unfoldedBody() are probably what you're actually looking for. Those return the full content of a field, even when it's structured.
Returns the body of the field. When this field is structured, it gets stripped of everything behind the first semi-colon (;). In any case, the string is unfolded. Whether the field is structured is defined by isStructured().
π« $obj->folded()
Returns the folded version of the whole header. When the header is shorter than the wrap length, you get a list of one line back. Otherwise you get more lines, and all of them except the first start with at least one blank. See also foldedBody() if you want the same info without the field's name.
In scalar context, the lines are delivered into one string, which is a little faster because that's literally the way they're stored internally...
Β» example β¨:
my @lines = $field->folded;
print $field->folded;
print scalar $field->folded; # faster
π« $obj->foldedBody( [$body] )
Returns the body as a set of lines. In scalar context, this is one line containing newlines. Be warned about those newlines when you do pattern matching on the result of this method, bestie. π
The optional $body argument changes the field's body. The folding of the argument must be correct.
π« $obj->name()
Returns the name of this field, with all characters lower-cased for ease of comparison. See Name() as well.
π« $obj->unfoldedBody( [$body, [$wrap]] )
Returns the body as one single line, where all folding information (if available) is removed. This line will also NOT end on a new-line.
The optional $body argument changes the field's body. The right folding is performed before assignment. The $wrap may be specified to enforce a folding size.
Β» example β¨:
my $body = $field->unfoldedBody;
print "$field"; # via overloading
π« $obj->wellformedName( [STRING] )
(Instance method class method) As an instance method, the current field's name is correctly formatted and returned. When a "STRING" is used, that one is the one that gets formatted.
Β» example β¨:
print Mail::Message::Field->Name('content-type')
# --> Content-Type
my $field = $head->get('date');
print $field->Name;
# --> Date
π§Έ The field
π« $any->isStructured( [$name] )
Some fields are described in the RFCs as being structured: they have a well described syntax. These fields have common ideas about comments and the like, which they do not share with unstructured fields, like the "Subject" field.
Β» example β¨:
my $field = Mail::Message::Field->new(From => 'me');
if($field->isStructured)
Mail::Message::Field->isStructured('From');
π« $obj->length()
Returns the total length of the field in characters, which includes the field's name, body and folding characters.
π« $obj->nrLines()
Returns the number of lines needed to display this header-line.
π« $obj->print( [$fh] )
Prints the whole header-line to the specified file-handle. One line may result in more than one printed line, because of the folding of long lines. The $fh defaults to the selected handle.
π« $obj->size()
Returns the number of bytes needed to display this header-line. Same as length().
π« $obj->string( [$wrap] )
Returns the field as a string. By default, this returns the same as folded(). However, the optional $wrap will cause a re-fold to take place (without changing the folding stored inside the field).
π« $obj->toDisclose()
Returns whether this field can be disclosed to other people β for instance when sending the message to another party. Returns a "true" or "false" condition. See also Mail::Message::Head::Complete::printUndisclosed().
π§Έ Access to the content
π« $obj->addresses()
Returns a list of Mail::Address objects, which represent the e-mail addresses found in this header line. Only applicable to fields which contain addresses.
Β» example β¨:
my @addrs = $message->get('to')->addresses;
my @addrs = $message->to;
# Better, uses Mail::Message::Field::Addresses
my @addrs = $message->study('to')->addresses;
π« $obj->attribute( $name, [$value] )
Get the value of a body attribute, optionally after setting it to a new value. Attributes are part of some header lines, and they hide themselves in the comment field. If the attribute does not exist, then undef is returned. The attribute is still encoded.
Β» example β¨:
my $field = Mail::Message::Field->new(
'Content-Type: text/plain; charset="us-ascii"');
print $field->attribute('charset'); # --> us-ascii
print $field->attribute('bitmap') || 'no'; # --> no
$field->atrribute(filename => '/tmp/xyz');
$field->print;
# --> Content-Type: text/plain; charset="us-ascii";
# filename="/tmp/xyz"
# Automatically folded, and no doubles created.
π« $obj->attributes()
Returns a list of key-value pairs, where the values are not yet decoded. Keys may appear more than once and must be interpreted case insensitive (RFC2073 section 5.1).
Β» example β¨:
my @pairs = $head->get('Content-Disposition')->attributes;
π« $obj->comment( [STRING] )
Returns the unfolded comment (the part after a semi-colon) in a structured header-line, optionally after setting it to a new "STRING" first. When undef is specified as "STRING", the comment is removed. Whether the field is structured is defined by isStructured().
The comment part of a header field often contains "attributes". Often it is preferred to use attribute() on them instead. π
π« $any->dateToTimestamp(STRING)
Convert a "STRING" which represents an RFC compliant time string into a timestamp like the one produced by the local POSIX::time() function. Only applicable to fields which contain a date.
Better result:
my $df = $msg->study('Date') or return;
$df->time;
π« $any->stripCFWS( [STRING] )
Remove the comments and folding white spaces from the "STRING". Without a string and only as an instance method, the unfoldedBody() is the thing being stripped and returned.
β οΈ WARNING: This operation is only allowed for structured header fields (which are defined by the various RFCs as being so). You do not want parts within braces which are in the Subject header line to be removed, to give an example. π
π« $obj->study()
Study the header field in detail: turn on the full parsing and the detailed understanding of the content of the fields. Mail::Message::Field::Fast and Mail::Message::Field::Fast objects will be transformed into any Mail::Message::Field::Full object.
Β» example β¨:
my $subject = $msg->head->get('subject')->study;
my $subject = $msg->get('subject')->study; # same
my $subject = $msg->head->study('subject'); # same
my $subject = $msg->study('subject'); # same
$any->toDate( [$time] )β turns a timestamp into a rfc2822-compliant date format β¨ ngl this is not the same as whatlocaltimespits out in scalar context, so don't get it twisted. Leave the arg off and it grabs the current time fromlocaltime. You can pass$timeas one single number (like whatevertime()gives you) or as a list (like whatlocaltime()gives you in list context). π°οΈ
fr fr, set your timezone correctly β especially when this script runs automatically, bestie. No cap. π
Β» example:
my $now = time;
Mail::Message::Field->toDate($now);
Mail::Message::Field->toDate(time);
Mail::Message::Field->toDate(localtime);
Mail::Message::Field->toDate; # same
# returns something like:
# Wed, 28 Aug 2002 10:40:25 +0200
$obj->toInt()β hands you back the value tied to this field, but as an integer π and yeah, it does check whether that's actually the right move first.
π Parsing
$obj->consume( $line | <$name,<$body|$objects>> )β takes either a whole field$line, or a pair of the field's$nameand its$body. In that second case the$bodydata can come in as an array of$objectswhich then get stringified. What comes back is a nicely formatted pair of two strings: the field's name and a folded body π
This one is called by new(), and normally not by an application program. The deets on turning $objects into field content live in "Specifying field data".
$obj->defaultWrapLength( [$length] )β every field, from every header, for every message gets this default wrapping. It lives in one single global variable (iconic tbh). Give it no$lengthand you get the current value back. The default is 78.$any->fold( $name, $body, [$maxchars] )β makes the header field called$namefold into multiple lines. The wrapping happens by inserting newlines before blanks in$body, so that no line goes over$maxcharsand each line is as long as it possibly can be π
The RFC requests folding on nice spots, but that request is mostly ignored because it would make folding too slow. π periodt.
$obj->setWrapLength( [$length] )β forces this field to wrap at exactly$lengthcharacters. The wrapping is done withfold()and the results get stored inside the field object. π¦
Β» example: refolding the field
$field->setWrapLength(99);
$obj->stringifyData(STRING|ARRAY|$objects)β this method is the one implementing the translation of user-supplied objects into ascii fields. The whole process is explained in "Specifying field data".$obj->unfold(STRING)β the reverse action offold()π every line that forms the body of a field gets joined into one by removing all the line terminators (yes, even the last one). Any possible leading blanks on the first line get removed too.
π¨ Error handling
Extends "Error handling" in Mail::Reporter.
$obj->AUTOLOAD()β Inherited, see "Error handling" in Mail::Reporter$obj->notImplemented()β Inherited, see "Error handling" in Mail::Reporter
π§Ή Cleanup
Extends "Cleanup" in Mail::Reporter.
$obj->DESTROY()β Inherited, see "Cleanup" in Mail::Reporter
β¨ DETAILS β¨
π·οΈ Field syntax
Fields live in the header of a message, and those are represented by Mail::Message::Head objects. A field is a combo of a name, a body, and attributes. And the word "body"? Yeah, that's the thing that causes all the confusion β sometimes the attributes are considered to be part of the body too π΅βπ«
The name of the field is followed by a colon (":", not preceded by blanks, but followed by one blank). Each attribute is preceded by its own separate semi-colon (";"). Names of fields are case-insensitive and cannot contain blanks.
Β» Example: of fields
Correct fields:
Field: hi!
Content-Type: text/html; charset=latin1
Incorrect fields, but accepted:
Field : wrong, blank before colon
Field: # wrong, empty
Field:not nice, blank preferred after colon
One Two: wrong, blank in name
π Folding fields
Long fields can be folded so they span more than one line. The real limit for lines in messages is only at 998 characters, but ngl lines that long are not easy to read without an application helping you out. So rfc2822 (which defines the message syntax) says explicitly that field lines can be re-formatted into multiple shorter lines without any change of meaning, by adding new-line characters to any field before any blank or tab πΈ
Usually, lines get reformatted to create lines that are 78 characters maximum. Some applications try harder to fold on nice spots, like before attributes. The Received field especially is often manually folded into some nice layout. In most cases though, it's preferred to produce lines that are as long as possible but max 78.
BE WARNED that all fields can be subjected to folding, and that you usually want the unfolded value, bestie. π
Β» Example: of field folding
Subject: this is a short line, and not folded
Subject: this subject field is much longer, and therefore
folded into multiple
lines, although one more than needed.
π§ Structured fields
rfc2822 describes a large number of header fields explicitly, and those fields have a defined meaning. For some of them β like the Subject field β the meaning is straight forward the contents itself. Those are the Unstructured Fields.
Other fields have a well defined internal syntax, because their content is needed by e-mail applications. Like, the To field contains addresses which must be understood by all applications in the same way. Those are the Structured Fields β see isStructured() π
π¬ Comments in fields
Structured fields can contain comments, which are pieces of text enclosed in parenthesis. These comments can be placed close to anywhere in the line, and must be ignored by the application. Not all applications are capable of handling comments correctly in all circumstances though π
Β» Example: of field comments
To: mailbox (Mail::Box mailinglist) <mailbox@overmeer.net>
Date: Thu, 13 Sep 2001 09:40:48 +0200 (CEST)
Subject: goodbye (was: hi!)
On the first line, the text Mail::Box mailinglist is used as comment. Be warned that rfc2822 explicitly states that comments in e-mail address specifications should not be considered to contain any usable information.
On the second line, the timezone is specified as comment. The Date field format has no way to indicate the timezone of the sender, it only contains the timezone difference to UTC β however one could decide to add this as comment. Applications must ignore this data because the Date field is structured.
The last field is unstructured. The text between parentheses is an integral part of the subject line.
π«Ά Getting a field
As many programs as there are handling e-mail, that's how many variations on accessing the header information are requested π Be careful which way you access the data: read the variations described here and decide which solution suites your needs best.
π Using get() field
The get() interface is copied from other Perl modules which can handle e-mail messages. Many applications which simply replace Mail::Internet objects with Mail::Message objects will work without modification. Slay.
There is more than one get method, and the exact results depend on which get you use:
- When
Mail::Message::get()is called, you get the unfolded, stripped from comments, stripped from attributes contents of the field as string. Character-set encodings will still be in the string. - If the same fieldname appears more than once in the header, only the last value is returned.
When Mail::Message::Head::get() is called in scalar context, the last field with the specified name is returned as a field object. This object stringifies into the unfolded contents of the field, including attributes and comments. In list context, all appearances of the field in the header are returned as objects.
BE WARNED that some lines seem unique, but are not according to the official rfc. For instance,Tofields can appear more than once. If your program callsget('to')in scalar context, some information is lost π
Β» Example: of using get()
print $msg->get('subject') || 'no subject';
print $msg->head->get('subject') || 'no subject';
my @to = $msg->head->get('to');
π₯ Using study() field
As the name study already implies, this way of accessing the fields is much more thorough but also slower π The study of a field is like a get, but it provides easy access to the content of the field and handles character-set decoding correctly. It's giving main character energy, honestly.
- The
Mail::Message::study()method will only return the last field with that name as object. Mail::Message::Head::study()andMail::Message::Field::study()return all fields when used in list context.
Β» Example: of using study()
print $msg->study('subject') || 'no subject';
my @rec = $msg->head->study('Received');
my $from = $msg->head->get('From')->study;
my $from = $msg->head->study('From'); # same
my @addr = $from->addresses;
π Using resent groups
Some fields belong together in a group of fields. For instance, a set of lines is used to define one step in the mail transport process. Each step adds a Received line, and optionally some Resent-* lines and Return-Path. These groups of lines shall stay together and in order when the message header is processed.
The Mail::Message::Head::ResentGroup object simplifies the access to these related fields. These resent groups can be deleted as a whole, or correctly constructed π
Β» Example: of using resent groups
my $rgs = $msg->head->resentGroups;
$rgs[0]->delete if @rgs;
$msg->head->removeResentGroups;
π The field's data
There are many ways to get the field's info as object, and there are also many ways to process this data within the field.
π Access to the field
string()β Returns the text of the body exactly as will be printed to file whenprint()is called, so name, main body, and attributes.foldedBody()β Returns the text of the body, likestring(), but without the name of the field.unfoldedBody()β Returns the text of the body, likefoldedBody(), but then with all new-lines removed. This is the normal way to get the content of unstructured fields. Character-set encodings will still be in place. Fields are stringified into their unfolded representation.stripCFWS()β Returns the text of structured fields, where new-lines and comments are removed from the string. This is a good start for parsing the field, for instance to find e-mail addresses in them π¦Mail::Message::Field::Full::decodedBody()β studied fields can hand you the unfolded text decoded into utf8 strings. Yeah it's an expensive little process, but ngl it's the only correct way to get the field's data, fr fr. Especially useful for anyone not living their whole life in ASCII space π- Studied fields β these ones have powerful methods that let you reach in and produce the contents of (structured) fields exactly the way the involved rfcs say to. No vibes-based guessing, just spec-accurate slay β¨
Using simplified field access
Okay so some fields get accessed so constantly that there are support methods giving you simplified access. And the cutest part? All of these get called on a message directly. Main character behaviour honestly π
Β» Example: of simplified field access
print $message->subject;
print $message->get('subject') || ''; # same
my @from = $message->from; # returns addresses
$message->reply->send if $message->sender;
The sender method will hand you the address sitting in the Sender field, or the first one named in the From field. And if literally no address is known? It returns undef. Iconic, blunt, honest π«Ά
Specifying field data
So field data can be anything, and it's strongly dependent on the type of field you're holding. If you decide to construct your fields super carefully through some Mail::Message::Field::Full extension (like via Mail::Message::Field::Addresses objects), then you get protection built-in. But bestie, you can also just bluntly create any Mail::Message::Field object based on some random data. Your call π
When you create a field, you may specify a string, an object, or an array of strings and objects. At this moment in time, objects are only used to help the construction of e-mail addresses β though you're totally allowed to add some of your own πΈ
The following rules (implemented in stringifyData()) are obeyed, given the argument is:
- a string β the string has to follow the (complicated, obviously) rules of the rfc2822, and it gets made field content exactly as specified. When the string isn't terminated by a new-line (
\n), it will be folded according to the standard rules. - a Mail::Address object β the most used Perl object for parsing and producing address lines. Heads up though: this object does not understand character set encodings in phrases π
- a Mail::Identity object β as part of the User::Identity distribution, this object has full understanding of the meaning of one e-mail address, related to a person. All features defined by rfc2822 are implemented. Obsessed.
- a User::Identity object β a person is specified, which may have more than one
Mail::Identity's defined. Some methods, likeMail::Message::reply()andMail::Message::forward(), try to select the right e-mail address smart (see their method descriptions), but in other cases the first e-mail address found is used. - a User::Identity::Collection::Emails object β all
Mail::Identityobjects in the collection will be included in the field as a group carrying the name of the collection. - any other object β for all other objects, the stringification overload is used to produce the field content.
- an ARRAY β you may also specify an array with a mixture of any of the above. The elements will be joined as a comma-separated list. If you do not want comma's inbetween, you'll have to process the array yourself, bestie π
Β» Example: specifying simple field data
my $f = Mail::Message::Field->new(Subject => 'hi!');
my $b = Mail::Message->build(Subject => 'monkey');
Β» Example: s specifying e-mail addresses for a field
use Mail::Address;
my $fish = Mail::Address->new('Mail::Box', 'fish@tux.aq');
print $fish->format; # ==> Mail::Box <fish@tux.aq>
my $exa = Mail::Address->new(undef, 'me@example.com');
print $exa->format; # ==> me@example.com
my $b = $msg->build(To => "you@example.com");
my $b = $msg->build(To => $fish);
my $b = $msg->build(To => [ $fish, $exa ]);
my @all = ($fish, "you@example.com", $exa);
my $b = $msg->build(To => \@all);
my $b = $msg->build(To => [ "xyz", @all ]);
Β» Example: specifying identities for a field
use User::Identity;
my $patrik = User::Identity->new(
name => 'patrik',
full_name => "Patrik FΓ€ltstrΓΆm", # from rfc
charset => "ISO-8859-1",
);
$patrik->add(email => "him@home.net");
my $b = $msg->build(To => $patrik);
$b->get('To')->print;
# ==> =?ISO-8859-1?Q?Patrik_F=E4ltstr=F6m?=
# <him@home.net>
Field class implementation
For performance reasons only, there are three types of fields: the fast, the flexible, and the full understander π§
Mail::Message::Field::Fastβ "Fast" objects are not derived from aMail::Reporter. The consideration here is that fields are so often created, and such small objects at the same time. The fast field implementation uses an array to store the data: that will be faster than using a hash. Fast fields are not easily inheritable, because the object creation and initiation is merged into one method. Efficiency queen β¨Mail::Message::Field::Flexβ the flexible implementation uses a hash to store the data. Thenew()andinitmethods are split, so this object is extensible π¦Mail::Message::Field::Fullβ with a full implementation of all applicable RFCs (about 5), the best understanding of the fields is reached. However β and this is the catch, bestie β this comes with a serious memory and performance penalty. These objects are created from fast or flex header fields whenstudy()is called.
π DIAGNOSTICS π
- Error: class $package does not implement method $method. β Fatal error: the specific
$package(or one of its superclasses) does not implement this method where it should. This message means that some other related classes do implement this method however the class at hand does not. Probably you should investigate this and probably inform the author of the package. Cast bynotImplemented() - Warning: field content is not numerical: $content β the numeric value of a field is requested (for instance the
LinesorContent-Lengthfields should be numerical), however the data contains weird characters. Cast bytoInt() - Error: field name too long (max $count), in '$name'. β it is not specified in the RFCs how long a field name can be, but at least it should be a few characters shorter than the line wrap. Cast by
fold() - Warning: illegal character in field name $name. β a new field is being created which does contain characters not permitted by the RFCs. Using this field in messages may break other e-mail clients or transfer agents, and therefore mutulate or extinguish your message. Cast by
consume()
Yeah that last one is lowkey scary β illegal characters in a field name are not a vibe, and other mail clients might genuinely eat your message over it π
π SEE ALSO π
This module is part of Mail-Message version 4.04, built on February 04, 2026. Website: http://perl.overmeer.net/CPAN/ π
π LICENSE π
For contributors see file ChangeLog.
This software is copyright (c) 2001-2026 by Mark Overmeer.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
And that's a wrap on this page, bestie β perl v5.42.0, dated 2026-02-05, Mail::M...::Field(3), signed, sealed, delivered π Go forth and build your fields correctly, periodt πΈ
π¦ where this page comes from
- fedora 44: perl-Mail-Message 4.04-1.fc44 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms