Top 25 Javamail Api Interview Questions
Q1. Sample Code For Reading Attachment Message Using Javamail?
Java Mail API offers training to send a couple of Mime body element with one Mime Message. MulipltMimeBody elements may be text, record or photo. All message are saved in Folder objects. Folders can contain folders or messages. The Folder magnificence pronounces strategies that fetch, append, replica and delete messages, and message contain Attachment.
Package deal com.Withoutbook.Common;
import java.Io.*;
import java.Util.*;
import javax.Mail.*;
public elegance ReadAttachment
public static void predominant(String args[]) throws Exception
String host = "192.168.10.One hundred ten";
String person = "arindam";
String password = "arindam";
// Get gadget properties
Properties residences = System.GetProperties();
// Get the default Session object.
Session session = Session.GetDefaultInstance(residences);
// Get a Store object that implements the desired protocol.
Store store = session.GetStore("pop3");
//Connect to the cutting-edge host the usage of the desired username and password.
Shop.Connect(host, person, password);
//Create a Folder item similar to the given name.
Folder folder = shop.GetFolder("inbox");
// Open the Folder.
Folder.Open(Folder.READ_WRITE);
Message[] message = folder.GetMessages();
for (int a = zero; a < message.Period; 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 circulate = bodyPart.GetInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(circulation));
while (br.Geared up())
System.Out.Println(br.ReadLine());
System.Out.Println();
System.Out.Println();
folder.Close(true);
shop.Near();
Q2. Sample Code For Replying To Messages Using Javamail?
The Message elegance have a respond() technique to configure a new Message with the right recipient and situation, including "Re: " if no longer already there. This does now not upload any content material to the message, reply() method have a boolean parameter indicating whether or not to answer to handiest the sender (false) or respond to all (real).
MimeMessage reply = (MimeMessage)message.Reply(fake);reply.SetFrom(new InternetAddress("president@whitehouse.Gov"));respond.SetText("Thanks");Trport.Ship(respond);
To configure the reply-to cope with whilst sending a message, use the setReplyTo() technique.
Bundle com.Withoutbook.Commonplace;
import java.Io.*;
import java.Util.*;
import javax.Mail.*;
import javax.Mail.Internet.*;
public class ReplyMail
public static void essential(String args[]) throws Exception
Date date = null;
Properties residences = System.GetProperties();
homes.SetProperty("mail.Smtp.Host", "192.168.10.One hundred ten");
Session session = Session.GetDefaultInstance(houses);
Store store = session.GetStore("pop3");
keep.Join("192.168.10.110", "arindam", "arindam");
Folder folder = keep.GetFolder("inbox");
if (!Folder.Exists())
System.Out.Println("inbox now not observed");
System.Exit(0);
folder.Open(Folder.READ_ONLY);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.In));
Message[] message = folder.GetMessages();
if (message.Duration != zero)
System.Out.Println("no. From ttSubject ttDate");
for (int i = zero, 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()
// 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 material
respond.SetText(buffer.ToString());
// Send the message
Trport.Ship(reply);
else if ("n".Equals())
ruin;
else
System.Out.Println("There isn't any msg....");
Q3. What Is Message In Javamail Api?
After growing consultation object, create message to ship with the aid of the usage of Message elegance. Because of message magnificence is abstract elegance so we will use subclass javax.Mail.Internet.MimeMessage.
MimeMessage message = new MimeMessage(session)
// set the content of message by means of setContent() method
message.SetContent(“www.Roseindia.Internet”, "text/plain");
We can also use setText() technique to set the content.
Message.SetText("www.Roseindia.Net");
To create issue line of sending message use setSubject() approach.
Q4. Explain Imap?
IMAP: Short for Internet Message Access Protocol. This is every other maximum popular protocol of net general for e-mail utilization other than POP. Usually all of the modern-day e-mail server and client supports those protocols for trmitting the email messages. For Example Gmail server makes use of to trmit the message to a purchaser which includes Mozilla Thunderbird and Microsoft Outlook.
IMAP is an application layer protocol over internet that is running from port no. 143 that lets in the accessibility of e-mail on a remote server by using a patron. IMAP supports the web and offline (disconnected) modes of operations. Usually the e-mail customers the use of IMAP makes use of the ability of leaving the message on the server. The message lasts until the user explicitly deletes them. IMAP additionally lets in a couple of clients to have the accessibility of the identical mailbox.
Q5. Do The Javamail Apis Work In Web Browsers?
JavaMail will work in any browser that supports the specified JDK version. The Java Plug-in may be required to offer such help.
Q6. Which Protocols Are Used In Javamail Api?
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 gives a mechanism to deliver the email. We can use Apache James server, Postcast server, cmail server and so on. As an SMTP server. But if we buy the host space, an SMTP server is bydefault supplied by using the host company. For instance, my smtp server is mail.Javatpoint.Com. If we use the SMTP server supplied by means of the host issuer, authentication is needed for sending and receiving emails.
POP : POP is an acronym for Post Office Protocol, additionally referred to as POP@It offers a mechanism to acquire the email. It affords support for single mail container for each person. We can use Apache James server, cmail server and so on. As an POP server. But if we buy the host space, an POP server is bydefault supplied via the host issuer. For example, the pop server supplied by using the host company for my website is mail.Javatpoint.Com. This protocol is defined in RFC 1939.
IMAP : IMAP is an acronym for Internet Message Access Protocol. IMAP is a complicated protocol for receiving messages. It offers support for a couple of mail field for every consumer ,further to, mailbox can be shared by way of a couple of customers. It is described in RFC 2060.
MIME : Multiple Internet Mail Extension (MIME) tells the browser what's being despatched e.G. Attachment, layout of the messages etc. It isn't called mail trfer protocol however it's miles used by your mail software.
NNTP and Others : There are many protocols that are provided via 1/3-birthday celebration companies. Some of them are Network News Trfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.
Q7. Explain Pop?
POP: The Post Office Protocol is an software-degree protocol within an intranet which might be used by the nearby email clients to send and retrieve e-mails from a far off server those are linked the use of TCP/IP. POP is one of the maximum ordinary protocol fro the usage of e mail. The POP and its techniques support the quit-users with dial-up community connections.
POP allows the customers to retrieve e mail while related and later allows viewing and altering the retrieved messages. This is completed with a promising function – with out staying connected. The system of the usage of emails over POP is to attach, retrieve the messages, and keep them at the user’s PC as a brand new message. Later these messages may be ‘deleted from the server’ and disconnecting the server – makes POP a outstanding protocol.
Q8. What Are The Javamail Api Core Classes?
There are applications which can be utilized in Java Mail API: javax.Mail and javax.Mail.Net package. These applications consists of many lessons for Java Mail API. They are:
javax.Mail.Session class
javax.Mail.Message elegance
javax.Mail.Internet.MimeMessage elegance
javax.Mail.Address magnificence
javax.Mail.Net.InternetAddress elegance
javax.Mail.Authenticator class
javax.Mail.PasswordAuthentication elegance
javax.Mail.Trport elegance
javax.Mail.Store class
javax.Mail.Folder elegance and so on.
Q9. What Are The Advantages Of Javamail?
Potential benefits include - Java mail is used to create non-public mail clear out, easy mailing lists and personal mail programs. Java mail additionally includes the talents to feature the emailing process to an employer utility or even to create a full-fledged e mail patron. Many corporations within the industry have written new e-mail customers the usage of Java Mail.
Q10. What Is Mime?
MIME and RFC822 are the standards for describing electronic mail messages which might be despatched across the Internet. The javax.Mail.Net subpackage (that is part of the JavaMail APIs) affords a whole implementation of these applications. MIME is particular by way of the subsequent RFCs: RFC2045, RFC2046, RFC2047.
Q11. What Is Store And Folder In Javamail Api?
After getting the session you hook up with javax.Mail.Store magnificence with Authenticator or host, port, person and password records. Store object that implements the required protocol may be created by means of by passing the protocol records to the getStore() method of the consultation item.
Store shop = consultation.GetStore("pop3");
save.Join(host, username, password);
After connecting to shop you want to get a folder that holds messages. For POP3, the only folder available is the INBOX but with IMAP, you could have other folders to be had. For this you could use javax.Mail.Folder elegance.
Folder folder = keep.GetFolder("INBOX");
folder.Open(Folder.READ_ONLY);
Message message[] = folder.GetMessages();
Once you have examine messages, you need to shut Store and Folder.
Folder.Close(booleanValue);
shop.Near();
Q12. Sample Code For Reading Multipart Mail Using Javamail?
These days Multipart mail is used to compose emails with attachment. In the email you may connect pics, zip documents, xls, document and so on.. It allows you to create well design emails.
Java Mail API also affords instructions to create, send and study the Multipart message. If you've got given a assignment to create emails with attachment in Java technologies, then you could use the Java Mail api to perform your project.
Using the Multipart Class
Following code snippet shows how you could use the Multipart class. You need to create the item of Multipart class and then you may get the body component and compose or examine your e mail.
Multipart multipart = (Multipart) msg[i].GetContent();After that create BodyPart object BodyPart bodyPart = multipart.GetBodyPart(x);
And then examine bodyPart content the use of getContent() technique.
Package com.Withoutbook.Common;
import java.Util.*;
import javax.Activation.DataHandler;
import javax.Mail.*;
import javax.Mail.Net.*;
public class ReadMultipartMail
public static void principal(String args[]) throws Exception
String host = "192.168.10.110";
String username = "arindam";
String passwoed = "arindam";
Properties residences = System.GetProperties();
Session consultation = Session.GetDefaultInstance(properties);
Store save = session.GetStore("pop3");
keep.Join(host, username, passwoed);
Folder folder = store.GetFolder("inbox");
if (!Folder.Exists())
System.Out.Println("No INBOX...");
System.Exit(zero);
folder.Open(Folder.READ_WRITE);
Message[] msg = folder.GetMessages();
for (int i = zero; 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 challenge = msg[i].GetSubject();
if (concern != null)
System.Out.Println("Subject: " + situation);
Date sent = msg[i].GetSentDate();
if (sent != null)
System.Out.Println("Sent: " + despatched);
System.Out.Println();
System.Out.Println("Message : ");
Multipart multipart = (Multipart) msg[i].GetContent();
for (int x = zero; 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("report name : " + handler.GetName());
else
System.Out.Println(bodyPart.GetContent());
System.Out.Println();
folder.Close(authentic);
save.Close();
Q13. Sample Code To Send Html Mail With Images Using Javamail?
A purchaser create new message by using the usage of Message subclass. It sets attributes like recipient address and the difficulty, and inserts the content material into the Message item, and inserts the content into the Message item. Finally, it sends the Message with the aid of invoking the Trport.Send() approach.
The Trport magnificence models the trport agent that routes a message to its vacation spot addresses. This magnificence provides techniques that send a message to a listing of recipients. Invoking the Trport.Send() approach with a Message item identifies the precise trport based on its vacation spot addresses.
Package com.Withoutbook.Commonplace;
import java.Util.*;
import javax.Mail.*;
import javax.Mail.Internet.*;
public elegance HTMLMail
public static void major(String args[]) throws Exception
Strig host = "192.168.10.One hundred ten";
String from = "arindam@localhost";
String to = "arindam@localhost";
// Get gadget residences
Properties residences = System.GetProperties();
// Setup mail server
houses.SetProperty("mail.Smtp.Host", host);
// Get the default Session item.
Session consultation = Session.GetDefaultInstance(residences);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set the RFC 822 "From" header area the use of the
// fee 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 area.
Message.SetSubject("hello..!");
String htmlText = "
Hello
// Sets the given String as this part's content, // with a MIME form of "text/undeniable".
Message.SetContent(htmlText, "textual content/html");
// Send message
Trport.Send(message);
System.Out.Println("Message Send.....");
Q14. What Is Session In Javamail Api?
Session is the top-degree entry elegance representing mail session. It uses java.Util.Properties item to get records about mail server, username, password and many others. This class has a non-public constructor and you could get consultation gadgets through getInstance() and getDefaultInstance() techniques. GetDefaultInstance() approach presents default Session item which takes Properties and Authenticator objects as arguments.
Properties props = new Properties();
Session consultation = Session.GetDefaultInstance(props, null);
Or create a unique consultation via getInstance() approach…
Properties props = new Properties();
Session consultation = Session.GetInstance(props, null);
Q15. How Do We Store Mail Messages On My Local Disk?
A "nearby store provider" may be used to store mail messages on a nearby disk. The JavaMail API down load does no longer consist of this sort of issuer however a issuer that helps the Unix mbox format is to be had within the JavaMail source repository that you may build your self. See this page for details. In addition, several nearby shop providers are to be had from 1/3 events for different local keep codecs which includes MH and Mbox. See our Third Party Products web page for the modern-day list of such vendors.
Q16. Discuss About Javamail?
JavaMail is a fixed of summary classes that create a framework for sending, receiving and coping with e-mail.
The bundle that Sun provides includes implementations of IMAP and SMTP, which permit sending and receiving mail.
The framework eases the creation of cross-platform mail software without an in-depth expertise of e mail.
There are strategies and instructions that permit get right of entry to to mail folders, download messages, send messages with attachments and clear out mail.
Q17. Explain Smtp?
SMTP: Simple Mail Trfer Protocol, for sending e-mail among ‘servers’. Most of the emailing systems implement the messages over net use SMTP. The message sent from one server to every other server, after which the message can be retrieved through an e-mail patron. The purchaser makes use of either POP or IMAP. In addition to this process, SMTP is also generally used for message sending and retrieval from a mail consumer to a mail server. This is the motive why the need of POP or IMAP server and the SMTP servers on the time of configuring the email software.
Q18. What Is Javamail?
Java Mail is an API that is used to acquire and ship emails between applications. To send the emails, the protocols, SMPT, POP AND IMAP are used. The messages sending and receiving is performed by using creating a framework the use of set of abstract lessons inside the API. The framework permits the software to create customized move-platform mail application by using having basic knowledge of e-mail. There are methods and lessons which can be used to get entry to mail folders, message downloading and sending messages together with attachments characteristic.
Potential benefits consist of - Java mail is used to create non-public mail filter out, easy mailing lists and private mail applications. Java mail also includes the abilties to add the emailing process to an business enterprise software or even to create a full-fledged electronic mail customer. Many companies inside the industry have written new electronic mail customers using Java Mail.
The JavaMail is an API that is used to compose, write and study digital messages (emails).
The JavaMail API presents protocol-impartial and plateform-impartial framework for sending and receiving mails.
The javax.Mail and javax.Mail.Activation packages consists of the center instructions of JavaMail API.
The JavaMail facility can be implemented to many events. It can be used at the time of registering the consumer (sending notification inclusive of thanks for your hobby to my website online), forgot password (sending password to the customers email id), sending notifications for critical updates and so on. So there may be numerous utilization of java mail api.
Q19. Explain Javamail Architecture?
The java software uses JavaMail API to compose, send and receive emails. The JavaMail API uses SPI (Service Provider Interfaces) that gives the intermediatory offerings to the java utility to cope with the exceptional protocols.
Q20. What Is Trport In Javamail Api?
This is final part of sending Email, it's miles an summary class. Default version of this magnificence may be used by calling static send() approach.
Trport.Ship(message);
Or can create a selected instance from the consultation for defined protocol.
Message.SaveChanges();
Trport trport = session.GetTrport("smtp");
trport.Connect(host, username, password);
trport.SendMessage(message, message.GetAllRecipients());
trport.Near();
Q21. What Is Address In Javamail Api?
Address class is likewise an abstract class so we will use here class javax.Mail.Net.InternetAddress.
Address cope with = new InternetAddress("arindam@withoutbook.Com");
To show a name next to the Email Address use one greater argument for call.
Address address = new InternetAddress("arindam@withoutbook.Com", "Arindam");
After developing deal with connect with message with the aid of ways:
1: By setFrom()technique: message.SetFrom(address);
1: By setReplyTo()technique: When want to send reply to more addresses.
Address deal with[] = ...;
Message.SetReplyTo(deal with[]);
To perceive the recipient, add the recipients by using addRecipient() method….
Message.AddRecipient(type, deal with);
Address sorts are of 3 sorts:
Message.RecipientType.TO: primary recipient
Message.RecipientType.CC: carbon replica
Message.RecipientType.BCC: blind carbon reproduction
Q22. Explain The Structure Of Javamail Api?
The JavaMail API has training such as Message, Store and Trport. The API may be used to subclass for imparting new protocols and some additional capability when wished. The concrete subclasses of this API are MimeMessage and MimeBodyPart which are applied widely by way of 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 proclaims the lessons, interfaces and summary strategies which can be meant for helping the mail capabilities which all mailing structures helps. Intranet Implementation Layer: The implementation of MIME net standards and part of the summary layer comprises this deposit. Java Bean Activation Framework: The encapsulation of message statistics and managing the facts interacting instructions is utilized by the Javabean
Q23. Explain The Use Of Mime Within Message Makeup?
MIME message consists of the image stored as record in GIF layout and the GIF layout makes use of eight-bit layout. The RFC 822 makes use of ASCII text layout. The messages in the shape of ASCII textual content format is to be encoded. To show the picture within the recipient device, the information abut the encoding mechanism is used. The message is to be made up within the recipient’s application. The following snippet is used to perceive the content is a GIF report that's to be encoded the usage of the standard “base64Algorithm. This is to be dealt with as an attachment by the consumer who uses the email.
Content-Type: picture/gif;
name="waterfall.Gif"
Content-Trfer-Encoding: base64
Content-Disposition: attachment;
filename="waterfall.Gif"
[Author the encoded content here]
..
The accomplishment of that is finished via simplifying and rebuilding of complex files. These documents are encoded and trported as a frame of the message or a sequence of messages which can be the components of the document.A message layout is defined with the aid of the MIME that lets in the subsequent:
Non ASCII person textual message bodies.
Non textual message our bodies
Message bodies that are multipart
Non ASCII man or woman 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, deal with);
msg.SetSubject("Hello");
msg.SetSentDate(new Date());
msg.SetText("Mail Message");
Q24. What Jdk Does The Javamail Api Need?
The JavaMail API calls for JDK/JRE 1.Four or higher. The JavaMail API is a Java optionally available package, it isn't always a part of the center Java SE however is protected in Java EE.
Q25. What Is Authenticator In Javamail Api?
The JavaMail Authenticator is determined inside the javax.Mail package, and used as an authenticator to get entry to blanketed assets by using prompting the person for username and password.
Properties props = new Properties();
Authenticator auth = new MyAuthenticator();
Session session = Session.GetDefaultInstance(props, auth);

