Docsity

TUTORIALS POINT Simply Easy Learning JavaMail API tutori, Ejercicios de Administración de Empresas

Vista previa parcial del texto

¡Descarga TUTORIALS POINT Simply Easy Learning JavaMail API tutori y más Ejercicios en PDF de Administración de Empresas solo en Docsity!

JavaMail API Tutorial

i

JAVAMAIL API TUTORIAL

Simply Easy Learning by tutorialspoint.com

tutorialspoint.com

TUTORIALS POINT

TUTORIALS POINT

JavaMail API – Overview

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and

messaging applications. The JavaMail API provides a set of abstract classes defining objects that comprise a mail system. It is an optional package (standard extension) for reading, composing, and sending electronic messages.

JavaMail provides elements that are used to construct an interface to a messaging system, including system components and interfaces. While this specification does not define any specific implementation, JavaMail does include several classes that implement RFC822 and MIME Internet messaging standards. These classes are delivered as part of the JavaMail class package.

Following are some of the protocols supported in JavaMail API:

 SMTP : Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email.
 POP : Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their

mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol.

 IMAP : Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It

provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.

 MIME : Acronym 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. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs.

 NNTP and Others :There are many protocols that are provided by third-party providers. Some of them are

Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

Details of these will be covered in the subsequent chapters.

CHAPTER

TUTORIALS POINT

Architecture

As said above the java application uses JavaMail API to compose, send and receive emails.The following figure illustrates the architecture of JavaMail:

The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is divided into two main parts:

 An application-independent part: An application-programming interface (API) is used by the application

components to send and receive mail messages, independent of the underlying provider or protocol used.

 A service-dependent part: A service provider interface (SPI) speaks the protocol-specific languages, such as

SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform.

TUTORIALS POINT

JavaMail API - Core Classes

The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail

messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages con tain all the JavaMail core classes. They are:

Class Description

javax.mail.Session The key class of the API. A multithreaded object represents the connection factory.

javax.mail.Message

An abstract class that models an e-mail message. Subclasses provide the actual implementations.

javax.mail.Address An abstract class that models the addresses (from and to addresses) in a message. Subclasses provide the specific implementations.

javax.mail.Authenticator An abstract class used to protect mail resources on the mail server.

javax.mail.Transport

An abstract class that models a message transport mechanism for sending an e-mail message.

javax.mail.Store

An abstract class that models a message store and its access protocol, for storing and retrieving messages. A Store is divided into Folders.

javax.mail.Folder

An abstract class that represents a folder of mail messages. It can contain subfolders.

javax.mail.internet. MimeMessage

Message is an abstract class, hence must work with a subclass; in most cases, you’ll use a MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers.

javax.mail.internet. InternetAddress

This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form [email protected] or _Personal Name _.

Let us study each of these classes in detail and in the subsequent chapters we shall study examples using each of these.

Session Class

The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication.

CHAPTER

TUTORIALS POINT

Session object can be created in the following ways:

 By looking up the administered object stored in the JNDI service

InitialContext ctx = new InitialContext();
Session session = (Session) ctx.lookup("usersMailSession");

Users MailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object.

 Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application.

The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object.

getDefaultInstance() : There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.

public static Session getDefaultInstance(Properties props) public static Session getDefaultInstance(Properties props,Authenticator auth)

getInstance() : There are two methods to get the session object by using the getInstance() method. It returns the new session.

public static Session getInstance(Properties props)

public static Session getInstance(Properties props,Authenticator auth)

Message Class

With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message.

Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used.

 To create the message, you need to pass session object in MimeMessage class constructor. For example:

MimeMessage message=new MimeMessage(session);

 Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content.

 Commonly used methods of MimeMessage class are

Method Description

public void setFrom(Address address) used to set the from header field. public void addRecipients(Message.RecipientType type, String addresses)

used to add the given address to the recipient type. public void setSubject(String subject) used to set the subject header field.

public void setText(String textmessage) used to set the text as the message content using text/plain MIME type.

TUTORIALS POINT

Transport Class

Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message.

 It is an abstract class.
 You can use the default version of the class by just calling the static send() method:
Transport.send(message);
 The other way to send message is by getting 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()

//Get transport for session Transport transport = session.getTransport("smtp");

//Connect transport.connect(host, username, password);

//repeat if necessary transport.sendMessage(message, message.getAllRecipients());

//Done, close the connection transport.close();

Store Class

An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to connection events.

Clients gain access to a Message Store by obtaining a Store object that implements the database access protocol. Most message stores require the user to be authenticated before they allow access. The connect method performs that authentication.

Store store = session.getStore("pop3"); store.connect(host, username, password);

Folder Class

Folder is an abstract class that represents a folder for mail messages. Subclasses implement protocol specific Folders. Folders can contain subfolders as well as messages, thus providing a hierarchical structure.

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

TUTORIALS POINT

The getFolder(String name) method for a Folder object returns the named subfolder. Close the both the Store and Folder connection once reading mail is done.

We can see the Store and Folder relation the image below:

As we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders.

TUTORIALS POINT

JavaMail API - Sending Simple

Email

Here is an example to send a simple email. Here we have used JangoSMPT server via which emails are sent to

our destination email address. The setup is explained in the Environment Setup chapter.

To send a simple email steps followed are:

 Get a Session
 Create a default MimeMessage object and set From, To, Subject in the message.
 Set the actual message as:
message.setText("your text goes here");
 Send the message using the Transport object.

Create Java Class

Create a java class file SendEmail , the contents of which are as follows:

package com.tutorialspoint;

import java.util.Properties;

import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;

public class SendEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]";

// Sender's email ID needs to be mentioned String from = "[email protected]"; final String username = "manishaspatil";//change accordingly

CHAPTER

TUTORIALS POINT

final String password = "******";//change accordingly

// Assuming you are sending email through relay.jangosmtp.net

String host = "relay.jangosmtp.net";

Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25");

// Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } });

try { // Create a default MimeMessage object. Message message = new MimeMessage(session);

// Set From: header field of the header. message.setFrom(new InternetAddress(from));

// Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

// Set Subject: header field

message.setSubject("Testing Subject");

// Now set the actual message

message.setText("Hello, this is sample for to check send " +

"email using JavaMailAPI ");

// Send message

Transport.send(message);

System.out.println("Sent message successfully....");

TUTORIALS POINT

JavaMail API - Sending Email With

Attachment

Here is an example to send an email with attachment from your machine. The file on local machine is file.txt

placed at /home/manisha/. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter.

To send a email with an inline image, the steps followed are:

 Get a Session
 Create a default MimeMessage object and set From, To, Subject in the message.
 Set the actual message as below:
messageBodyPart.setText("This is message body");
 Create a MimeMultipart object. Add the above messageBodyPart with actual message set in it, to this multipart

object.

 Next add the attachment by creating a Datahandler as follows:

messageBodyPart = new MimeBodyPart(); String filename = "/home/manisha/file.txt";

DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source));

messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart);

 Next set the multipart in the message as follows:

message.setContent(multipart);

 Send the message using the Transport object.

Create Java Class

Create a java class file SendAttachmentInEmail , the contents of which are as follows:

CHAPTER

TUTORIALS POINT

package com.tutorialspoint;

import java.util.Properties;

import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart;

public class SendAttachmentInEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "[email protected]";

// Sender's email ID needs to be mentioned String from = "[email protected]";

final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly

// Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net";

Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25");

// Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } });

try { // Create a default MimeMessage object. Message message = new MimeMessage(session);

// Set From: header field of the header. message.setFrom(new InternetAddress(from));

// Set To: header field of the header.