JavaMail in applets

General

Q: What is the JavaMail API?A: The JavaMail API is a set of
abstract APIs that model a mail system.
The API provides a platform independent and protocol independent framework
to build Java technology based email client applications.
The JavaMail API provides facilities for reading and sending email.
Service providers implement particular protocols.
Several service providers are included with the JavaMail API package;
others are available separately.
The JavaMail API is implemented as a Java optional package that can be
used on JDK 1.4 and later on any operating system.
The JavaMail API is also a required part of the
Java Platform,
Enterprise Edition (Java EE).

Q: How do I get an implementation of the JavaMail API?A: Oracle provides a royalty-free reference
implementation, in binary form, that developers may use and ship.
The reference implementation
includes the core JavaMail packages and IMAP, POP3, and SMTP service providers.
The reference implementation may be downloaded
here.

Q: What is IMAP?A: IMAP stands for Internet Message Access Protocol. It is a
method of accessing electronic mail messages stored on a (possibly shared)
mail server. In other words, it permits a "client" email program to
access remote message stores as if they were local. IMAP is defined
by RFC2060.

Q: What is SMTP?A: SMTP stands for Simple Mail Transfer Protocol. It is used
to transfer RFC822-style messages between different mail hosts as
well as to submit new messages to a host for delivery. SMTP is in
very wide use (it originated in 1982) and is defined by
RFC821.

Q: What is MIME?A: MIME and RFC822
are the standards for describing email
messages that are sent across the Internet. The javax.mail.internet
subpackage (which is part of the JavaMail APIs) provides a complete
implementation of these two packages. MIME is specified by the
following RFCs: RFC2045,
RFC2046,
RFC2047.

Q: What is POP3?A: POP3 stands for Post Office Protocol version 3.
POP3 is a very limited protocol for accessing a single mailbox.
It is much less capable than IMAP.
POP3 is very widely used and is defined by
RFC1939.

Q: How do I store mail messages on my local disk?A: A "local store provider" can be used to store mail messages
on a local disk. The JavaMail API download does not include such a provider
but a provider that supports the Unix mbox format is available in the JavaMail
source repository that you can build yourself. See
this page
for details.
In addition, several local store providers are available from third parties
for different local store formats such as MH and Mbox.
See our Third Party Products page
for the latest list of such providers.

Q: Where do I find documentation on the protocol providers?A: The protocol providers for IMAP, POP3, and SMTP support
many features that are not part of the JavaMail API specification. The
documentation for these protocol providers is included in the JavaMail
javadocs. The package level documentation for each protocol provider
package describes the properties that are supported by the protocol
proivder. In addition, the protocol providers include some classes and
methods that applications can use to take advantage of
provider-specific features. Note that use of these properties,
classes, and methods renders a program non-portable; it may
only work with Oracle's implementation of the JavaMail API.
See the
IMAP,
POP3, and
SMTP package
javadocs for details.

Installation and Configuration

Q: How do I install the JavaMail API implementation?A: Download the
[JavaMail jar file](https://github.com/eclipse-ee4j/javamail/releases/download/1.6.3/jakarta.mail.jar)
and edit your CLASSPATH environment variable to include the jakarta.mail.jar file.
You will also need an implementation of the
JavaBeans Activation Framework (see below) unless you're using JDK 1.6
through JDK 10 (which includes JAF).
See the README.txt file
for additional details and examples,
as well as the following FAQ entry.

Select the "Classpath" tab on the right and choose
<Add Jar/Folder...>

Using the file browser, select the jakarta.mail.jar that you downloaded,
and hit <Add Jar/Folder> to accept.

Select the "Javadoc" tab and choose <Add ZIP/Folder...>

Using the file browser, select the folder where the JavaMail javadoc
index files are, and hit <Add ZIP/Folder> to accept.

If you downloaded the JavaMail source code, you
can set the source code reference on the "Sources" tab. This can be helpful
for debugging. Using the file browser, select the source root for the
JavaMail sources and hit <Add Jar/Folder> to accept.

Note: If you are using JDK 1.5.0 or earlier you will need to add the
JavaBeans Activation Framework
library as well. You can create a separate library in a manner similar to
the above, or just add activation.jar (and javadoc/source references
if desired) to this library definition.

Now add a reference to this library to your project.

Open your project in NetBeans and make sure the "Projects" tab is
visible.

Right click your project in the project explorer and select
"Properties"

In the Properties dialog, select "Libraries" in the tree on the left
and make sure the "Compile" tab is selected.

Click <Add Library...>

Locate and select the library you created above and
click "Add Library". It should be added to the list of compile-time
libraries.

In the new library dialog, enter a user library name, e.g. "JavaMail",
and hit <OK>. Do not check system library.

Make sure the new library is selected and choose <Add Jars...>

Browse to where JavaMail is installed and select jakarta.mail.jar

Select <Javadoc location: (None)> and hit <Edit...> to
add a reference to the javadoc location. This can be found at docs/javadocs
under the same folder where you installed JavaMail.

You can also set the source code reference here if you downloaded the
JavaMail source code. Use
".../javamail-1.6.3/mail/src/main/java" as the source root for 1.6.3.

Choose <OK> to close the Preferences dialog. JavaMail is now
installed as a Library in Eclipse.

Note: If you are using JDK 1.5.0 or earlier you will need to add the
JavaBeans Activation Framework
library as well. You can create a separate library in a manner similar to
the above, or just add activation.jar (and javadoc/source references
if desired) to this library definition.

Now use the JavaMail library in your Eclipse Java Project (Eclipse 3.4)

In the Properties dialog that opens, ensure Java Build Path is selected
in the tree on the left and select the Libraries tab on the right

Click <Add Library...>

Select "User Library", then click <Next>

Locate and select the JavaMail library added in the previous step,
click "Finish", and you're done.

This article
explains how to make the JavaMail source code available to your Eclipse project.

Q: Does JavaMail include all the necessary mail servers? A: No, the JavaMail API package does not include any mail servers.
To use the JavaMail API package, you'll need to have access to an IMAP
or POP3 mail server (for reading mail) and/or an SMTP mail server (for
sending mail).
These mail servers are usually provided by your Internet Service Provider
or are a part of your organization's networking infrastructure.
If you don't have access to such a mail server, see below.

Q: Where can I get the necessary mail servers?A:
The University of Washington IMAP server supports multiple platforms
(UNIX, Windows 32bit, etc).
Get the source code from
http://www.washington.edu/imap/.
There are several free, all Java mail servers available, including
Apache James and
Java Email Server.
Sendmail is a popular (non-Java) SMTP server.
SubEthaSMTP
is a Java library for implementing SMTP server functionality;
their web page also references other mail servers.
Many other vendors provide mail servers supporting Internet standards.
There are also many free, public mail servers that support the required
mail protocols such as Gmail, Yahoo! Mail, Hotmail, etc.

Q: What host name, user name, or password should I use?A: We do not provide a mail server for you to use. You must use your
own mail server, or one provided by your Internet Service Provider
or the company you work for. Your network administrator can give you
the information necessary to configure JavaMail to work with your mail server.

Q: How do I configure JavaMail to work through my proxy server?A: Starting with JavaMail 1.6.0, JavaMail supports accessing
mail servers through a web proxy server.
Set the "mail.protocol.proxy.host" and "mail.protocol.proxy.port"
properties for the proxy server.
Note that proxy server authentication is not supported.

In addition, if your proxy server supports the SOCKS V4 or V5 protocol
(http://www.socks.nec.com/aboutsocks.html,
RFC1928)
and allows anonymous connections, and
you're using JDK 1.5 or newer and JavaMail 1.4.5 or newer, you can
configure a SOCKS proxy on a per-session, per-protocol basis by setting the
"mail.smtp.socks.host" property as described in the javadocs for the
com.sun.mail.smtp package.
Similar properties exist for the "imap" and "pop3" protocols.

If you're using older versions of the JDK or JavaMail, you can tell the Java
runtime to direct all TCP socket connections to the SOCKS server.
See the
Networking Properties guide
for the latest documentation of the socksProxyHost and
socksProxyPort properties. These are system-level properties,
not JavaMail session properties. They can be set from the command line
when the application is invoked, for example:
java -DsocksProxyHost=myproxy ....
This facility can be used to direct the SMTP, IMAP, and POP3
communication from JavaMail to the SOCKS proxy server. Note that
setting these properties directs all TCP sockets to the SOCKS
proxy, which may have negative impact on other aspects of your
application.

When using older versions of JavaMail, and without such a SOCKS server,
if you want to use JavaMail to access mail servers
outside the firewall indirectly, you might be able to use a program such as
connect
to tunnel TCP connections through an HTTP proxy server.
Configure JavaMail to use the connect instance as the SOCKS server.

The problem is due to a buggy version of the unzip command used to unzip
the JavaMail download package on Linux. The unzip command corrupts the
jakarta.mail.jar file. Get a newer version of the unzip command, or use the
JDK's jar command to unzip the package.

There are a number of debugging techniques that can be used to determine
if this is the problem. Setting the Session property "mail.debug" to
true (or calling session.setDebug(true)) will cause JavaMail
to print debugging messages as it attempts to load each configuration
file. A message of the form "DEBUG: can't load default providers file"
indicates that this problem might exist. Similarly, setting the System
property "javax.activation.debug" to "true" (e.g., by running the
program using "java -Djavax.activation.debug=true ...") will cause JAF
to print debugging messages as it attempts to load each resource file.
Finally, the JDK can produce helpful debugging output by setting the
system property "java.security.debug" to "access:failure" (e.g., by
running the program using "java -Djava.security.debug=access:failure ...").
The command java -Djava.security.debug=help will display
other security debugging options.

In addition to the permissions necessary to read the configuration files,
the application (and JavaMail) will also need permission to connect to the
mail servers it uses. If the application uses System properties to
configure JavaMail (e.g., by passing the Properties object returned from
System.getProperties() to the Session constructor, as many
of the JavaMail demo programs do), it will also need permission to use
the System Properties object. Alternatively, the application can use
its own Properties object and be sure to set the "mail.from" property
or the "mail.user" and "mail.host" properties (see the
InternetAddress.getLocalAddress() method).

To allow an application to use JavaMail under a SecurityManager,
the application, JavaMail, and JAF will need permissions such as the
following (be sure to replace the host and path names with appropriate
values); add these to the security policy file used by the application:

If you don't want to give the application read/write permission to
System properties, but you still want to be able to use System properties
to configure the application, you can give the application only "read"
permission to System properties and use the following approach:

Q: How do I access Gmail with JavaMail? A:
JavaMail is capable of sending and reading messages using Gmail.
All that's required is to properly configure JavaMail. I'll
illustrate the proper configuration using the
demo programs that come with JavaMail -
msgshow.java and smtpsend.java.
You can use these programs for basic testing to ensure that
your networking is working properly, that you can connect to
the servers, that your username and password are correct, etc.
This is important when debugging problems to determine whether
the bug is in your code or is elsewhere.

By reading the msgshow.java source code, you can see how these
command line arguments are used in the JavaMail API. You should
first try using msgshow as shown above, and once that's working
move on to writing and configuring your own program to use Gmail.
The following code fragment shows a simple way to incorporate the
needed configuration in your application:

To connect to Gmail using the POP3 protocol instead of the IMAP protocol,
simply change the host name "imap.gmail.com" to "pop.gmail.com" and change
"imap" to "pop3" in the property name and protocol name in the above
instructions.

The smtpsend program will prompt for a subject and message body text.
End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the
command line arguments are used in the JavaMail API.
The following code fragment shows a simple way to incorporate the
needed configuration in your application:

Q: How do I delete a message in Gmail?
A:
Gmail does not follow the normal IMAP conventions for deleting messages.
Marking a message as deleted and then expunging the folder simply removes
the current folder's "label" from the message. The message will still
appear in the "[Gmail]/All Mail" folder.
To delete a message, copy the message to the "[Gmail]/Trash" folder,
which will immediately remove the message from the current folder.
To permanently remove a message, open the "[Gmail]/Trash" folder,
mark the message deleted (msg.setFlag(Flags.Flag.DELETED, true);),
and expunge the folder (folder.close(true);).

Q: How do I access Yahoo! Mail with JavaMail? A:
JavaMail is capable of sending and reading messages using Yahoo! Mail.
All that's required is to properly configure JavaMail. I'll
illustrate the proper configuration using the
demo programs that come with JavaMail -
msgshow.java and smtpsend.java.

By reading the msgshow.java source code, you can see how these
command line arguments are used in the JavaMail API. You should
first try using msgshow as shown above, and once that's working
move on to writing and configuring your own program to use Yahoo! Mail.
The code fragment shown above for connecting to Gmail will also work for
connecting to Yahoo! Mail by simply changing the host name.

The smtpsend program will prompt for a subject and message body text.
End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the
command line arguments are used in the JavaMail API. The code fragment shown
above for connecting to Gmail will also work for connecting to Yahoo! Mail
by simply changing the host name.
There is, of course, more than one way to use the JavaMail API to accomplish
the same goal. This should help you understand the essential
configuration parameters necessary to use Yahoo! Mail.

By reading the msgshow.java source code, you can see how these
command line arguments are used in the JavaMail API. You should
first try using msgshow as shown above, and once that's working
move on to writing and configuring your own program to use Hotmail.
The code fragment shown above for connecting to Gmail will also work for
connecting to Hotmail by simply changing the host name.

(Note that I split the command over three lines for display, but you
should type it on one line.)

The smtpsend program uses the System properties
when creating the JavaMail Session, so the properties set on the
command line will be available to the JavaMail Session.

The smtpsend program will prompt for a subject and message body text.
End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the
command line arguments are used in the JavaMail API. The code fragment shown
above for connecting to Gmail will also work for connecting to Hotmail
by simply changing the host name and changing the connect call to
t.connect(host, 587, username, password).
There is, of course, more than one way to use the JavaMail API to accomplish
the same goal. This should help you understand the essential
configuration parameters necessary to use Hotmail.

Q: How do I access Outlook.com with JavaMail? A:
JavaMail is capable of sending and reading messages using Outlook.com.
All that's required is to properly configure JavaMail. I'll
illustrate the proper configuration using the
demo programs that come with JavaMail -
msgshow.java and smtpsend.java.

By reading the msgshow.java source code, you can see how these
command line arguments are used in the JavaMail API. You should
first try using msgshow as shown above, and once that's working
move on to writing and configuring your own program to use Outlook.com.
The code fragment shown above for connecting to Gmail will also work for
connecting to Outlook.com by simply changing the host name.

To connect to Outlook.com using the POP3 protocol instead of the IMAP protocol,
simply change the host name "imap-mail.outlook.com" to "pop-mail.outlook.com"
and change the protocol name "imaps" to "pop3s" in the above instructions.

(Note that I split the command over three lines for display, but you
should type it on one line.)

The smtpsend program uses the System properties
when creating the JavaMail Session, so the properties set on the
command line will be available to the JavaMail Session.

The smtpsend program will prompt for a subject and message body text.
End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the
command line arguments are used in the JavaMail API.
The following code fragment shows a simple way to incorporate the
needed configuration in your application:

There is, of course, more than one way to use the JavaMail API to accomplish
the same goal. This should help you understand the essential
configuration parameters necessary to use Outlook.com.
For more details, see the
Outlook Blog.

Use of Session.getDefaultInstance.
Almost all code should use Session.getInstance instead,
as described below

Calling the send method on a Transport instance variable.
As described below, send is a static
method and ignores the Transport instance you use to call it.

Setting various socketFactory properties.
Long, long ago JavaMail didn't have built in support for SSL connections,
so it was necessary to set these properties to use SSL.
This hasn't been the case for years; remove these properties and simplify
your code.
The easiest way to enable SSL support in current versions of JavaMail is
to set the property "mail.smtp.ssl.enable" to "true".
(Replace "smtp" with "imap" or "pop3" as appropriate.)

Using an Authenticator just to supply a username and password.
There's really nothing wrong with using an Authenticator, it's just
unnecessarily complex.
A more straightforward approach is to call the connect
method that takes a username and password when connecting to a Store.
When sending a message, use the static Transport.send method
that takes a username and password.

Q: How do I send a message with an attachment?A: A message with attachments is represented as a
MIME multipart message where the first part is the main body of the
message and the other parts are the attachments.
There are numerous examples showing how to construct such a message
in the demo programs included in the JavaMail download package.
To attach a file use the
attachFile method of MimeBodyPart.

Q: How do I tell if a message has attachments?A: In the simplest case, a message of MIME type
multipart/mixed with more than one body part is likely
a message with attachments. As described above, there are more complex
cases to consider as well. In particular, messages may have arbitrary
nesting of multipart/mixed and multipart/alternative
parts and may include multipart/related parts for embedded
HTML and multipart/signed and/or multipart/encrypted
parts for secure messages. It's up to you to decide how many of these
cases you want to handle in your application before deciding that a
message has an attachment. Most applications take a very simple approach
to this and handle only a few of the most commonly seen cases.

Note that while it's recommended that attachments have a Content-Disposition
of "ATTACHMENT", and will usually have a file name, these are not requirements.
Some messages with attachments will have only one or none of these. Looking
for attachments by looking for a body part with these set will fail in some
cases.

In the simplest case, here's how to tell if a message has attachments:

Q: How do I read a message with an attachment and save the
attachment?A: As described above, a message with an attachment is
represented in
MIME as a multipart message. In the simple case, the results of the
Message object's getContent method will be a
MimeMultipart object. The first body part of the multipart
object wil be the main text of the message. The other body parts will
be attachments. The msgshow.java demo program shows how
to traverse all the multipart objects in a message and extract the data
of each of the body parts. The getDisposition method will
give you a hint as to whether the body part should be displayed inline
or should be considered an attachment (but note that not all mailers
provide this information). So to save the contents of a body part in a file,
use the saveFile method of MimeBodyPart.

To save the data in a body part into a file (for example), use the
getInputStream method to access the attachment content and
copy the data to a FileOutputStream.
Note that when copying the data you can not use the
available method to determine how much data is in the
attachment. Instead, you must read the data until EOF.
The saveFile method of MimeBodyPart will
do this for you.
However, you should not use the results of the getFileName
method directly to name the file to be saved; doing so could cause you
to overwrite files unintentionally, including system files.

Note that there are also more complicated cases to be handled as well.
For example, some mailers send the main body as both plain text and
html. This will typically appear as a multipart/alternative
content (and a MimeMultipart object) in place of a simple
text body part. Also, messages that are digitally signed or encrypted
are even more complex. Handling all these cases can be challenging.
Please refer to the various MIME specifications and other
resources listed on our main page.

You can call the getText method with a Message
object (which is a Part).

Q: How do I find the attachments in a message? A:
There's a wide variety of possible MIME structures for email. A general
solution can be quite complex since it would need to take into account
signed and encrypted messages, among other issues. Different mailers
will use different MIME structure, and of course some mailers will have
bugs in how they use MIME. You need to decide which cases you need to
support.

In general, multipart/alternative is used to contain different versions
of the main message body, and so can be skipped because it doesn't
contain any attachments. Typically, a message with attachments will
have a top level multipart/mixed content with the first body part
containing the main message body. The first part may be a simple text
part, a multipart/alternative with text/plain and text/html parts, or a
multipart/related with a text/html part and associated images.

Attachments will usually, but not always, have a Content-Disposition of
attachment. Attachments will usually, but not always, have a file
name.

So, a good approach to start with is to only consider messages with a
top level multipart/mixed content and then consider the parts after the
first part to be attachments whether they say so or not. And as I said
above, signed and encrypted messages will make this more complex.

And of course you should always make sure the message you're dealing with is
a multipart message before calling the getContent method, using something like
if (msg.isMimeType("multipart/*")), as described
above and in this example.

Q: When I attach a file it gets a MIME type of
application/octet-stream instead of the correct MIME type. A: The FileDataSource class uses the JavaBeans Activation
Framework (JAF) class MimetypesFileTypeMap to determine the
MIME type of a file based on the extension of the filename.
The default mapping knows about only a few extensions.
You can add support for more extensions either programmatically
or by adding a META-INF/mime.types configuration file
to your application.
For example, to map the .doc extension to the MIME type
application/msword, create a META-INF/mime.types
file with the single line:

Q: How do I create a multipart message with a part of any
MIME type I choose?A: The JavaMail API includes builtin support for the most
common MIME types, but to create a message that includes data in
a MIME type that JavaMail does not already understand, you'll
need to supply that data to JavaMail in a byte stream format.
The ByteArrayDataSource class in the javax.mail.util
pacakge in JavaMail 1.4 and later, or included in source code in the demo
directory of older versions of the JavaMail download package, can help.
This class
will take a String, byte array, or InputStream
and create a DataSource object that you can use as follows:

You can specify any MIME type that you want. The MimeBodyPart
object can then be added to a MimeMultipart object in the
usual way.

Note that if you create a ByteArrayDataSource with an
InputStream, it first copies all of the data in the stream
into memory. This is necessary because a DataSource needs
to be able to supply multiple InputStream objects so that
JavaMail can read the data once to determine what
Content-Transfer-Encoding is appropriate, and then read the data again
to include the data in the message.

Q: When should I use Session.getDefaultInstance
and when should I use Session.getInstance? A: Almost all code should use Session.getInstance.
The Session.getDefaultInstance method creates a new Session the
first time it's called, using the Properties that are passed.
Subsequent calls will return that original Session and ignore any
Properties you pass in.
If you want to create different Sessions with different properties,
Session.getDefaultInstance won't do that.
If some other code in the same JVM (e.g., in the same app server) has already
created the default Session with their properties, you may end up using their
Session and your properties will be ignored.
This often explains why your property settings seem to be ignored.
Always use Session.getInstance to avoid this problem.

Q: What is "disconnected support"?A: A mail client supporting disconnected operation will allow
the user to access messages in a remote message store (e.g.,
IMAP), cache (parts of) some of those messages locally, and
break the connection to the server. While in this disconnected
state, the mail client can access the messages that have been
cached, possibly deleting them or saving them to other folders.
When the mail client next connects to the remote message store,
the changes made locally will be synchronized with the remote
store. Similarly, disconnected support may allow the client
to "send" messages when there is no connection to the server, with
the messages being queued until a connection to the server is
available. See also
RFC 1733 and
RFC 4549.

Q: Can I use the JavaMail APIs to implement a
mail server?A: The JavaMail APIs were not intended to help you implement a
mail server.
Nonetheless, some of the utility classes, such as the MIME
message parsing classes, might be of use to you.
In general you'll find that the JavaMail API errs on the side
of "simple" instead of "robust". That's appropriate for a mail
client, but a mail server would likely make different tradeoffs.

Q: Can I use the JavaMail APIs to access my address book
on my mail server?A: The JavaMail API does not include any facilities for accessing
an address book. There are no standards in this area;
every mail server handles this differently.
If you can figure out how your server does it, you might be able
to find a Java API to access it. For example, if your server stores
address books in LDAP, you could use the JNDI API to access it.

The hard part about serializing a Message is retaining the pointers to
the Folder, Store, and Session. If you only want to save the content
of the message, and not the object itself, the writeTo
method of a message gives you everything you need.
If you want to create an entire email system based on serialized messages,
you should be able to subclass Message et. al. and implement Serializable
in your subclass.

If you want to serialize other objects of your own that reference
MimeMessages, the writeObject method of your object can use the
writeTo method of MimeMessage, and the readObject
method of your object can use the MimeMessage constructor that takes an
InputStream. Your class will need to provide a Session when constructing
the MimeMessage.

Q: How do I write a Service Provider?A: Please read the Service Provider documentation for details.
In general, if you want to write a Store provider, you subclass
javax.mail.Store, javax.mail.Folder, possibly
javax.mail.Message and a few others. For a Transport
provider, you subclass javax.mail.Transport, possibly
javax.mail.Message and a few others. Then you add
the entry describing your provider to the javamail.providers
registry. If you're interested in writing a service provider for a protocol
or messaging system not currently supported by the JavaMail API
implementation, please contact us at
javamail_ww@oracle.com.

Note also that there's a bug in Exchange 2007. The Exchange server
advertises that it supports AUTH=PLAIN, even though
this Exchange documentation claims that it's not supported.
This causes JavaMail to choose PLAIN authentication, which will always fail.
To work around this Exchange bug, set the session property
"mail.imap.auth.plain.disable" to "true". (Change "imap" to "imaps" if
you're using the "imaps" protocol.)

Q: If I don't need to encode and decode attachments myself,
when should I use the MimeUtility methods?
A: The MimeUtility methods are useful in cases that
JavaMail doesn't handle automatically for you. One such case that
occurs frequently is encoding of filenames. The base MIME spec does not
allow header parameter values (such as the filename parameter) to be
encoded in the same way that (e.g.) the Subject header may be encoded.
This restricts parameter values, and thus filenames, to ASCII. However,
some mailers actually do encode non-ASCII filenames using the MIME text
encoding. Applications that wish to interoperate with such non-standard
mailers can use the encodeText method to encode filenames
before calling the MimeBodyPartsetFileName method,
and can use the decodeText method to decode returned filenames.
See also this entry below if you need to
encode filenames.

The base MIME spec does not allow for encoding parameters.
RFC 2231 defines a new way to include encoded paramters,
including filenames, in MIME headers. It is not
compatible with the de facto way that many older applications
illegally encode filenames. Even though JavaMail supports RFC 2231, that
alone does not allow JavaMail to interoperate with these older
programs. Most recent email programs support RFC 2231 and JavaMail
enables support for it by default starting in JavaMail 1.5.
To enable RFC 2231 support in older JavaMail releases for encoded parameters,
set the System properties "mail.mime.encodeparameters" and
"mail.mime.decodeparameters" to "true".

If you choose to violate the MIME spec, in order to
interoperate with other programs that also violate the
MIME spec, JavaMail gives you all the tools you need to
do so. Starting with JavaMail 1.4, setting the System properties
"mail.mime.encodefilename" and "mail.mime.decodefilename" to "true"
will cause JavaMail to encode and decode the filename parameter
using the non-RFC 2231 MIME encoding.

Applications using earlier versions of JavaMail can use the following
workaround to encode a filename:

mbp.setFileName(MimeUtility.encodeText(filename));

The workaround for decoding a filename is equally simple:

String filename = MimeUtility.decodeText(part.getFileName());

Again, this is primarily for applications using old versions of JavaMail.
Most applications should never need to use these methods.

Debugging

Q: How do I debug my application that uses JavaMail APIs?A: Turn on session debugging by invoking the method
setDebug(true)
on the Session object in your code. That will cause debug information to
be printed to the console, including a protocol trace.
If you passed the System properties to the Session when you created it,
you can simply run your program with java -Dmail.debug=true ...
If you think that you found a bug in JavaMail,
send us this trace along with a test case that reproduces the problem,
the platform you are using, the version of the JDK you are using, and
the name and version of the mail servers (IMAP, SMTP) that you are using.

Q: How do I debug problems connecting to my mail server?A: The first thing to do when debugging such problems is to
determine whether it's a Java problem or a networking problem.
Use telnet to try to connect to the remote system. For
example, if you're having trouble connecting to the POP3 server named
mail.example.com, you would use:

telnet mail.example.com 110

If you're trying to connect to an SMTP server, use 25 instead of 110
for the port number. If you're trying to connect to an IMAP server
use 143 for the port number.

If you get a greeting banner you can simply disconnect.
If this works, your
networking, name service, firewall, etc. are all set up
correctly and your problem is most likely in your Java
program.

If it doesn't work, you'll need to check your networking
configuration or talk to your network administrator for help.
Sometimes a firewall installed on your local machine or on
your network will prevent you from connecting to the server.
If telnet complains that it doesn't know the host name that
you're using, most likely your name service (e.g., DNS) isn't
properly configured to resolve internet host names.
None of these problems are JavaMail or Java problems.

Usually, when you get a low level SocketException
when connecting, the problem is due to your networking
configuration. Usually it's not a Java problem.

If you've succeeded in connecting with telnet, the next thing
to do is to turn on Session debugging and get the protocol
trace when JavaMail tries to connect to the remote machine,
as described above.
This will often include more detailed error messages from the
server that will indicate the real source of the problem.

Q: How do I debug problems with Java security permissions? A: You can set the java.security.debug System property
to debug problems with Java security permissions.
To get the possible values for setting that property, the following command
will print a help message: java -Djava.security.debug=help MyClass

Reading mail, IMAP

Q: I tried running your demos against my IMAP server,
but I get an error.A: First verify that you indeed have an email account on the IMAP
server. Check with your system administrator about it.
Turn debug mode on, by invoking the method setDebug(true) on
the session object in your code. This will cause the IMAP
protocol trace to be dumped on your screen. Send us this trace.
The trace will be very useful to us for identifying the problem.
If you can, please send us vendor information about your IMAP
server.

The best approach when running into server bugs of this sort is to contact
the vendor of the server and get them to fix their product. Contact
javamail_ww@oracle.com and we'll help you
pinpoint the problem so that you can report it to the server vendor.
If you can't get a fix from the server vendor, the following technique
will often allow you to work around these server bugs:

// Get the message object from the folder in the
// usual way, for example:
MimeMessage msg = (MimeMessage)folder.getMessage(n);
// Use the MimeMessage copy constructor to make a copy
// of the entire message, which will fetch the entire
// message from the server and parse it on the client:
MimeMessage cmsg = new MimeMessage(msg);
// The cmsg object is disconnected from the server so
// setFlags will have no effect (for example). Use
// the original msg object for such operations. Use
// the cmsg object to access the content of the message.

In some cases, the server may be so badly broken that loading the envelope
data is not possible, which can cause the above workaround to fail because
internally it first fetches the message flags and message size from the server.
In that case, the following approach will usually work:

// Get the message object from the folder in the
// usual way, for example:
MimeMessage msg = (MimeMessage)folder.getMessage(n);
// Copy the message by writing into a byte array and
// creating a new MimeMessage object based on the contents
// of the byte array:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
msg.writeTo(bos);
bos.close();
SharedByteArrayInputStream bis =
new SharedByteArrayInputStream(bos.toByteArray());
MimeMessage cmsg = new MimeMessage(session, bis);
bis.close();
// The cmsg object is disconnected from the server so
// setFlags will have no effect (for example). Use
// the original msg object for such operations. Use
// the cmsg object to access the content of the message.

Q: Does the IMAP provider cache the retrieved data?A: The IMAP provider fetches the data for a message from the server only
when necessary. (The javax.mail.FetchProfile can be used
to optimize this).
The header and bodystructure information, once fetched, is always
cached within the Message object. However, the content of a bodypart
is not cached. So each time the content is
requested by the client (either using getContent() or
using getInputStream()), a new FETCH request is issued
to the server.
The reason for this is that the content of a message could be
potentially large, and if we cache this content for a large number
of messages, there is the possibility that the system may
run out of memory soon since the garbage collector cannot free
the referenced objects.
Clients should be aware of this and must hold on to the retrieved
content themselves if needed.

Q: Retrieving large message bodies seems inefficient at times.A: If you are using the IMAP provider, you could try increasing
the mail.imap.fetchsize property (the current default is 16k).
This will cause data to be fetched from the server in larger chunks.
Note that you risk the possibility of the JVM running out of memory
when you do this.

Q: I get OutOfMemory errors when loading this large binary attachement.
A: Increase the maximum JVM heapsize at startup. Use the "-mx" option
if using the standard JVM from Oracle.
Don't keep references to the "content" of messages not being used.
In certain cases, you could try streaming the message content
(using getInputStream()) as raw bytes, use and then discard the
used data chunks.

Q: Why do I get the UnsupportedDataTypeException when I invoke
getContent() on a bodypart?A: The getContent() method returns a Java object that
represents
the bodypart content. For this to work, a JAF DataContentHandler
corresponding to the content's MIME type must be registered. Otherwise, the
UnsupportedDataTypeException will be thrown. In this case, you
can use the getInputStream() method to retrieve the content as
a stream of bytes. See the JAF docs for details on how to create
and register your own DataContentHandlers.

Q: Why do I get the UnsupportedEncodingException when I invoke
getContent() on a bodypart that contains text data?A: Textual bodyparts (i.e., bodyparts whose type is "text/plain",
"text/html", or "text/xml")
return Unicode String objects when getContent() is used.
Typically,
such bodyparts internally hold their textual data in some non Unicode
charset. JavaMail (through the corresponding DataContentHandler)
attempts to convert that data into a Unicode string.
The underlying JDK's charset converters are used to do this.
If the JDK does not support a particular charset, then the
UnsupportedEncodingException is thrown.
In this case, you can use the getInputStream() method to retrieve
the content as a stream of bytes.
For example:

You can also add an alias for an existing charset already supported
by the JDK so that it will be known by an additional name.
You can create
a charset provider for the "bad" charset name that simply redirects to
an existing charset provider; see the following code.
Create an appropriate CharsetProvider subclass and include it along with the
META-INF/services file and the JDK will find it.
Obviously you could get significantly more clever and redirect all
unknown charsets to "us-ascii", for instance.

Part of the key to understanding how this works is understanding when
the server is allowed to notify the client of new messages, and when
JavaMail will see those notifications. Between getting the number of
messages and adding the listener, JavaMail won't see any notifications
of new messages. By the time you do an operation that will allow
JavaMail to see the notification, the listener will be in place.

The following code illustrates the general approach. Many details have
been omitted.

Sending mail, SMTP

Q: How do I reply to a message?
A: To reply to a message, use the reply method
on the Message object. This method will return a new object with the
headers set appropriately for a reply. You'll need to supply the content
of the message yourself.
If you have the content of the original message as a String, you can use
a simple method such as the following to create the prototypical reply
text, which inserts "> " in front of each line:

Q: How do I forward a message?
A: The approach used to forward a message depends on how you want
to present the forwarded message.
It's straightforward to create a new MimeMessage, address it appropriately,
and attach an existing message as an attachment to the new message.
To attach the original message to the new message, use code such as:

MimeMessage msg = new MimeMessage(session);
// set To, From, Subject, Date, etc.
MimeMultipart mp = new MimeMultipart();
// create a body part to contain whatever text you want to include
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("Here's the forwarded message\n");
mp.addPart(mbp);
// create another body part to contain the message to be forwarded
MimeBodyPart fmbp = new MimeBodyPart();
// forwardedMsg is the MimeMessage object you want to forward
// as an attachment
fmbp.setContent(forwardedMsg, "message/rfc822");
fmbp.setDisposition(Part.ATTACHMENT);
mp.addPart(fmbp);
msg.setContent(mp);

If instead you want to create the new message with the text of the
original message included in the new message, to forward the message
"inline", you can use an approach such as the following:

(You'll have to write the formatAddressList method using
the toUnicodeString method of InternetAddress.
You'll also want to include appropriate error checking and test for null
values.)

Q: How do I send HTML mail?A: There are a number of demo programs included with the
distribution that show how to send HTML mail. If you want to
send a simple message that has HTML instead of plain text, see
the sendhtml.java program in the demo directory.
If you want to send an HTML file as an attachment, see the
sendfile.java example that shows how to send any file
as an attachment.

Q: How do I send HTML mail that includes images?
A: The simplest approach is to send HTML text with image tags
that reference images on a public web site. In this approach the
images aren't actually included in the message, and so won't be visible
if the user is not connected to the Internet when they read the message.
Note also that some mailers will refuse to display images that are on
remote sites.

Another approach is to include the image data inline in the html content
of the message, for example:

<img src="data:image/jpeg;base64,base64-encoded-data-here" />

This works best for relatively small images.

Alternatively, you can construct a MIME multipart/related
message. See RFC2387
for details of the structure of such a message.
A simple example follows:

Multipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
// messageBody contains html that references image
// using something like <img src="cid:XXX"> where
// "XXX" is an identifier that you make up to refer
// to the image
htmlPart.setText(messageBody, "utf-8", "html");
multipart.addBodyPart(htmlPart);
MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
imgPart.attachFile(imageFile);
// or, if the image is in a byte array in memory, use
// imgPart.setDataHandler(new DataHandler(
// new ByteArrayDataSource(bytes, "image/whatever")));
// "XXX" below matches "XXX" above in html code
imgPart.setContentID("<XXX>");
multipart.addBodyPart(imgPart);
message.setContent(multipart);

Q: What's the difference between the Transport methods
send and sendMessage?
A: The send() method is a static method and can be
used without needing an instance of a Transport object. It is intended
for the common, simple case of sending a single message using the
default transport. Internally, the send() method will
first call the saveChanges() method on the message.
It will then create an appropriate new Transport object, call the Transport's
connect() method, call the Transport's sendMessage()
method to actually send the message, call the Transport's close()
method, and finally abandon the new instance of the Transport object to be
collected by the garbage collector.
(Actually, it's rather more complicated than that, but that's the general
idea.)

As you can see, the static send() convenience method is
built on the more general per-instance sendMessage()
method. There are a number of reasons for an application to use the
sendMessage() method directly. The most common reasons are
to improve performance by sending more than one message during a single
connection, or to manually manage the connection so as to provide
authentication information.

Q: I modified this message, but the headers do not reflect the changes.
A: You should call saveChanges() after you create a
new message or modify an existing message. This will cause the headers to be
reset and reflect your changes.
Note that the Transport.send(Message) method calls this implicitly.
So if all you are doing is sending the modified message, you can
skip calling saveChanges() yourself.
saveChanges() is a potentially expensive operation (especially for
large or deeply nested messages), so call it only when needed.

Q: How can I explicitly set the SMTP FROM: attribute when sending a
message?A: The mail.smtp.from property can be used to set the
SMTP FROM: attribute. If this property if absent, the message's From
attribute is used.
If multiple threads need to send mail simultaneously, and each needs
to set the From attribute, each thread should use its own Session object
with its own Properties object. The mail.smtp.from property
can then be set on each Properties object for each Session (and thus
each thread) independently.
Alternatively, each thread can use the com.sun.mail.SMTPMessage
class. The setEnvelopeFrom method on that class can be used
to set this value. With this approach, all threads can use the same Session.

Q: I get "MessagingException: 501 HELO requires domain address"
when trying to send a message.A: The SMTP provider uses the results of
InetAddress.getLocalHost().getHostName()
in the SMTP HELO command. If that call fails to return any data, no
name is sent in the HELO command. Check your JDK and name server
configuration to ensure that that call returns the correct data.
You may also set the "mail.smtp.localhost"
property to the name you want to use for the HELO command.

Q: I get "Must issue a STARTTLS command first"
when trying to send a message.A: Your SMTP server wants you to switch from a plain text connection
to a secure connection using the STARTTLS command.
You can enable use of this command by setting the Session property
"mail.smtp.starttls.enable" to "true".
This will cause the SMTP protocol provider to issue the STARTTLS
command after connecting to the server.
See the file
SSLNOTES.txt
for additional information.
Also, the javadocs for the
com.sun.mail.smtp
package has more information on the properties that can be set.

Note that your server is most likely also going to want you to authenticate,
as described in this entry.

In Internet email, the existence of a particular mailbox or user
name can only be determined by the ultimate server that would deliver the
message. The message may pass through several relay servers (that are not
able to detect the error) before reaching the end server. Typically, when
the end server detects such an error, it will return a message indicating
the reason for the failure to the sender of the original message. There
are many Internet standards covering such Delivery Status Notifications
but a large number of servers don't support these new standards, instead
using ad hoc techniques for returning such failure messages. This makes
it very difficult to correlate a "bounced" message with the original message
that caused the problem. (Note that this problem is completely independent
of JavaMail.)
JavaMail now includes support for parsing Delivery Status Notifications;
see the NOTES.txt
file in the JavaMail package for details.

There are a number of techniques and heuristics for dealing with this
problem - none of them perfect. One technique is Variable Envelope
Return Paths, described at
http://cr.yp.to/proto/verp.txt.
The use of VERP with JavaMail and Apache James is described
here.

Q: When I try to send a message, why do I get
javax.mail.SendFailedException: 550 Unable to relay for
my-address?A: This is not a JavaMail problem. This is an error reply from
your SMTP mail server. It indicates that your mail server is not
configured to allow you to send mail through it. Typically, mail servers
for an organization will be configured to allow mail from within the
organization to be sent to other addresses within the organization,
or to addresses external to the organization. It will also typically allow
mail coming from an address external to an organization to be sent to
addresses within the orgnaization. What it will typically not
allow is mail coming from an address external to the organization to be
sent (relayed) to another address also external to the organization.
The configuration of the mail server determines whether such relaying is
allowed, and which addresses are considered internal vs. external.
Often mail servers will require you to
authenticate before they will
relay messages.

If you're not trying to connect to a web mail account, but instead are
trying to connect to a host on your local network, then most likely the
host you're trying to connect to is not running a mail server. Sometimes
this will occur if you forget to set (for example) the "mail.smtp.host"
property, which will cause you to try to connect to "localhost". Most
Windows machines do not run a mail server, although many UNIX (Solaris,
Linux, etc.) machines do. Thus, attempts to connect to "localhost" on
Windows machines will usually fail with a "connection refused" error.

Q: How can I tell which messages are new with POP3?A: The POP3 protocol doesn't provide support for any permanent flags
so the RECENT flag is of no use. The com.sun.mail.pop3 package
documentation discusses several strategies for dealing with this problem.

As above, you've mixed versions of the POP3
provider and jakarta.mail.jar. You probably have an older version of
jakarta.mail.jar in your CLASSPATH before the newer version that includes
the POP3 provider.

Q: Why does the getSize method return a negative number
when using POP3?
A: Your POP3 server is broken. The POP3 provider uses the
TOP command to fetch the headers for the message
and the LIST command to determine the size of the
entire message. It then subtracts the two values to determine
the size of the message body. If the server reports the size of
the entire message incorrectly, you may get a negative number.
You can set the property "mail.pop3.disabletop" to "true" to
disable the use of the TOP command, but note that
this will cause any access to the message headers to fetch the
entire message.

Q: I'm having problems using POP3 with Microsoft Exchange.
A: Some versions of Microsoft Exchange do not implement the
POP3 protocol properly. They return different headers from the
TOP command than they do from the RETR
command. This can cause all sorts of strange failures in JavaMail.
One solution is to disable use of the TOP command,
as described above. Another approach
that works in some cases os to tell JavaMail to forget about the
headers it retrieved using the TOP command after
retrieving the entire message using the RETR command.
To do this, set the property "mail.pop3.forgettopheaders" to "true".

JavaMail in applets

Q: What are the security implications of using JavaMail in an applet?
A: One of the biggest
issues with using JavaMail in applets is the default applet security
restrictions. These restrictions only allow applets to connect to the
host from which they were loaded. Thus, for such applets to use JavaMail,
the mail server will need to be located on the same machine as the web
server from which the applet is loaded. You can find more information
on the applet security model
here.