Top 25 Javamail Api Interview Questions You Must Prepare 19.Mar.2024

Java Mail API provides classes to send multiple Mime body part with one Mime Message. MulipltMimeBody parts can be text, file or image. All message are stored in Folder objects. folders can contain folders or messages. The Folder class declares methods that fetch, append, copy and delete messages, and message contain Attachment.

package com.withoutbook.common;

import java.io.*;
import java.util.*;
import javax.mail.*;
public class ReadAttachment {
public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String user = "arindam";
String password = "arindam";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_WRITE);
Message[] message = folder.getMessages();
for (int a = 0; a < message.length; a++) {
System.out.println("-------------" + (a + 1) + "-----------");
System.out.println(message[a].getSentDate());
Multipart multipart = (Multipart) message[a].getContent();
//System.out.println(multipart.getCount());
for (int i = 0; i < multipart.getCount(); i++) {
//System.out.println(i);
//System.out.println(multipart.getContentType());
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while (br.ready()) {
System.out.println(br.readLine());
}
System.out.println();
}
System.out.println();
}
folder.close(true);
store.close();
}
}

The Message class have a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, reply() method have a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true).

MimeMessage reply = (MimeMessage)message.reply(false);reply.setFrom(new InternetAddress("president@whitehouse.gov"));reply.setText("Thanks");Trport.send(reply);

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

package com.withoutbook.common;

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ReplyMail {
public static void main(String args[]) throws Exception {
Date date = null;
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "192.168.10.110");
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect("192.168.10.110", "arindam", "arindam");
Folder folder = store.getFolder("inbox");
if (!folder.exists()) {
System.out.println("inbox not found");
System.exit(0);
}
folder.open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Message[] message = folder.getMessages();
if (message.length != 0) {
System.out.println("no. From ttSubject ttDate");
for (int i = 0, n = message.length; i < n; i++) {
date = message[i].getSentDate();
System.out.println(" " + (i + 1) + ": " + message[i].getFrom()[0] + "t" +
message[i].getSubject() + " t" + date.getDate() + "/" +
date.getMonth() + "/" + (date.getYear() + 1900));
System.out.print("Do you want to reply [y/n] : ");
String = reader.readLine();
if ("Y".equals() || "y".equals()) {
// Create a reply message
MimeMessage reply = (MimeMessage) message[i].reply(false);
// Set the from field
reply.setFrom(message[i].getFrom()[0]);
// Create the reply content
// Create the reply content, copying over the original if text
MimeMessage orig = (MimeMessage) message[i];
StringBuffer buffer = new StringBuffer("Thanksnn");
if (orig.isMimeType("text/plain")) {
String content = (String) orig.getContent();
StringReader contentReader = new StringReader(content);
BufferedReader br = new BufferedReader(contentReader);
String contentLine;
while ((contentLine = br.readLine()) != null) {
buffer.append("> ");
buffer.append(contentLine);
buffer.append("rn");
}
}
// Set the content
reply.setText(buffer.toString());
// Send the message
Trport.send(reply);
} else if ("n".equals()) {
break;
}
}
} else {
System.out.println("There is no msg....");
}
}
}

After creating session object, create message to send by using Message class. Because of message class is abstract class so we will use subclass javax.mail.internet.MimeMessage.

MimeMessage message = new MimeMessage(session) 
// set the content of message by setContent() method
message.setContent(“www.roseindia.net”, "text/plain");
We can also use setText() method to set the content.
Message.setText("www.roseindia.net");
To create subject line of sending message use setSubject() method.

IMAP: Short for Internet Message Access Protocol. This is another most prevalent protocol of internet standard for email usage apart from POP. Usually all the modern email server and client supports these two protocols for trmitting the email messages. For Example Gmail server uses to trmit the message to a client such as Mozilla Thunderbird and Microsoft Outlook.

IMAP is an application layer protocol over internet that is operating from port no. 143 that allows the accessibility of email on a remote server by a client. IMAP supports the online and offline (disconnected) modes of operations. Usually the email clients using IMAP utilizes the facility of leaving the message on the server. The message lasts until the user explicitly deletes them. IMAP also allows multiple clients to have the accessibility of the same mailbox.

JavaMail will work in any browser that supports the required JDK version. The Java Plug-in may be required to provide such support.

There are some protocols that are used in JavaMail API.

  • SMTP
  • POP
  • IMAP
  • MIME
  • NNTP and others

SMTP : SMTP is an acronym for Simple Mail Trfer Protocol. It provides a mechanism to deliver the email. We can use Apache James server, Postcast server, cmail server etc. as an SMTP server. But if we purchase the host space, an SMTP server is bydefault provided by the host provider. For example, my smtp server is mail.javatpoint.com. If we use the SMTP server provided by the host provider, authentication is required for sending and receiving emails.

POP : POP is an acronym for Post Office Protocol, also known as POP@It provides a mechanism to receive the email. It provides support for single mail box for each user. We can use Apache James server, cmail server etc. as an POP server. But if we purchase the host space, an POP server is bydefault provided by the host provider. For example, the pop server provided by the host provider for my site is mail.javatpoint.com. This protocol is defined in RFC 1939.

IMAP : IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced protocol for receiving messages. It provides support for multiple mail box for each user ,in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.

MIME : Multiple Internet Mail Extension (MIME) tells the browser what is being sent e.g. attachment, format of the messages etc. It is not known as mail trfer protocol but it is used by your mail program.

NNTP and Others : There are many protocols that are provided by third-party providers. Some of them are Network News Trfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

POP: The Post Office Protocol is an application-level protocol within an intranet which are used by the local e-mail clients to send and retrieve e-mails from a remote server those are connected using TCP/IP. POP is one of the most prevalent protocol fro the usage of e-mail. The POP and its procedures support the end-users with dial-up network connections.

POP allows the users to retrieve e-mail when connected and later allows viewing and altering the retrieved messages. This is done with a promising feature – without staying connected. The process of using emails over POP is to connect, retrieve the messages, and store them on the user’s PC as a new message. Later these messages can be ‘deleted from the server’ and disconnecting the server – makes POP a distinguished protocol.

 

There are two packages that are used in Java Mail API: javax.mail and javax.mail.internet package. These packages contains many classes for Java Mail API. They are:

  • javax.mail.Session class
  • javax.mail.Message class
  • javax.mail.internet.MimeMessage class
  • javax.mail.Address class
  • javax.mail.internet.InternetAddress class
  • javax.mail.Authenticator class
  • javax.mail.PasswordAuthentication class
  • javax.mail.Trport class
  • javax.mail.Store class
  • javax.mail.Folder class etc.

 

Potential advantages include - Java mail is used to create personal mail filter, simple mailing lists and personal mail applications. Java mail also includes the capabilities to add the emailing process to an enterprise application or even to create a full-fledged e-mail client. Many companies in the industry have written new e-mail clients using Java Mail.

MIME and RFC822 are the standards for describing email messages that are sent across the Internet. The javax.mail.internet subpackage (which is part of the JavaMail APIs) provides a complete implementation of these two packages. MIME is specified by the following RFCs: RFC2045, RFC2046, RFC2047.

After getting the session you connect to javax.mail.Store class with Authenticator or host, port, user and password information. Store object that implements the specified protocol can be created by by passing the protocol information to the getStore() method of the session object.

Store store = session.getStore("pop3");

store.connect(host, username, password);

After connecting to store you need to get a folder that holds messages. For POP3, the only folder available is the INBOX but with IMAP, you can have other folders available. For this you can use javax.mail.Folder class.

Folder folder = store.getFolder("INBOX");

folder.open(Folder.READ_ONLY);

Message message[] = folder.getMessages();

Once you have read messages, you need to close Store and Folder.

folder.close(booleanValue);

store.close();

These days Multipart mail is used to compose emails with attachment. In the email you can attach images, zip files, xls, doc etc.. It allows you to create nicely design emails.

Java Mail API also provides classes to create, send and read the Multipart message. If you have given a task to create emails with attachment in Java technologies, then you can use the Java Mail api to accomplish your task.

Using the Multipart Class

Following code snippet shows how you can use the Multipart class. You have to create the object of Multipart class and then you can get the body part and compose or read your email.

Multipart multipart = (Multipart) msg[i].getContent();After that create BodyPart object BodyPart bodyPart = multipart.getBodyPart(x);

And then read bodyPart content using getContent() method.

 

package com.withoutbook.common;
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
public class ReadMultipartMail {
public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String username = "arindam";
String passwoed = "arindam";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("pop3");
store.connect(host, username, passwoed);
Folder folder = store.getFolder("inbox");
if (!folder.exists()) {
System.out.println("No INBOX...");
System.exit(0);
}
folder.open(Folder.READ_WRITE);
Message[] msg = folder.getMessages();
for (int i = 0; i < msg.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
String from = InternetAddress.toString(msg[i].getFrom());
if (from != null) {
System.out.println("From: " + from);
}
String replyTo = InternetAddress.toString(
msg[i].getReplyTo());
if (replyTo != null) {
System.out.println("Reply-to: " + replyTo);
}
String to = InternetAddress.toString(
msg[i].getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}
String subject = msg[i].getSubject();
if (subject != null) {

System.out.println("Subject: " + subject);
}
Date sent = msg[i].getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}
System.out.println();
System.out.println("Message : ");
Multipart multipart = (Multipart) msg[i].getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
System.out.println();
}
folder.close(true);
store.close();
}
}

A client create new message by using Message subclass. It sets attributes like recipient address and the subject, and inserts the content into the Message object, and inserts the content into the Message object. Finally, it sends the Message by invoking the Trport.send() method.

The Trport class models the trport agent that routes a message to its destination addresses. This class provides methods that send a message to a list of recipients. Invoking the Trport.send() method with a Message object identifies the appropriate trport based on its destination addresses.

package com.withoutbook.common;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class HTMLMail {
public static void main(String args[]) throws Exception {
Strig host = "192.168.10.110";
String from = "arindam@localhost";
String to = "arindam@localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set the RFC 822 "From" header field using the 
// value of the InternetAddress.getLocalAddress method.
message.setFrom(new InternetAddress(from));
// Add the given addresses to the specified recipient type.
message.addRecipient(Message.RecipientType.TO, 
new InternetAddress(to));
// Set the "Subject" header field.
message.setSubject("hi..!");
String htmlText = "
Hello
// Sets the given String as this part's content, // with a MIME type of "text/plain".
message.setContent(htmlText, "text/html");
// Send message
Trport.send(message);
System.out.println("Message Send.....");
}
}

Session is the top-level entry class representing mail session. It uses java.util.Properties object to get information about mail server, username, password etc. This class has a private constructor and you can get session objects through getInstance() and getDefaultInstance() methods. getDefaultInstance() method provides default Session object which takes Properties and Authenticator objects as arguments.

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Or create a unique session by getInstance() method…

Properties props = new Properties();
Session session = Session.getInstance(props, null);

 A "local store provider" can be used to store mail messages on a local disk. The JavaMail API download does not include such a provider but a provider that supports the Unix mbox format is available in the JavaMail source repository that you can build yourself. See this page for details. In addition, several local store providers are available from third parties for different local store formats such as MH and Mbox. See our Third Party Products page for the latest list of such providers.

  • JavaMail is a set of abstract classes that create a framework for sending, receiving and handling e-mail.
  • The package that Sun provides contains implementations of IMAP and SMTP, which allow sending and receiving mail.
  • The framework eases the creation of cross-platform mail application without an in-depth knowledge of e-mail.
  • There are methods and classes that allow access to mail folders, download messages, send messages with attachments and filter mail.

SMTP: Simple Mail Trfer Protocol, for sending email between ‘servers’. Most of the emailing systems implement the messages over internet use SMTP. The message sent from one server to another server, and then the message can be retrieved by an email client. The client uses either POP or IMAP. In addition to this process, SMTP is also generally used for message sending and retrieval from a mail client to a mail server. This is the reason why the need of POP or IMAP server and the SMTP servers at the time of configuring the email application.

Java Mail is an API that is used to receive and send emails between applications. To send the emails, the protocols, SMPT, POP AND IMAP are used. The messages sending and receiving is done by creating a framework using set of abstract classes in the API. The framework allows the application to create customized cross-platform mail application by having basic knowledge of e-mail. There are methods and classes that are used to access mail folders, message downloading and sending messages along with attachments feature.

Potential advantages include - Java mail is used to create personal mail filter, simple mailing lists and personal mail applications. Java mail also includes the capabilities to add the emailing process to an enterprise application or even to create a full-fledged e-mail client. Many companies in the industry have written new e-mail clients using Java Mail.

The JavaMail is an API that is used to compose, write and read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.

The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API.

The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the users email id), sending notifications for important updates etc. So there can be various usage of java mail api.

The java application uses JavaMail API to compose, send and receive emails. The JavaMail API uses SPI (Service Provider Interfaces) that provides the intermediatory services to the java application to deal with the different protocols. 

This is final part of sending Email, it is an abstract class. Default version of this class can be used by calling static send() method.

Trport.send(message); 

Or can create a specific instance from the session for defined protocol.

message.saveChanges();

Trport trport = session.getTrport("smtp");

trport.connect(host, username, password);

trport.sendMessage(message, message.getAllRecipients());

trport.close();

Address class is also an abstract class so we will use here class javax.mail.internet.InternetAddress.
Address address = new InternetAddress("arindam@withoutbook.com");
To display a name next to the Email Address use one more argument for name.
Address address = new InternetAddress("arindam@withoutbook.com", "Arindam");

After creating address connect with message by two ways: 

1: By setFrom()method: message.setFrom(address);
1: By setReplyTo()method: When want to send reply to more addresses.
Address address[] = ...;
Message.setReplyTo(address[]);
To identify the recipient, add the recipients by using addRecipient() method….
message.addRecipient(type, address);

Address types are of three types:

  • Message.RecipientType.TO: primary recipient
  • Message.RecipientType.CC: carbon copy
  • Message.RecipientType.BCC: blind carbon copy

The JavaMail API has classes such as Message, Store and Trport. The API can be used to subclass for providing new protocols and some additional functionality when needed. The concrete subclasses of this API are MimeMessage and MimeBodyPart which are implemented widely by the internet mail protocols. The supporting protocols for Javamail API are IMAP4, POP3 and SMTP.

The Java mail architectural components include the following: 

Abstract Layer: This layer declares the classes, interfaces and abstract methods that are intended for supporting the mail functions which all mailing systems supports. Intranet Implementation Layer: The implementation of MIME internet standards and part of the abstract layer comprises this layer. Java Bean Activation Framework: The encapsulation of message data and handling the data interacting commands is used by the Javabean

MIME message includes the picture stored as file in GIF format and the GIF format uses 8-bit format. The RFC 822 uses ASCII text format. The messages in the form of ASCII text format is to be encoded. To display the image in the recipient system, the information abut the encoding mechanism is used. The message is to be made up in the recipient’s application. The following snippet is used to identify the content is a GIF file which is to be encoded using the standard “base64Algorithm. This is to be treated as an attachment by the client who uses the email.

Content-Type: image/gif;
name="waterfall.gif"
Content-Trfer-Encoding: base64
Content-Disposition: attachment;
filename="waterfall.gif"
[Author the encoded content here]
..

The accomplishment of this is done by simplifying and rebuilding of complex files. These files are encoded and trported as a body of the message or a series of messages which are the parts of the file.A message format is defined by the MIME that allows the following:

Non ASCII character textual message bodies.
Non textual message bodies 
Message bodies that are multipart 
Non ASCII character textual header information
Code Example:
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(args[0])};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Hello");
msg.setSentDate(new Date());
msg.setText("Mail Message");

The JavaMail API requires JDK/JRE 1.4 or higher. The JavaMail API is a Java optional package, it is not part of the core Java SE but is included in Java EE.

The JavaMail Authenticator is found in the javax.mail package, and used as an authenticator to access protected resources by prompting the user for username and password.

  • Properties props = new Properties();
  • Authenticator auth = new MyAuthenticator();
  • Session session = Session.getDefaultInstance(props, auth);