Sie sind auf Seite 1von 10

Java Mail

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.

JavaMail API and Java Activation Framework (JAF)


The latest JavaMail API requires Java Activation Framework (JAF), which is downloaded separately from java.sun.com. JAF contains services to determine the type of data that is associated with an email. This enables the program to call appropriate EJB to process the data. For example, an email attachment is a BMP image, then the JAF identifies and enabling the program to display the BMP image.

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

Reviewing the Core Classes


The core classes that make up the JavaMail API: Session, Message, Address, Authenticator, Transport, Store, and Folder. All these classes are found in the top-level package javax.mail, though we'll frequently find our self using subclasses found in the javax.mail.internet package.

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);

Or, you can create a unique session with getInstance():


Properties props = new Properties(); // fill props with any information Session session = Session.getInstance(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);

Constructors of MimeMessage Object


MimeMessage(Session session) MimeMessage(Session session, InputStream is)

Methods of MimeMessage Object


public void addFrom(Address[] addresses) public void setSender(Address address) public Address getSender() public void setRecipients(Message.RecipientType type,Address[] addresses) public Address[] getAllRecipients() public void setReplyTo(Address[] addresses) public Address[] getReplyTo() public void setSubject(String subject) public String getSubject() public void setSentDate(Date d) public Date getSentDate() public Date getReceivedDate() public int getSize() public int getLineCount() public String getContentType() public void setContentID(String cid) public String getContentID() public void setDescription(String description) public String getDescription() public void setContentLanguage(String[] languages) public String[] getContentLanguage()

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

Methods of InternetAddress Object


public void setAddress(String address) public String getAddress() public void setPersonal(String name)throws UnsupportedEncodingException public String getPersonal() public boolean equals(Object a) public int hashCode() public boolean isGroup() public InternetAddress[] getGroup(boolean strict)throws AddressException

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);

PasswordAuthentication Object Constructor & Methods


PasswordAuthentication(String userName, String password) public String getUserName() public String getPassword()

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();

Store and Folder Objects


Getting messages starts similarly to sending messages, with a Session. However, after getting the session, you connect to a Store, quite possibly with a username and password or Authenticator. Like Transport, you tell the Store what protocol to use:

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

Folder Object Methods


public abstract String getName() public abstract String getFullName() public Store getStore() public abstract Folder getParent()throws MessagingException public Folder[] list()throws MessagingException public abstract char getSeparator()throws MessagingException public abstract boolean renameTo(Folder f)throws MessagingException public abstract int getMessageCount()throws MessagingException public int getNewMessageCount()throws MessagingException public int getUnreadMessageCount()throws MessagingException public int getDeletedMessageCount()throws MessagingException public abstract Message getMessage(int msgnum)throws MessagingException public Message[] getMessages(int start,int end)throws MessagingException public Message[] getMessages(int[] msgnums)throws MessagingException public Message[] getMessages()throws MessagingException public void copyMessages(Message[] msgs,Folder folder)throws MessagingException public Message[] search(SearchTerm term)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()

Sending Email Message


Procedure 1. Add the name of your SMTP server to the properties for the mail.smtp.host key. 2. Get a Session object based on the Properties. 3. Create a MimeMessage from the session. 4. Set the From field of the message. 5. Set the To field of the message. 6. Set the subject of the message. 7. Set the content of the message. 8. Use a Transport to send the message. 9. Compile and run the program, passing your SMTP server, from address, and to address on the command line. Program for sending email import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendMail{ public static void main(String[] args){ String host = "smtp.mydomain.com"; String from = "me@myweb.com"; String to = "you@nyweb.com"; Properties prop = System.getProperties(); prop.put("mail.smtp.host", host); Session ses = Session.getDefaultInstance(prop, null); MimeMessage msg = new MimeMessage(ses); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.To, new InternetAddress(to)); msg.setSubject("test"); msg.setText("This is a test message"); Transport.send(msg); } }

Page 9 of 10

Retrieving Email Messages


For reading mail, you get a session, get and connect to an appropriate store for your mailbox, open the appropriate folder, and get your message(s). Also, don't forget to close the connection when done 1. Get a Session object based on the Properties. 2. Get a Store for our email protocol, either pop3 or imap. 3. Connect to our mail host's store with the appropriate username and password. 4. Get the folder you want to read. More than likely, this will be the INBOX. 5. Open the folder read-only. 6. Get a directory of the messages in the folder. Save the message list in an array variable named message. 7. For each message, display the from field and the subject. Display the message content when prompted. 8. Close the connection to the folder and store. 9. Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT.

Page 10 of 10

Das könnte Ihnen auch gefallen