TODAY JAVA SCHOOL

In java school, programming, design, computer general knowledge, web application, software, web services, social media, digital marketing, oops, concept of programming language, oops feature, console media, graphics medium, first programming, c, c ++ , Java, PHP, SQL, MySQL, HTML, HTML_5, J_query, JavaScript, Bootstrap, Framework, images with logos, examples, shared and explained.

https://www.amazon.in/b?node=26373545031&linkCode=ll2&tag=1234567801cdb-21&linkId=3b9882431b00409b44141e0344b35a15&language=en_IN&ref_=as_li_ss_tl

Breaking

Monday, 27 April 2020

Sending Email In Java

Sending Email in Java

There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.

You can use one of the following techniques to get the SMTP server:

  • Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc. (or)
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javatpoint.com (or)
  • Use the SMTP Server provided by other companies e.g. gmail etc.
Here, we are going to learn above three approaches to send email using javamail API. But we should learn the basic steps to send email from java application.

download image of sending e mail in java

Fig: Sending Email In Java 

               Steps to send email using JavaMail API

There are following three steps to send email using JavaMail. They are as follows:
1.    Get the session object that stores all the information of host like host name, username, password etc.
2.    compose the message
3.    send the message


1) Get the session object


The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use any method to get the session object.


Example of getInstance() method

  
      Properties properties=new Properties();  
      //fill all the information like host name etc.  
    Session session=Session.getInstance(properties,null);  


2) Compose the message


The javax.mail.Message class provides methods to compose the message.
But it is an abstract class so its subclass javax.mail.internet.
MimeMessage class is mostly used.
To create the message, you need to pass session object in MimeMessage
 class constructor. 

For Example:

MimeMessage message=new MimeMessage(session);

3) Send the message


The javax.mail.Transport class provides method to send the message.


Example to send the message:

Transport.send(message);

Simple example of sending email in Java

To send email by SMTP server installed on the machine e.g. Postcast 
server, Apache James server, Cmail server etc.


For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

No comments:

Post a Comment