![]() | |
Sun Java System Application Server Standard and Enterprise Edition 7 2004Q2 Developer's Guide to J2EE Services and APIs |
Chapter 6
Using the JavaMail APIThis chapter describes how to use the JavaMail API, which provides a set of abstract classes defining objects that comprise a mail system.
This chapter contains the following sections:
Introducing JavaMailThe JavaMail API defines classes such as Message, Store, and Transport. The API can be extended and can be subclassed to provide new protocols and to add functionality when necessary. In addition, the API provides concrete subclasses of the abstract classes. These subclasses, including MimeMessage and MimeBodyPart, implement widely used Internet mail protocols and conform to the RFC822 and RFC2045 specifications. The JavaMail API includes support for the IMAP4, POP3, and SMTP protocols.
The JavaMail architectural components are as follows:
- The abstract layer declares classes, interfaces, and abstract methods intended to support mail handling functions that all mail systems support.
- The internet implementation layer implements part of the abstract layer using the RFC822 and MIME internet standards.
- JavaMail uses the JavaBeans Activation Framework (JAF) to encapsulate message data and to handle commands intended to interact with that data.
For more information, see the Sun Java System Application Server Administrator’s Guide and the JavaMail specification at:
http://java.sun.com/products/javamail/
Creating a JavaMail SessionYou can create a JavaMail session in the following ways:
The “Using The Administration Interface” section describes each connection pool setting. The “Using The Command Line Interface” section merely lists syntax and default values.
Using the Administration Interface
To create a JavaMail session using the Administration interface, perform the following tasks:
- Open the Java Mail Sessions component under your server instance.
- Click the New button.
- Enter the following information:
- JNDI Name (required) - Enter the JNDI name that application components must use to access the JavaMail session. For more information, see Looking Up a JavaMail Session.
- Mail Host (required) - The mail server host name.
- Default User (required) - The mail server user name.
- Default Return Address (required) - The e-mail address the mail server uses to indicate the message sender.
- Description (optional) - You can enter a text description of the JavaMail session.
- Check the Java Mail Session Enabled box to enable the JavaMail session.
If a JavaMail session is disabled, no application component can connect to it, but its configuration remains in the server instance.
- You can also edit the following Advanced settings:
- Store Protocol - Specifies the storage protocol service, which connects to a mail server, retrieves messages, and saves messages in folder(s). Example values are imap (the default) and pop3.
- Store Protocol Class - Specifies the service provider implementation class for storage. The default is com.sun.mail.imap.IMAPStore.
- Transport Protocol - Specifies the transport protocol service, which sends messages. The default is smtp.
- Transport Protocol Class - Specifies the service provider implementation class for transport. The default is com.sun.mail.smtp.SMTPTransport.
- Debug Enabled - Enables debugging for this JavaMail session.
- Click the OK button.
- To add properties to a JavaMail session, perform the following tasks:
- Go back to the Java Mail Sessions page.
- Click the JavaMail session you just created.
- Click the Properties button.
- Specify names and values for any properties you want to use. If you need another name-value row, use the Add button to add it. For details about JavaMail session properties, see JavaMail Session Properties.
- Click the Save button.
- Go to the server instance page.
- Click the General tab.
- Click the Apply Changes button.
Using the Command Line Interface
To create a JavaMail session using the command line, use the asadmin create-javamail-resource command. The syntax is as follows, with defaults shown for optional parameters that have them:
asadmin create-javamail-resource --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] --mailhost mail_host --mailuser mail_user --fromaddress address [--storeprotocol=imap] [--storeprotocolclass=com.sun.mail.imap.IMAPStore] [--transprotocol=smtp] [--transprotocolclass=com.sun.mail.smtp.SMTPTransport] [--debug=false] [--enabled=true] [--description text] [--property (name=value)[:name=value]*] jndi_name
For more information about the parameters specific to asadmin create-javamail-resource, see Using the Administration Interface. For more information about the general asadmin parameters (--user, --password, --passwordfile, --host, --port, and --secure), see the Sun Java System Application Server Administrator’s Guide.
For example:
asadmin create-javamail-resource --user joeuser --password secret --mailhost MailServer --mailuser MailUser --fromaddress user@mailserver.com MailSession
To delete a JavaMail session, use the following command:
asadmin delete-javamail-resource --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name] jndi_name
For example:
asadmin delete-javamail-resource --user joeuser --password secret MailSession
To list JavaMail sessions, use the following command:
asadmin list-javamail-resources --user admin_user [--password admin_password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s] [--instance instance_name]
For example:
asadmin list-javamail-resources --user joeuser --password secret --instance server1
After you create the JavaMail session, you must reconfigure the server instance using the following command:
asadmin reconfig --user user [--password password] [--passwordfile password_file] [--host localhost] [--port 4848] [--secure | -s][--discardmanualchanges=false | --keepmanualchanges=false] instance_name
For example:
asadmin reconfig --user joeuser --password secret server1
JavaMail Session PropertiesYou can set properties for a JavaMail Session object. Every property name must start with a mail- prefix. Sun Java System Application Server changes the dash (-) character to a period (.) in the name of the property and saves the property to the MailConfiguration and JavaMail Session objects. If the name of the property doesn’t start with mail-, the property is ignored.
For example, if you want to define the property mail.password in a JavaMail Session object, first define the property as follows:
After you get the JavaMail Session object, you can get the mail.password property to retrieve the value secret, as follows:
String password = session.getProperty("mail.password");
Looking Up a JavaMail SessionThe standard Java Naming and Directory Interface (JNDI) subcontext for JavaMail sessions is java:comp/env/mail.
Registering JavaMail sessions in the mail naming subcontext of a JNDI namespace, or in one of its child subcontexts, is standard. The JNDI namespace is hierarchical, like a file system’s directory structure, so it is easy to find and nest references. A JavaMail session is bound to a logical JNDI name. The name identifies a subcontext, mail, of the root context, and a logical name. To change the JavaMail session, you can change its entry in the JNDI namespace without having to modify the application.
The resource lookup in the application code looks like this:
InitialContext ic = new InitialContext();
String snName = "java:comp/env/mail/MyMailSession";
Session session = (Session)ic.lookup(snName);For more information about the JNDI API, see Chapter 4, “Using the Java Naming and Directory Interface.”
Sending Messages Using JavaMailTo send a message using JavaMail, perform the following tasks:
- Import the packages that you need:
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;- Look up the JavaMail session, as described in Looking Up a JavaMail Session:
InitialContext ic = new InitialContext();
String snName = "java:comp/env/mail/MyMailSession";
Session session = (Session)ic.lookup(snName);- Override the JavaMail session properties if necessary. For example:
Properties props = session.getProperties();
props.put("mail.from", "user2@mailserver.com");- Create a MimeMessage. The msgRecipient, msgSubject, and msgTxt variables in the following example contain input from the user:
Message msg = new MimeMessage(session);
msg.setSubject(msgSubject);
msg.setSentDate(new Date());
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(msgRecipient, false));
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText(msgTxt);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);- Send the message:
Transport.send(msg);
Reading Messages Using JavaMailTo read a message using JavaMail, perform the following tasks:
- Import the packages that you need:
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;- Look up the JavaMail session, as described in Looking Up a JavaMail Session:
InitialContext ic = new InitialContext();
String snName = "java:comp/env/mail/MyMailSession";
Session session = (javax.mail.Session)ic.lookup(snName);- Override the JavaMail session properties if necessary. For example:
Properties props = session.getProperties();
props.put("mail.from", "user2@mailserver.com");- Get a Store object from the Session, then connect to the mail server using the Store object’s connect() method. You must supply a mail server name, a mail user name, and a password.
Store store = session.getStore();
store.connect("MailServer", "MailUser", "secret");- Get the default folder, then get the INBOX folder:
Folder folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");- It is efficient to read the Message objects (which represent messages on the server) into an array:
Message[] messages = folder.getMessages();
Sample ApplicationsJavaMail sample applications are in the following directory:
install_dir/samples/javamail