Java Reference
In-Depth Information
The InternetAddress Class
An
InternetAddress
object represents an RFC 822-style email address. This is the
standard Internet-style email address that is rapidly supplanting all other proprietary
formats. It looks like
elharo@ibiblio.org
or
nuts@oreilly.com
. However, it can contain a
name as well—for instance,
elharo@ibiblio.org
(Elliotte Harold)
.
The state of an
InternetAddress
object is defined by three protected fields:
protected
String
address
protected
String
personal
protected
String
encodedPersonal
The
address
field is the actual email address—for example,
elharo@ibiblio.org
. The
personal
field is the name—for example,
Elliotte Harold
. Although Java strings are pure
Unicode that can express names like Erwin Schrödinger or
孔夫子
, the strings used in
mail headers must be pure ASCII in order to pass through most existing mail software.
Consequently, Java's Unicode strings need to be converted to pure ASCII using a sort of
hexadecimal escape. The details of this conversion are described in RFC 2047,
MIME
(Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for
Non-ASCII Text
. The encoded string is placed in the
encodedPersonal
field. All of these
fields will be initially set in the constructor. There are five overloaded constructors for
InternetAddress
objects:
public
InternetAddress
()
public
InternetAddress
(
String
address
)
throws
AddressException
public
InternetAddress
(
String
address
,
boolean
strict
)
throws
AddressException
public
InternetAddress
(
String
address
,
String
personal
)
throws
UnsupportedEncodingException
public
InternetAddress
(
String
address
,
String
personal
,
String
charset
)
throws
UnsupportedEncodingException
They are used exactly as you'd expect. For example:
Address
president
=
new
InternetAddress
(
"president@whitehouse.gov"
,
"Barack Obama"
);
Although two of these methods are declared to throw
UnsupportedEncodingExcep
tion
, this should happen only in the last method and then only if the name of the
character set is not recognized by the VM.
The two constructors declared to throw
AddressException
make basic checks that the
string passed is a syntactically correct email address. For instance, they check that the
address does not contain white space. However they don't check absolutely everything.
If you turn on strict checking, then a couple of other checks are made, primarily that
the address contains a domain name as well as a username. Otherwise raw names such
as “elharo” are allowed.