Class Session
- java.lang.Object
-
- javax.mail.Session
-
public final class Session extends java.lang.ObjectThe Session class represents a mail session and is not subclassed. It collects together properties and defaults used by the mail API's. A single default session can be shared by multiple applications on the desktop. Unshared sessions can also be created.The Session class provides access to the protocol providers that implement the
Store,Transport, and related classes. The protocol providers are configured using the following files:-
javamail.providersandjavamail.default.providers -
javamail.address.mapandjavamail.default.address.map
Each
javamail.X resource file is searched for using three methods in the following order:-
java.home/conf/javamail.X -
META-INF/javamail.X -
META-INF/javamail.default.X
(Where java.home is the value of the "java.home" System property and conf is the directory named "conf" if it exists, otherwise the directory named "lib"; the "conf" directory was introduced in JDK 1.9.)
The first method allows the user to include their own version of the resource file by placing it in the conf directory where the
java.homeproperty points. The second method allows an application that uses the JavaMail APIs to include their own resource files in their application's or jar file'sMETA-INFdirectory. Thejavamail.default.X default files are part of the JavaMailmail.jarfile and should not be supplied by users.File location depends upon how the
ClassLoadermethodgetResourceis implemented. Usually, thegetResourcemethod searches through CLASSPATH until it finds the requested file and then stops.The ordering of entries in the resource files matters. If multiple entries exist, the first entries take precedence over the later entries. For example, the first IMAP provider found will be set as the default IMAP implementation until explicitly changed by the application. The user- or system-supplied resource files augment, they do not override, the default files included with the JavaMail APIs. This means that all entries in all files loaded will be available.
javamail.providersandjavamail.default.providersThese resource files specify the stores and transports that are available on the system, allowing an application to "discover" what store and transport implementations are available. The protocol implementations are listed one per line. The file format defines four attributes that describe a protocol implementation. Each attribute is an "="-separated name-value pair with the name in lowercase. Each name-value pair is semi-colon (";") separated. The following names are defined.
Attribute Names in Providers Files Name Description protocol Name assigned to protocol. For example, smtpfor Transport.type Valid entries are storeandtransport.class Class name that implements this protocol. vendor Optional string identifying the vendor. version Optional string identifying the version. Here's an example of
META-INF/javamail.default.providersfile contents:protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Oracle; protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle;
The current implementation also supports configuring providers using the Java SE
ServiceLoadermechanism. When creating your own provider, create aProvidersubclass, for example:package com.example; import javax.mail.Provider; public class MyProvider extends Provider { public MyProvider() { super(Provider.Type.STORE, "myprot", MyStore.class.getName(), "Example", null); } }Then include a file namedMETA-INF/services/javax.mail.Providerin your jar file that lists the name of your Provider class:com.example.MyProvider
javamail.address.mapandjavamail.default.address.mapThese resource files map transport address types to the transport protocol. The
getTypemethod ofjavax.mail.Addressreturns the address type. Thejavamail.address.mapfile maps the transport type to the protocol. The file format is a series of name-value pairs. Each key name should correspond to an address type that is currently installed on the system; there should also be an entry for eachjavax.mail.Addressimplementation that is present if it is to be used. For example, thejavax.mail.internet.InternetAddressmethodgetTypereturns "rfc822". Each referenced protocol should be installed on the system. For the case ofnews, below, the client should install a Transport provider supporting the nntp protocol.Here are the typical contents of a
javamail.address.mapfile:rfc822=smtp news=nntp
-
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.PropertiesaddressMapprivate Authenticatorauthenticatorprivate java.util.Hashtable<URLName,PasswordAuthentication>authTableprivate static java.lang.StringconfDirprivate booleandebugprivate static SessiondefaultSessionprivate booleanloadedProvidersprivate MailLoggerloggerprivate java.io.PrintStreamoutprivate java.util.Propertiespropsprivate java.util.List<Provider>providersprivate java.util.Map<java.lang.String,Provider>providersByClassNameprivate java.util.Map<java.lang.String,Provider>providersByProtocolprivate EventQueueq
-
Constructor Summary
Constructors Modifier Constructor Description privateSession(java.util.Properties props, Authenticator authenticator)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description voidaddProvider(Provider provider)Add a provider to the session.(package private) static java.lang.ClassLoadergetContextClassLoader()booleangetDebug()Get the debug setting for this Session.java.io.PrintStreamgetDebugOut()Returns the stream to be used for debugging output.static SessiongetDefaultInstance(java.util.Properties props)Get the default Session object.static SessiongetDefaultInstance(java.util.Properties props, Authenticator authenticator)Get the default Session object.(package private) EventQueuegetEventQueue()FoldergetFolder(URLName url)Get a closed Folder object for the given URLName.static SessiongetInstance(java.util.Properties props)Get a new Session object.static SessiongetInstance(java.util.Properties props, Authenticator authenticator)Get a new Session object.PasswordAuthenticationgetPasswordAuthentication(URLName url)Return any saved PasswordAuthentication for this (store or transport) URLName.java.util.PropertiesgetProperties()Returns the Properties object associated with this Sessionjava.lang.StringgetProperty(java.lang.String name)Returns the value of the specified property.ProvidergetProvider(java.lang.String protocol)Returns the default Provider for the protocol specified.private ProvidergetProviderByClassName(java.lang.String className)Get the Provider that uses the specified class name.private ProvidergetProviderByProtocol(java.lang.String protocol)Get the Provider for the specified protocol.Provider[]getProviders()This method returns an array of all the implementations installed via the javamail.[default.]providers files that can be loaded using the ClassLoader available to this application.private static java.io.InputStreamgetResourceAsStream(java.lang.Class<?> c, java.lang.String name)private static java.net.URL[]getResources(java.lang.ClassLoader cl, java.lang.String name)private <T extends Service>
TgetService(Provider provider, URLName url, java.lang.Class<T> type)Get a Service object.StoregetStore()Get a Store object that implements this user's desired Store protocol.StoregetStore(java.lang.String protocol)Get a Store object that implements the specified protocol.StoregetStore(Provider provider)Get an instance of the store specified by Provider.private StoregetStore(Provider provider, URLName url)Get an instance of the store specified by Provider.StoregetStore(URLName url)Get a Store object for the given URLName.private static java.net.URL[]getSystemResources(java.lang.String name)TransportgetTransport()Get a Transport object that implements this user's desired Transport protcol.TransportgetTransport(java.lang.String protocol)Get a Transport object that implements the specified protocol.TransportgetTransport(Address address)Get a Transport object that can transport a Message of the specified address type.TransportgetTransport(Provider provider)Get an instance of the transport specified in the Provider.private TransportgetTransport(Provider provider, URLName url)Get a Transport object using the given provider and urlname.TransportgetTransport(URLName url)Get a Transport object for the given URLName.private voidinitLogger()private voidloadAddressMap(java.lang.Class<?> cl)private voidloadAllResources(java.lang.String name, java.lang.Class<?> cl, StreamLoader loader)Load all of the named resource.private voidloadFile(java.lang.String name, StreamLoader loader)Load from the named file.private voidloadProviders(boolean fallback)Load the protocol providers config files.private voidloadProvidersFromStream(java.io.InputStream is)private voidloadResource(java.lang.String name, java.lang.Class<?> cl, StreamLoader loader, boolean expected)Load from the named resource.private static java.io.InputStreamopenStream(java.net.URL url)PasswordAuthenticationrequestPasswordAuthentication(java.net.InetAddress addr, int port, java.lang.String protocol, java.lang.String prompt, java.lang.String defaultUserName)Call back to the application to get the needed user name and password.voidsetDebug(boolean debug)Set the debug setting for this Session.voidsetDebugOut(java.io.PrintStream out)Set the stream to be used for debugging output for this session.voidsetPasswordAuthentication(URLName url, PasswordAuthentication pw)Save a PasswordAuthentication for this (store or transport) URLName.voidsetProtocolForAddress(java.lang.String addresstype, java.lang.String protocol)Set the default transport protocol to use for addresses of the specified type.voidsetProvider(Provider provider)Set the passed Provider to be the default implementation for the protocol in Provider.protocol overriding any previous values.
-
-
-
Field Detail
-
props
private final java.util.Properties props
-
authenticator
private final Authenticator authenticator
-
authTable
private final java.util.Hashtable<URLName,PasswordAuthentication> authTable
-
debug
private boolean debug
-
out
private java.io.PrintStream out
-
logger
private MailLogger logger
-
providers
private java.util.List<Provider> providers
-
providersByProtocol
private final java.util.Map<java.lang.String,Provider> providersByProtocol
-
providersByClassName
private final java.util.Map<java.lang.String,Provider> providersByClassName
-
addressMap
private final java.util.Properties addressMap
-
loadedProviders
private boolean loadedProviders
-
q
private final EventQueue q
-
defaultSession
private static Session defaultSession
-
confDir
private static final java.lang.String confDir
-
-
Constructor Detail
-
Session
private Session(java.util.Properties props, Authenticator authenticator)
-
-
Method Detail
-
initLogger
private final void initLogger()
-
getInstance
public static Session getInstance(java.util.Properties props, Authenticator authenticator)
Get a new Session object.- Parameters:
props- Properties object that hold relevant properties.
It is expected that the client supplies values for the properties listed in Appendix A of the JavaMail spec (particularly mail.store.protocol, mail.transport.protocol, mail.host, mail.user, and mail.from) as the defaults are unlikely to work in all cases.authenticator- Authenticator object used to call back to the application when a user name and password is needed.- Returns:
- a new Session object
- See Also:
Authenticator
-
getInstance
public static Session getInstance(java.util.Properties props)
Get a new Session object.- Parameters:
props- Properties object that hold relevant properties.
It is expected that the client supplies values for the properties listed in Appendix A of the JavaMail spec (particularly mail.store.protocol, mail.transport.protocol, mail.host, mail.user, and mail.from) as the defaults are unlikely to work in all cases.- Returns:
- a new Session object
- Since:
- JavaMail 1.2
-
getDefaultInstance
public static Session getDefaultInstance(java.util.Properties props, Authenticator authenticator)
Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default.Since the default session is potentially available to all code executing in the same Java virtual machine, and the session can contain security sensitive information such as user names and passwords, access to the default session is restricted. The Authenticator object, which must be created by the caller, is used indirectly to check access permission. The Authenticator object passed in when the session is created is compared with the Authenticator object passed in to subsequent requests to get the default session. If both objects are the same, or are from the same ClassLoader, the request is allowed. Otherwise, it is denied.
Note that if the Authenticator object used to create the session is null, anyone can get the default session by passing in null.
Note also that the Properties object is used only the first time this method is called, when a new Session object is created. Subsequent calls return the Session object that was created by the first call, and ignore the passed Properties object. Use the
getInstancemethod to get a new Session object every time the method is called.Additional security Permission objects may be used to control access to the default session.
In the current implementation, if a SecurityManager is set, the caller must have the
RuntimePermission("setFactory")permission.- Parameters:
props- Properties object. Used only if a new Session object is created.
It is expected that the client supplies values for the properties listed in Appendix A of the JavaMail spec (particularly mail.store.protocol, mail.transport.protocol, mail.host, mail.user, and mail.from) as the defaults are unlikely to work in all cases.authenticator- Authenticator object. Used only if a new Session object is created. Otherwise, it must match the Authenticator used to create the Session.- Returns:
- the default Session object
-
getDefaultInstance
public static Session getDefaultInstance(java.util.Properties props)
Get the default Session object. If a default has not yet been setup, a new Session object is created and installed as the default.Note that a default session created with no Authenticator is available to all code executing in the same Java virtual machine, and the session can contain security sensitive information such as user names and passwords.
- Parameters:
props- Properties object. Used only if a new Session object is created.
It is expected that the client supplies values for the properties listed in Appendix A of the JavaMail spec (particularly mail.store.protocol, mail.transport.protocol, mail.host, mail.user, and mail.from) as the defaults are unlikely to work in all cases.- Returns:
- the default Session object
- Since:
- JavaMail 1.2
-
setDebug
public void setDebug(boolean debug)
Set the debug setting for this Session.Since the debug setting can be turned on only after the Session has been created, to turn on debugging in the Session constructor, set the property
mail.debugin the Properties object passed in to the constructor to true. The value of themail.debugproperty is used to initialize the per-Session debugging flag. Subsequent calls to thesetDebugmethod manipulate the per-Session debugging flag and have no affect on themail.debugproperty.- Parameters:
debug- Debug setting
-
getDebug
public boolean getDebug()
Get the debug setting for this Session.- Returns:
- current debug setting
-
setDebugOut
public void setDebugOut(java.io.PrintStream out)
Set the stream to be used for debugging output for this session. Ifoutis null,System.outwill be used. Note that debugging output that occurs before any session is created, as a result of setting themail.debugsystem property, will always be sent toSystem.out.- Parameters:
out- the PrintStream to use for debugging output- Since:
- JavaMail 1.3
-
getDebugOut
public java.io.PrintStream getDebugOut()
Returns the stream to be used for debugging output. If no stream has been set,System.outis returned.- Returns:
- the PrintStream to use for debugging output
- Since:
- JavaMail 1.3
-
getProviders
public Provider[] getProviders()
This method returns an array of all the implementations installed via the javamail.[default.]providers files that can be loaded using the ClassLoader available to this application.- Returns:
- Array of configured providers
-
getProvider
public Provider getProvider(java.lang.String protocol) throws NoSuchProviderException
Returns the default Provider for the protocol specified. Checks mail.<protocol>.class property first and if it exists, returns the Provider associated with this implementation. If it doesn't exist, returns the Provider that appeared first in the configuration files. If an implementation for the protocol isn't found, throws NoSuchProviderException- Parameters:
protocol- Configured protocol (i.e. smtp, imap, etc)- Returns:
- Currently configured Provider for the specified protocol
- Throws:
NoSuchProviderException- If a provider for the given protocol is not found.
-
setProvider
public void setProvider(Provider provider) throws NoSuchProviderException
Set the passed Provider to be the default implementation for the protocol in Provider.protocol overriding any previous values.- Parameters:
provider- Currently configured Provider which will be set as the default for the protocol- Throws:
NoSuchProviderException- If the provider passed in is invalid.
-
getStore
public Store getStore() throws NoSuchProviderException
Get a Store object that implements this user's desired Store protocol. Themail.store.protocolproperty specifies the desired protocol. If an appropriate Store object is not obtained, NoSuchProviderException is thrown- Returns:
- a Store object
- Throws:
NoSuchProviderException- If a provider for the given protocol is not found.
-
getStore
public Store getStore(java.lang.String protocol) throws NoSuchProviderException
Get a Store object that implements the specified protocol. If an appropriate Store object cannot be obtained, NoSuchProviderException is thrown.- Parameters:
protocol- the Store protocol- Returns:
- a Store object
- Throws:
NoSuchProviderException- If a provider for the given protocol is not found.
-
getStore
public Store getStore(URLName url) throws NoSuchProviderException
Get a Store object for the given URLName. If the requested Store object cannot be obtained, NoSuchProviderException is thrown. The "scheme" part of the URL string (Refer RFC 1738) is used to locate the Store protocol.- Parameters:
url- URLName that represents the desired Store- Returns:
- a closed Store object
- Throws:
NoSuchProviderException- If a provider for the given URLName is not found.- See Also:
getFolder(URLName),URLName
-
getStore
public Store getStore(Provider provider) throws NoSuchProviderException
Get an instance of the store specified by Provider. Instantiates the store and returns it.- Parameters:
provider- Store Provider that will be instantiated- Returns:
- Instantiated Store
- Throws:
NoSuchProviderException- If a provider for the given Provider is not found.
-
getStore
private Store getStore(Provider provider, URLName url) throws NoSuchProviderException
Get an instance of the store specified by Provider. If the URLName is not null, uses it, otherwise creates a new one. Instantiates the store and returns it. This is a private method used by getStore(Provider) and getStore(URLName)- Parameters:
provider- Store Provider that will be instantiatedurl- URLName used to instantiate the Store- Returns:
- Instantiated Store
- Throws:
NoSuchProviderException- If a provider for the given Provider/URLName is not found.
-
getFolder
public Folder getFolder(URLName url) throws MessagingException
Get a closed Folder object for the given URLName. If the requested Folder object cannot be obtained, null is returned.The "scheme" part of the URL string (Refer RFC 1738) is used to locate the Store protocol. The rest of the URL string (that is, the "schemepart", as per RFC 1738) is used by that Store in a protocol dependent manner to locate and instantiate the appropriate Folder object.
Note that RFC 1738 also specifies the syntax for the "schemepart" for IP-based protocols (IMAP4, POP3, etc.). Providers of IP-based mail Stores should implement that syntax for referring to Folders.
- Parameters:
url- URLName that represents the desired folder- Returns:
- Folder
- Throws:
NoSuchProviderException- If a provider for the given URLName is not found.MessagingException- if the Folder could not be located or created.- See Also:
getStore(URLName),URLName
-
getTransport
public Transport getTransport() throws NoSuchProviderException
Get a Transport object that implements this user's desired Transport protcol. Themail.transport.protocolproperty specifies the desired protocol. If an appropriate Transport object cannot be obtained, MessagingException is thrown.- Returns:
- a Transport object
- Throws:
NoSuchProviderException- If the provider is not found.
-
getTransport
public Transport getTransport(java.lang.String protocol) throws NoSuchProviderException
Get a Transport object that implements the specified protocol. If an appropriate Transport object cannot be obtained, null is returned.- Parameters:
protocol- the Transport protocol- Returns:
- a Transport object
- Throws:
NoSuchProviderException- If provider for the given protocol is not found.
-
getTransport
public Transport getTransport(URLName url) throws NoSuchProviderException
Get a Transport object for the given URLName. If the requested Transport object cannot be obtained, NoSuchProviderException is thrown. The "scheme" part of the URL string (Refer RFC 1738) is used to locate the Transport protocol.- Parameters:
url- URLName that represents the desired Transport- Returns:
- a closed Transport object
- Throws:
NoSuchProviderException- If a provider for the given URLName is not found.- See Also:
URLName
-
getTransport
public Transport getTransport(Provider provider) throws NoSuchProviderException
Get an instance of the transport specified in the Provider. Instantiates the transport and returns it.- Parameters:
provider- Transport Provider that will be instantiated- Returns:
- Instantiated Transport
- Throws:
NoSuchProviderException- If provider for the given provider is not found.
-
getTransport
public Transport getTransport(Address address) throws NoSuchProviderException
Get a Transport object that can transport a Message of the specified address type.- Parameters:
address- an address for which a Transport is needed- Returns:
- A Transport object
- Throws:
NoSuchProviderException- If provider for the Address type is not found- See Also:
Address
-
getTransport
private Transport getTransport(Provider provider, URLName url) throws NoSuchProviderException
Get a Transport object using the given provider and urlname.- Parameters:
provider- the provider to useurl- urlname to use (can be null)- Returns:
- A Transport object
- Throws:
NoSuchProviderException- If no provider or the provider was the wrong class.
-
getService
private <T extends Service> T getService(Provider provider, URLName url, java.lang.Class<T> type) throws NoSuchProviderException
Get a Service object. Needs a provider object, but will create a URLName if needed. It attempts to instantiate the correct class.- Parameters:
provider- which provider to useurl- which URLName to use (can be null)type- the service type (class)- Throws:
NoSuchProviderException- thrown when the class cannot be found or when it does not have the correct constructor (Session, URLName), or if it is not derived from Service.
-
setPasswordAuthentication
public void setPasswordAuthentication(URLName url, PasswordAuthentication pw)
Save a PasswordAuthentication for this (store or transport) URLName. If pw is null the entry corresponding to the URLName is removed.This is normally used only by the store or transport implementations to allow authentication information to be shared among multiple uses of a session.
- Parameters:
url- the URLNamepw- the PasswordAuthentication to save
-
getPasswordAuthentication
public PasswordAuthentication getPasswordAuthentication(URLName url)
Return any saved PasswordAuthentication for this (store or transport) URLName. Normally used only by store or transport implementations.- Parameters:
url- the URLName- Returns:
- the PasswordAuthentication corresponding to the URLName
-
requestPasswordAuthentication
public PasswordAuthentication requestPasswordAuthentication(java.net.InetAddress addr, int port, java.lang.String protocol, java.lang.String prompt, java.lang.String defaultUserName)
Call back to the application to get the needed user name and password. The application should put up a dialog something like:Connecting to <protocol> mail service on host <addr>, port <port>. <prompt> User Name: <defaultUserName> Password:
- Parameters:
addr- InetAddress of the host. may be null.port- the port on the hostprotocol- protocol scheme (e.g. imap, pop3, etc.)prompt- any additional String to show as part of the prompt; may be null.defaultUserName- the default username. may be null.- Returns:
- the authentication which was collected by the authenticator; may be null.
-
getProperties
public java.util.Properties getProperties()
Returns the Properties object associated with this Session- Returns:
- Properties object
-
getProperty
public java.lang.String getProperty(java.lang.String name)
Returns the value of the specified property. Returns null if this property does not exist.- Parameters:
name- the property name- Returns:
- String that is the property value
-
getProviderByClassName
private Provider getProviderByClassName(java.lang.String className)
Get the Provider that uses the specified class name.- Parameters:
className- the class name- Returns:
- the Provider
-
getProviderByProtocol
private Provider getProviderByProtocol(java.lang.String protocol)
Get the Provider for the specified protocol.- Parameters:
protocol- the protocol- Returns:
- the Provider
-
loadProviders
private void loadProviders(boolean fallback)
Load the protocol providers config files. If fallback is true, provide built in defaults if nothing is loaded.
-
loadProvidersFromStream
private void loadProvidersFromStream(java.io.InputStream is) throws java.io.IOException- Throws:
java.io.IOException
-
addProvider
public void addProvider(Provider provider)
Add a provider to the session.- Parameters:
provider- the provider to add- Since:
- JavaMail 1.4
-
loadAddressMap
private void loadAddressMap(java.lang.Class<?> cl)
-
setProtocolForAddress
public void setProtocolForAddress(java.lang.String addresstype, java.lang.String protocol)Set the default transport protocol to use for addresses of the specified type. Normally the default is set by thejavamail.default.address.maporjavamail.address.mapfiles or resources.- Parameters:
addresstype- type of addressprotocol- name of protocol- Since:
- JavaMail 1.4
- See Also:
getTransport(Address)
-
loadFile
private void loadFile(java.lang.String name, StreamLoader loader)Load from the named file.
-
loadResource
private void loadResource(java.lang.String name, java.lang.Class<?> cl, StreamLoader loader, boolean expected)Load from the named resource.
-
loadAllResources
private void loadAllResources(java.lang.String name, java.lang.Class<?> cl, StreamLoader loader)Load all of the named resource.
-
getContextClassLoader
static java.lang.ClassLoader getContextClassLoader()
-
getResourceAsStream
private static java.io.InputStream getResourceAsStream(java.lang.Class<?> c, java.lang.String name) throws java.io.IOException- Throws:
java.io.IOException
-
getResources
private static java.net.URL[] getResources(java.lang.ClassLoader cl, java.lang.String name)
-
getSystemResources
private static java.net.URL[] getSystemResources(java.lang.String name)
-
openStream
private static java.io.InputStream openStream(java.net.URL url) throws java.io.IOException- Throws:
java.io.IOException
-
getEventQueue
EventQueue getEventQueue()
-
-