Java Mail Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is JavaMail?
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.
Ques 2. 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 3. Explain the use of MIME within message makeup.
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-Transfer-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 transported 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");
Ques 4. Explain the structure of Javamail API
The JavaMail API has classes such as Message, Store and Transport. 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 Activation Framework.
Ques 5. Discuss about JavaMail.
1) JavaMail is a set of abstract classes that create a framework for sending, receiving and handling e-mail.
2) The package that Sun provides contains implementations of IMAP and SMTP, which allow sending and receiving mail.
3) The framework eases the creation of cross-platform mail application without an in-depth knowledge of e-mail.
4) There are methods and classes that allow access to mail folders, download messages, send messages with attachments and filter mail.
Ques 6. What are the advantages of JavaMail?
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.
Ques 7. Sample code to send email from you java application.
You can use the JavaMail API to send emails from your Java application. Though the JavaMail API allows you to do many things including the ability to retrieve and read the emails or sending emails etc, this sample java program demonstrates how to send email from your Java application. Remember to change the email host (String host) to your email server host, otherwise it won't work.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail {
public static void main(String[] args) {
// Collect the necessary information to send a simple message
// Make sure to replace the values for host, to, and from with
// valid information.
// host - must be a valid smtp server that you currently have
// access to.
// to - whoever is going to get your email
// from - whoever you want to be. Just remember that many smtp
// servers will validate the domain of the from address
// before allowing the mail to be sent.
String host = "server.myhost.com";
String to = "YourFriend@someemail.com";
String from = "Me@myhost.com";
String subject = "My First Email";
String messageText = "I am sending a message using the"
+ " JavaMail API.n"
+ "Here type your message.";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try {
// Instantiate a new MimeMessage and fill it with the
// required information.
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
// Hand the message to the default transport service
// for delivery.
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Ques 8. Sample code to send email using GMAIL SMTP.
Here are two examples to show you how to use JavaMail API method to send an email via Gmail SMTP server, using both TLS and SSL connection.
To run this example, you need two dependency libraries – javaee.jar and mail.jar, both are bundle in JavaEE SDK.
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
GMail SMTP detail here – http://mail.google.com/support/bin/answer.py?hl=en&answer=13287
Send an Email via Gmail SMTP server using TLS connection:
package com.withoutbook.common;
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 SendMailTLS {
public static void main(String[] args) {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "nn No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Send an Email via Gmail SMTP server using SSL connection:
package com.withoutbook.common;
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 SendMailSSL {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@no-spam.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@no-spam.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"nn No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Exception like:
java.net.UnknownHostException: smtp.gmail.com
Some hit the UnknownHostException: smtp.gmail.com, try ping smtp.gmail.com and make sure you got a response (able to access). Often times, your connection may block by your firewall or proxy behind.
Ques 9. What is Session in JavaMail api?
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);
Ques 10. What is Message in JavaMail api?
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.
Ques 11. What is Address in JavaMail api?
Now we will define address, 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:
1. Message.RecipientType.TO: primary recipient
2. Message.RecipientType.CC: carbon copy
3. Message.RecipientType.BCC: blind carbon copy
Ques 12. What is Authenticator in JavaMail api?
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);
Ques 13. What is Transport in JavaMail api?
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.
Transport.send(message);
Or can create a specific instance from the session for defined protocol.
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Ques 14. What is Store and Folder in JavaMail api?
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();
Ques 15. Sample code for sending multipart mail using JavaMail.
Multipart is like a container that holds one or more body parts. When u send a multipart mail firstly create a Multipart class object and then create BodyPart class object, set text in BodyPart class object and add all BodyPart class object in Multipart class object and send the message. Class Multipart that we will use in this code is an abstract class. Method used in this program of Multipart class is:
void addBodyPart(BodyPart part);
This method is used to add parts in multipart.
package com.withoutbook.common;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMultipartMail {
public static void main(String args[]) throws Exception {
String host = "192.168.10.110";
String from = "test@localhost";
String to = "arindam@localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("MultiPart Mail");
Multipart multipart = new MimeMultipart();
BodyPart part1 = new MimeBodyPart();
part1.setText("This is multipart mail and you read part1......");
BodyPart part2 = new MimeBodyPart();
part2.setText("This is multipart mail and you read part2......");
multipart.addBodyPart(part1);
multipart.addBodyPart(part2);
msg.setContent(multipart);
Transport.send(msg);
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?