Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Send Receive Mails in Java with JavaMail (http://www.go4expert.com/articles/send-receive-mails-java-javamail-t3649/)

Mary 28Mar2007 08:26

Send Receive Mails in Java with JavaMail
 
The JavaMail API (http://java.sun.com/products/javamail/) is a messaging framework intended to build platform-independent applications that use e-mail messaging. It is included in the J2EE platform and is available as an optional package in J2SE. The API's main purpose is not for transporting, delivering, and forwarding messages, but rather providing protocol-independent access to mail infrastructure for sending and receiving messages.

Overview



The JavaMail API is divided into two parts:

The main part of the API is focused on sending and receiving messages (independent of the protocol).
The second part implements protocol-specific languages, such as SMTP, POP, IMAP, and NNTP. With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. (Sun provides a sufficient set of providers for free - at least SMTP, POP, and IMAP, which is more than enough for sending and receiving standard e-mail messages over standard Internet infrastructure.)

All versions of the JavaMail API require the JavaBeans Activation Framework, which adds support for typing arbitrary blocks of data and handling it accordingly. JavaMail uses Multipurpose Internet Mail Extensions (MIME) implementation from that framework. The MIME implementation defines the content of what is transferred in an e-mail: the format of messages, attachments, and so on. In order to use JavaMail, an application must include classpathmail.jar and activation.jar to operate properly. If you use J2EE, there is nothing special you have to do to use the basic JavaMail API - it comes with J2EE classes.

In 2006, JavaMail became open source, and the source code for the JavaMail API Reference Implementation is now available under the open source license as part of the project called GlassFish (https://glassfish.dev.java.net/).

Classes



Here is an overview of some of the most important classes used in JavaMail applications:

javax.mail.Session: This class is used to control access to the implementations of the other mail classes that represent the services offered by the mail system, for instance javax.mail.Store. (Be careful not to confuse this class with javax.servlet.http.HttpSession.)

javax.mail.Transport: This class is used for sending mail messages via a specific protocol such as SMTP, as implemented by the service provider.

javax.mail.Store: This class is implemented by the service provider. It aims to allow access to read, write, monitor, and search activities for a particular mail protocol such as POP3 or IMAP4. A reference to the javax.mail.Folder class is obtained via this class.

javax.mail.Folder: This class gives a hierarchical view of javax.mail.Message objects and provides access to specific messages for read, delete, and reply actions.

javax.mail.internet.MimeMessage: This class models the actual mail message. It holds very little information and data about the message when it is first instantiated; as successive methods retrieve more data about the message, this class is used to store that data.

javax.mail.internet.InternetAddress: This class models a RFC822 (Internet standard) e-mail address, i.e., an address of the form admin@go4expert.com. If an incorrect address format is encountered, an error occurs and an AddressException is thrown within the Java method processing the e-mail address.

Usage example



Snippet A contains sample code that sends a test message. In this example, you should replace the placeholder e-mail addresses with real addresses and replace smtp.go4expert.com with the address of a real SMTP server that is used by your Internet provider or company.

Snippet A
Code: Java

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

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.go4expert.com");
Session s = Session.getInstance(props,null);

MimeMessage message = new MimeMessage(s);

InternetAddress from = new InternetAddress("my@go4expert.com");
message.setFrom(from);
InternetAddress to = new InternetAddress("to@go4expert.com");
message.addRecipient(Message.RecipientType.TO, to);

message.setSubject("Test from JavaMail.");
message.setText("Hello from JavaMail!");

Transport.send(message);

A Session object is created representing our e-mail session. The Session object's constructor requires a java.util.Properties object representing the session's key information. For this example, you only need to set the "mail.smtp.host" property to an appropriate SMTP host. After that, you create the actual MimeMessage object and customise it for the e-mail. Two InternetAddress objects are needed representing the "from" and "to" addresses respectively. In your code, these should be valid e-mail addresses that you can access. Once the addresses are set for the e-mail, a subject and a simple message is set.

Finally, the message is ready to be sent. In JavaMail, the Transport object handles sending messages. Since we only have one, the static send method is used. This method uses the SMTP server specified as the "mail.smtp.host" address.

Beyond the basics



The JavaMail API has many advanced capabilities. As an example, you can add any mail headers to the message, set up multiple recipients, create blind copies of a message (what BCC is intended for), recode the message text into different charset encodings, and so on. For example, Listing B shows how to add multiple recipients.

Snippet B
Code: Java

String toAddresses = "address1@go4expert.com; address2@go4expert.com";
// Add to To: header
message.addRecipients(Message.RecipientType.TO, toAddresses);
String ccAddresses = "cc_address1@go4expert.com; cc_address2@go4expert.com";
// Add to Cc: header
message.setRecipients(Message.RecipientType.CC, ccAddresses);
String bccAddresses = "bcc_address1@go4expert.com; bcc_address2@go4expert.com";
// Add to Bcc: header
message.setRecipients(Message.RecipientType.BCC, bccAddresses);

If you send a message with a non-ASCII character (an accentuated character), the recipient may have problems reading it. To make the message easier to read, try adding the following lines to give a hint about the encoding:
Code: Java

MimeMessagemimeMsg = new MimeMessage(session);
mimeMsg.setHeader("Content-Transfert-Encoding", "8Bit");
mimeMsg.setText(frenchMsg, "iso-8859-1");
Transport.send((Message)frenchMsg);

This is fine for the body, but in order to correctly display accentuated characters in a title, you need to encode it using the 'quoted-printable' or 'base64' encodings. Hopefully, you can also use the javax.mail.internet.MimeUtility class. The encodeText() method will make sure that a passed string is "mail safe." Snippet C shows how you will send an e-mail with an attachment.

Snippet C
Code: Java

// create a message
Message msg = new MimeMessage(session);

// set the from
msg.setFrom(fromAddress);

InternetAddress[] address ={new InternetAddress(_to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(_subject);

MimeBodyParttextPart = new MimeBodyPart();
textPart.setContent(_bodyText, "text/plain");

MimeBodyPartattachFilePart = new MimeBodyPart();
FileDataSourcefds = new FileDataSource(_fileName);
attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fds.getName());

Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
mp.addBodyPart(attachFilePart);

msg.setContent(mp);
Transport.send(msg);

Conclusion



The ways in which you can use the JavaMail API are beyond the scope of this article. For a full description, refer to JSR 919, which is the latest JavaMail 1.4 specification. The Sun JavaMail API is the full reference implementation of this specification, so just install it and then take the rich features out for a test drive.


All times are GMT +5.5. The time now is 10:23.