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. 2.Protocols used in JavaMail API?There are some protocols that are used in JavaMail API.
SMTP is an acronym for Simple Mail Transfer 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 POP3. 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 transfer 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 Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc. 3.JavaMail ArchitectureThe 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. Let's understand it with the figure given below: 4.JavaMail API Core Classes?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:
5.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. 6.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;
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.name="waterfall.gif" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="waterfall.gif" [Author the encoded content here] .. 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"); 7.Discuss about JavaMail?
8.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. 9.Explain the use of MIME within message makeup?
Message msg = new MimeMessage(session);
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.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"); 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. 10.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. 11.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. 12.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(); } } } 13.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(); } 14.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
Exception like: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," + "\n\n 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," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } } 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. 15.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… 16.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); 17.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. 18.What is Address in JavaMail api?
19.Now we will define address, Address class is also an abstract class so we will use here class javax.mail.internet.InternetAddress.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 20.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); |