Beruflich Dokumente
Kultur Dokumente
Introduction
A J2EE application is able to send and receive email messages through the use of the JavaMail API. The JavaMail API is protocol independent and can send messages created by a J2EE application via email using existing email protocols. Likewise, it can receive email messages and make those messages available to a J2EE application for future processing. A developer can create a Mail User Agent (MUA) as part of a J2EE application. A MUA is a program that enables a person or component to compose, send, and receive email messages. A Mail Transfer Agent (MTA) uses one of several email protocols to transport email messages.
Protocols
Email protocols are provides a standard way of format an email message. There are four protocols used for emails. These are Multipurpose Internet Mail Extensions (MIME), Simple Mail Transfer Protocol (SMTP), Post Office Protocol (POP3), and Internet Message Access Protocol (IMAP). MIME MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. Similary Secure MIME protocol is used to encode multipart email messages for secure transmission. The MUA determines which of these protocols to use. SMTP The Simple Mail Transfer Protocol (SMTP) is the mechanism for delivery of email. The MUA sends an email message to an SMTP server that is provided by an Internet Service Provider (ISP) or by the business that is using the J2EE application. The SMTP server is responsible for forwarding the message to the recipients SMTP server.
Page 1 of 10
POP POP stands for Post Office Protocol version 3 (POP3), it is store-and-forward service where email messages are stored on the email server until the client logs in to receive them. It defines support for a single mailbox for each user. IMAP IMAP is a more advanced protocol for receiving messages. IMAP stands for Internet Message Access Protocol, and is currently in version 4, also known as IMAP4. Assuming your mail server supports IMAP, your JavaMail-based program can take advantage of users having multiple folders on the server and these folders can be shared by multiple users. Using this protocol, receive the new messages, deliver them to users when requested, and maintain them in multiple folders for each user. NNTP and Others Because of the split of the JavaMail API between provider and everything else, we can easily add support for additional protocols. Sun maintains a list of third-party providers that take advantage of protocols that Sun doesn't provide support for, out-of-the-box. There, you'll find support for NNTP (Network News Transport Protocol) [newsgroups], S/MIME (Secure Multipurpose Internet Mail Extensions), and more.
Exceptions
A fully implemented JavaMail Program must be prepared to handle each of the 11 commonly encountered exceptions that might be thrown by the program. Three of these exceptions are related to the folder that is used to store the email message. These are the ReadOnlyFolderException, FolderClosedException, and FolderNotFoundException. Next three are general exceptions. These are MessagingException, AuthenticationFailedException, and MethodNotSupportedException. Next three of exceptions might be thrown while the program is sending an email message. These are SendFailedException, IllegalWriteException, and NoSuchProviderException. The final two exceptions the MessageRemovedException, and the StoreClosedException.
Page 2 of 10
Session Object
The Session class defines a basic mail session. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application. The constructors for this class are private. The single default session that can be shared with the getDefaultInstance() method as shown below.
Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null);
In both cases here the null argument is an Authenticator object which is not being used at this time. Methods of Session Object
public static Session getInstance(Properties props,Authenticator authenticator) public static Session getInstance(Properties props) public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props, Authenticator authenticator) public void setProvider(Provider provider)throws NoSuchProviderException public Provider getProvider(String protocol)throws NoSuchProviderException public Provider[] getProviders() public Transport getTransport()throws NoSuchProviderException public Transport getTransport(String protocol)throws NoSuchProviderException public Transport getTransport(Provider provider)throws NoSuchProviderException public Transport getTransport(Address address)throws NoSuchProviderException public void setPasswordAuthentication(URLName url,PasswordAuthentication pw) public PasswordAuthentication getPasswordAuthentication(URLName url)
Page 3 of 10
Message Object
Once Session object is created, we need Message Object to send message. But it is an abstract class. So the subclass javax.mail.internet.MimeMessage is used for send messages. A MimeMessage is an email message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields. To create a Message, pass along the Session object to the MimeMessage constructor:
MimeMessage message = new MimeMessage(session);
Page 4 of 10
public String getMessageID() public InputStream getInputStream()throws IOException public void setContent(Object o,String type) public Object getContent()throws IOException public void setText(String text) public Message reply(boolean replyToAll) public void addHeaderLine(String line) public Enumeration getAllHeaderLines() public void saveChanges() Note: The above all methods throws MessagingExcepton.
Address Object
Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address. Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class. To create an address with just the email address, pass the email address to the constructor: Address address = new InternetAddress("president@whitehouse.gov"); If you want a name to appear next to the email address, you can pass that along to the constructor, too: Address address = new InternetAddress("president@whitehouse.gov", "George Bush"); You will need to create address objects for the message's from field as well as the to field. Unless your mail server prevents you, there is nothing stopping you from sending a message that appears to be from anyone. Once you've created the addresses, you connect them to a message in one of two ways. For identifying the sender, you use the setFrom() and setReplyTo() methods. message.setFrom(address) If your message needs to show multiple from addresses, use the addFrom() method: Address address[] = ...; message.addFrom(address); For identifying the message recipients, you use the addRecipient() method. This method requires a Message.RecipientType besides the address.
Page 5 of 10
message.addRecipient(type, address) The three predefined types of address are: Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC So, if the message was to go to the vice president, sending a carbon copy to the first lady, the following would be appropriate: Address toAddress = new InternetAddress("vice.president@whitehouse.gov"); Address ccAddress = new InternetAddress("first.lady@whitehouse.gov"); message.addRecipient(Message.RecipientType.TO, toAddress); message.addRecipient(Message.RecipientType.CC, ccAddress); The JavaMail API provides no mechanism to check for the validity of an email address. Constructors of InternetAddress Object
public InternetAddress() public InternetAddress(String address)throws AddressException public InternetAddress(String address,String personal) throws UnsupportedEncodingException
Authenticator Object
Like the java.net classes, the JavaMail API can take advantage of an Authenticator to access protected resources via a username and password. For the JavaMail API, that resource is the mail server. The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the
Page 6 of 10
same name. The two don't share the same Authenticator as the JavaMail API works with Java 1.1, which didn't have the java.net variety. To use the Authenticator, you subclass the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. You must register the Authenticator with the session when created. Then, your Authenticator will be notified when authentication is necessary. You could popup a window or read the username and password from a configuration file (though if not encrypted it is not secure), returning them to the caller as a PasswordAuthentication object.
Properties props = new Properties(); // fill props with any information Authenticator auth = new MyAuthenticator(); Session session = Session.getDefaultInstance(props, auth);
Transport Object
The final part of sending a message is to use the Transport class. This class speaks the protocol-specific language for sending the message (usually SMTP). It's an abstract class and works something like Session. You can use the default version of the class by just calling the static send() method: Transport.send(message); Or, you can get a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection:
message.saveChanges(); // implicit with send() Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close();
Page 7 of 10
// Store store = session.getStore("imap"); Store store = session.getStore("pop3"); store.connect(host, username, password); After connecting to the Store, you can then get a Folder, which must be opened before you can read messages from it: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); For POP3, the only folder available is the INBOX. If you are using IMAP, you can have other folders available. Store Object Methods
public abstract Folder getDefaultFolder()throws MessagingException public abstract Folder getFolder(String name)throws MessagingException public Folder[] getPersonalNamespaces()throws MessagingException public Folder[] getSharedNamespaces()throws MessagingException
Page 8 of 10
public Message[] search(SearchTerm term,Message[] msgs)throws MessagingException public abstract void open(int mode)throws MessagingException public abstract void close(boolean expunge)throws MessagingException public abstract boolean isOpen() public int getMode()
Page 9 of 10
Page 10 of 10