Java Mail Interview Questions and Answers
Experienced / Expert level questions & answers
Ques 1. Explain POP, SMTP and IMAP protocols.
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.
SMTP: Simple Mail Transfer 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.
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 transmitting the email messages. For Example Gmail server uses to transmit 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.
Ques 2. Explain the use of MIME within message makeup.
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");
This section creates the actual message object and fills in the to, from, subject, date and content. There are also options to set the reply to, content and content type, and other header information. Since this is a MIME - Multipurpose Internet Mail Extensions - message, it need not be plain text.
A DataHandler can be set using setDataHandler() in MimeMessage to handle nontext parts. This is a simple one-part text message, the setText() can be used.
Ques 3. Sample code for java mail api with attachment.
String SMTP_HOST_NAME = "mail.domain.com";
String SMTP_PORT = "25";
String SMTP_FROM_ADDRESS="xxx@domain.com";
String SMTP_TO_ADDRESS="yyy@domain.com";
String subject="Textmsg";
String fileAttachment = "C:\filename.pdf";
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT );
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{protected javax.mail.PasswordAuthentication
getPasswordAuthentication()
{return new javax.mail.PasswordAuthentication("xxxx@domain.com","password");}});
try{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SMTP_FROM_ADDRESS));
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Test mail one");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SMTP_TO_ADDRESS));
msg.setSubject(subject);
// msg.setContent(content, "text/plain");
Transport.send(msg);
System.out.println("success....................................");
}
catch(Exception e){
e.printStackTrace();
}
Ques 4. Sample code for Reading message using Java Mail.
The Folder class declares methods that fetch, append, copy and delete messages. These are some of the methods used in the program.
System.getProperties() this method get the system properties.
Session.getDefaultInstance(properties) this method get the default Session object.
session.getStore("pop3") this method get a Store object that implements the pop3 protocol.
store.connect(host, user, password) Connect to the current host using the specified username and password.
store.getFolder("inbox") create a Folder object of the inbox.
folder.open(Folder.READ_ONLY) open the Folder.
folder.getMessages() get all messages for the folder.
import java.io.*;
import java.util.*;
import javax.mail.*;
public class ReadMail {
public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String user = "test";
String password = "test";
// 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_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
}
Ques 5. Sample code for Reading Multipart mail using JavaMail.
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();
}
}
Ques 6. Sample code for reading attachment message using JavaMail.
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();
}
}
Ques 7. Sample code for replying to messages using JavaMail.
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");Transport.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 ans = reader.readLine();
if ("Y".equals(ans) || "y".equals(ans)) {
// 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
Transport.send(reply);
} else if ("n".equals(ans)) {
break;
}
}
} else {
System.out.println("There is no msg....");
}
}
}
Ques 8. Sample code for Forwarding Messages using JavaMail.
If u want forward a message to another user firstly get all header field and get message content then send its for another user.
Java code given below gives the functionality to forward same message to the next email address. With this code user can change Subject line and can edit the message content that is going to forward.
package com.withoutbook.common;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class ForwardMail {
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();
properties.setProperty("mail.smtp.host", "192.168.10.110");
// 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_ONLY);
Message message = folder.getMessage(1);
// Here's the big change...
String from = InternetAddress.toString(message.getFrom());
if (from != null) {
System.out.println("From: " + from);
}
String replyTo = InternetAddress.toString(
message.getReplyTo());
if (replyTo != null) {
System.out.println("Reply-to: " + replyTo);
}
String to = InternetAddress.toString(
message.getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}
String subject = message.getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Date sent = message.getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}
System.out.println(message.getContent());
// Create the message to forward
Message forward = new MimeMessage(session);
// Fill in header
forward.setSubject("Fwd: " + message.getSubject());
forward.setFrom(new InternetAddress(from));
forward.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Oiginal message:nn");
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message.getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
// Send message
Transport.send(forward);
System.out.println("msg forward ....");
}
}
Ques 9. How to show all header information of message using Java Mail api?
We will use method given below to retrieve all header information, this method returns Enumerations type.
public Enumeration getAllHeaders();
package com.withoutbook.common;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class AllHeaderClient {
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_ONLY);
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// Here's the difference...
Enumeration headers = messages[i].getAllHeaders();
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
System.out.println(h.getName() + ": " + h.getValue());
}
System.out.println();
}
}
}
Ques 10. Sample code for deleting messages using JavaMail.
If you want to delete any message then set the message flag delete. There are different types of flags, some system-defined and some user-defined.
* Flags.Flag.ANSWERED* Flags.Flag.DELETED* Flags.Flag.DRAFT* Flags.Flag.FLAGGED* Flags.Flag.RECENT* Flags.Flag.SEEN* Flags.Flag.USERTo delete messages, you set the message's DELETED flag:message.setFlag(Flags.Flag.DELETED, true);Open up the folder in READ_WRITE mode first though:folder.open(Folder.READ_WRITE);Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages.
folder.close(true);
package com.withoutbook.common;
import com.sun.mail.imap.protocol.FLAGS;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
public class DeleteMail {
public static void main(String args[]) throws Exception {
Properties properties = System.getProperties();
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_WRITE);
Message[] msg = folder.getMessages();
//System.out.println((messages.length+1)+" message found");
for (int i = 0; i < msg.length; i++) {
System.out.println("--------- " + (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("Message : ");
System.out.println(msg[i].getContent());
}
System.out.println("Enter message no to delete :");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String no = br.readLine();
msg[Integer.parseInt(no) - 1].setFlag(FLAGS.Flag.DELETED, true);
System.out.println("Msg Delete .....");
folder.close(true);
store.close();
}
}
Ques 11. Sample code to send HTML mail with images using JavaMail.
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 Transport.send() method.
The Transport class models the transport agent that routes a message to its destination addresses. This class provides methods that send a message to a list of recipients. Invoking the Transport.send() method with a Message object identifies the appropriate transport 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 {
String 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
Transport.send(message);
System.out.println("Message Send.....");
}
}
Most helpful rated by users:
- What is JavaMail?
- Explain POP, SMTP and IMAP protocols.
- Discuss about JavaMail.
- Explain the structure of Javamail API
- What are the advantages of JavaMail?