Using the JavaMail API

The previous section summarizes all the main classes of the JavaMail API, and in this section, you'll learn how to connect all the pieces together to perform the regular operations of e-mail services. You'll explore how to send, reply, and forward messages, in addition to finding out how to read or retrieve and delete them.

Sending Messages with JavaMail

Sending an e-mail message can vary between sending a plain text message and a rich-content message. The next sections shed light on how to send messages in languages that aren't Latin based. Forwarding and replying to messages are also implemented by sending messages. You'll learn how to send messages with attachments.

Sending a Text Message

This is the most common method of sending e-mail messages. Here are the steps to send a message with JavaMail from within you application components in the Web tier or the EJB tier:

1.
Import the JNDI (naming), JavaBean activation, and JavaMail packages. You'll also need to import java.util.Properties:

import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;

2.
Look up the mail session in the JNDI service by using the default context:

InitialContext ic = new InitialContext();
Session session = (Session) ic.lookup("ursMailSession");

3.
Use the properties to override the default Session by creating a Properties object and adding the properties you want to override. Then call getInstance() to get a new Session object with the new properties.

4.
Construct a MimeMessage with the recipient's address, subject, and body parts of the message. Create an Address for each recipient of the message:

String body = "Welcome to the new world of JavaMail";
Message msg = new MimeMessage(session);
Address to = new InternetAddress("[email protected]");
msg.setFrom();
meg.addRecipient(Message.RecipientType.TO, to);
msg.setSubject("Hello");
msg.setSentDate(new Date());
msg.setText(body);

In the setFrom() method, the value of the attribute is obtained implicitly from the mail.user property, which is set during the configuration of the mail Session. If this property is absent, the system property user.name is used.

5.
Send the message.

Transport.send(msg);

If the JNDI lookup fails, the NamingException will be thrown; if JavaMail transport fails, the MessagingException will be thrown. You must put your code in a try block and catch these exceptions.

Replying to Messages

To reply to a message, you must create a new message from the original by using the reply() method. You also need to set the new Message with the proper recipient and subject, and add the "Re: " if it isn't already there. The reply() method copies the from or reply-to header to the new recipient. It doesn't add any content to the original message, so you need to set the body of the new message. The method also takes a Boolean parameter indicating whether to reply to only the sender (false) or reply to all the recipients (true). The following is an example of replying only to the sender:

MimeMessage reply = (MimeMessage) msg.reply(false);
reply.setFrom(new InternetAddress("[email protected]"));
reply.setText("Have Fun!");
Transport.send(reply);

To set the reply-to address when sending a message, use the setReplyTo() method.

Forwarding Messages

To forward a message to a new recipient, you must construct a new message and then populate its parts. An e-mail message can be made up of multiple parts. Each part is a MimeBodyPart, and the different body parts are combined into a container called a MimeMultipart. To forward a message, you create one part for the text of your message and a second part with the message to forward, and then combine the two into a multipart message. Then you add the multipart message to a properly addressed message and send it. Here's an example of forwarding a message:

Address to = new InternetAddress("[email protected]");
Message forward = new MimeMessage(session);
forward.setSubject("Fwd: " + msg.getSubject());
forward.setFrom(new InternetAddress(msg.getFrom()));
forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Construct the message part of the text
BodyPart mbp1 = new MimeBodyPart();
mbp.setText("fyi");
// Create a multi-part to combine the parts
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
// Construct the message part of the forwarded content
BodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(msg.getDataHandler());
mp.addBodyPart(mbp2);
// Associate the multipart with the message
forward.setContent(mp);
// Send the message
Transport.send(forward);

Sending a Message with Attachments

Resources can be attached to and detached from messages using the JavaMail API. Attachments are resources that are associated with a mail message, and are usually kept outside of that message; for example, a text file, a Word document, or an image. A message with attachments is represented as a MIME multipart message in which the first part is the main body of the message and the other parts are the attachments. Sending a message with an attachment is similar to forwarding a message; here's an example:

Message msg = new MimeMessage(session);
String filename="c:myfiles
otes.doc";
Multipart mp = new MimeMultipart();
// Construct the message text part
mp.addBodyPart("Attached find my document.");
// Construct the attachment part
MimeBodyPart mbp = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
mbp.setDataHandler(new DataHandler(source));
mbp.setFileName(filename);
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);

The FileDataSource is part of the Java Activation Framework, and its constructor accepts a String that indicates the full filename on the disk.

Sending Messages as HTML and Images

New e-mail systems support HTML and image content. To send an HTML file, you use the more generic setContent() method, and set the MIME type to text/html, as follows:

String html = "<HTML><H1> Welcome to the new world of JavaMail</H1></HTML>";
Message msg = new MimeMessage(session);
msg.setContent(html, "text/html");

On the other hand, if you want your HTML content message to be complete with embedded images included as part of the message, you must treat those images as attachments and reference each one with a special content ID (CID) URL, where the CID is a reference to the Content-ID header of the image attachment:

Message msg = new MimeMessage(session);
BodyPart mbp = new MimeBodyPart();
String html = "<H1>Welcome to the world of JavaMail</H1>" +
              "<img src="cid:img1">";
mbp.setContent(html, "text/html");
// Create a related multi-part to combine the parts
MimeMultipart mp = new MimeMultipart("related");
mp.addBodyPart(mbp);
// Create part for the image
mbp = new MimeBodyPart();
// Fetch the image and associate to part
DataSource img = new FileDataSource("images/logo.gif");
mbp.setDataHandler(new DataHandler(img));
mbp.setHeader("Content-ID","img1");
// Add part to multi-part
mp.addBodyPart(mbp);
// Associate multi-part with message
msg.setContent(mp);

Sending Message Content Based on Locale

Situations sometimes arise in which you need to send a message in a language other than a Latin-based script (char set). This is common in internationalization (i18n) efforts of enterprise applications. To accomplish this, you must set the message to the right locale for the language. The following example is set to send an e-mail message based on the Japanese locale (ISO-2022-JP):

Message msg = new MimeMessage(session);
msg.setSubject(subject, "ISO-2022-JP");
msg.setText(body, "iso-2022-jp");

Note

Some Web servers are familiar only with the ISO-8859-1 (Western European) char set, and they can't decode messages written in other char sets. You might need to check the Web server documentation before sending messages using different char sets.


Reading Messages with JavaMail

Reading mail messages involves fetching the messages from the message store. The JavaMail API enables you to connect to a message store, which could be an IMAP server or POP3 server. The JavaMail API provides several options for reading messages, such as reading a specified message number or range of message numbers, or prefetching specific parts of messages into the folder's cache. Here's an example of reading incoming messages on a POP3 server:

Store store = session.getStore("POP3");
store.connect(host, userid, password);
Folder mbox = store.getFolder("INBOX");
mbox.open(Folder.READ_ONLY);
Message msg[] = mbox.getMessages();
//...process each message according to requirements...
mbox.close(false);
store.close();

Each message in the preceding snippet is processed according to your business requirements.

Note

Reading messages from an IMAP server is similar to reading messages from a POP3 server. With IMAP, however, the JavaMail API provides methods to create and manipulate folders and transfer messages between them. If you use an IMAP server, you can implement a full-featured, Web-based mail client with much less code than if you use a POP3 server.


Deleting Messages and Flags

To delete a message, you must connect to the message store and open the message folder using READ_WRITE mode. You must flag the message with the Flags.Flag.DELETED flag (too many flags!). When you've processed all the messages, close the folder, and pass in a true value to expunge the deleted messages. The following code snippet demonstrates how to delete a message:

mbox.open(Folder.READ_WRITE);
Message msg = mbox.getMessage(1);
msg.setFlag(Flags.Flag.DELETED, true);
mbox.close(true);

The setFlag() method does not delete the message, it only marks the message for deletion. The close() method with the true parameter value is where messages are deleted or expunged.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.91.254