Sending Email using JavaMail API

There are different approaches to send email utilizing JavaMail API. For this reason, you must have SMTP server that is capable to send mails.

You can utilize one of the accompanying procedures to get the SMTP server:

  1. Install and utilize any SMTP server, for example, Postcast server, Apache James server, cmail server and so forth (or)
  2. Utilize the SMTP server gave by the host supplier e.g. my SMTP server is mail.javatportal.com (or)
  3. Utilize the SMTP Server gave by different organizations e.g. gmail and so on.

Here, we are going to learn above three ways to deal with send email utilizing javamail API. However, we ought to take in the fundamental strides to send email from java application.

Ventures to send email utilizing JavaMail API

There are taking after three stages to send email utilizing JavaMail. They are as per the following:

  1. Get the session question that stores all the data of host like host name, username, secret key and so forth.
  2. make the message
  3. send the message

1. Get the session object

The javax.mail.Session class gives two systems to get the object of session, Session.getDefaultInstance() strategy and Session.getInstance() technique. You can utilize any technique to get the session object.

No. Method Description
1 public static Session getDefaultInstance(Properties props) returns the default session.
2 public static Session getDefaultInstance(Properties props,Authenticator auth) returns the default session.
3 public static Session getInstance(Properties props) returns the new session.
4 public static Session getInstance(Properties props,Authenticator auth) returns the new session.

Example of getDefaultInstance() method

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

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 gives routines to make the message. In any case, it is a unique class so its subclass javax.mail.internet.MimeMessage class is generally utilized.

MimeMessage message=new MimeMessage(session);

To make the message, you have to pass session object in MimeMessage class constructor. For instance:

Ordinarily utilized systems for MimeMessage class

No. Method Description
1 public void setFrom(Address address) is used to set the from header field.
2 public void addRecipient(Message.RecipientType type, Address address) is used to add the offered location to the beneficiary sort.
3 public void addRecipients(Message.RecipientType type, Address[] addresses) is used to add the offered locations to the beneficiary sort.
4 public void setSubject(String subject) is used to set the subject header field.
5 public void setText(String textmessage) is used to set the content as the message substance utilizing content/plain MIME sort.
6 public void setContent(Object msg, String contentType) is used to set the substance as the message substance utilizing given MIME sort.

Example to compose the message:

MimeMessage message=new MimeMessage(session);  
message.setFrom(new InternetAddress("mithilesh@javatportal.com"));  
message.addRecipient(Message.RecipientType.To,   
new InternetAddress("support@javatportal.com"));  
message.setHeader("Hi, Team");  
message.setText("Hi, This mail is to inform you all test..."); 

Send the message

The javax.mail.Transport class gives technique to send the message.

Regularly utilized strategies for Transport class

No. Method Description
1 public static void send(Message message) is utilized send the message.
2 public static void send(Message message, Address[] address) is utilized send the message to the given locations.

Sample to send the message:

Transport.send(message); 

Basic case of sending email utilizing JavaMail API

In this case, we are going to figure out how to send email by SMTP server introduced on the machine e.g. Postcast server, Apache James server, Cmail server and so forth. In the event that you need to send email by utilizing your SMTP server gave by the host supplier, see the illustration after this one.

For sending the email utilizing JavaMail API, you have to stack the two container records:

  • mail.jar
  • activation.jar

download these jar files go to the Oracle site to download the latest version.

					
import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
  
public class SendEmail  
{  
 public static void main(String [] args){  
      String to = "mithileshkushwaha@gmail.com";//change accordingly  
      String from = "mithileshgniit@gmail.com";change accordingly  
      String host = "localhost";//or IP address  
  
     //Get the session object  
      Properties properties = System.getProperties();  
      properties.setProperty("mail.smtp.host", host);  
      Session session = Session.getDefaultInstance(properties);  
  
     //compose the message  
      try{  
         MimeMessage message = new MimeMessage(session);  
         message.setFrom(new InternetAddress(from));  
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
         message.setSubject("Ping");  
         message.setText("Hello, this is example of sending email  ");  
  
         // Send message  
         Transport.send(message);  
         System.out.println("message sent successfully....");  
  
      }catch (MessagingException mex) {mex.printStackTrace();}  
   }  
}  

In this case, we are going to figure out how to send email by SMTP server introduced on the machine e.g. Postcast server, Apache James server, Cmail server and so on. On the off chance that you need to send email by utilizing your SMTP server gave by the host supplier, see the illustration after this one.

To run this sample, you have to load two container documents. There are 4 approaches to stack the jug record. One of the way is set classpath. How about we perceive how to run this sample:

Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac SendEmail.java
run by c:\> java SendEmail

Illustration of sending email utilizing JavaMail API through the SMTP server gave by the host supplier

On the off chance that you are utilizing the SMTP server gave by the host supplier e.g. mail.javatportal.com , you have to verify the username and secret word. The javax.mail.PasswordAuthentication class is utilized to confirm the secret word.

On the off chance that you are sending the email utilizing JavaMail API, stack the two container documents:

																			
import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;  
  
public class SendMailBySite {  
 public static void main(String[] args) {  
  
  String host="mail.javatportal.com";  
  final String user="mithileshgniit@javatportal.com";//change accordingly  
  final String password="*****";//change accordingly  
    
  String to="mithileshgniit@gmail.com";//change accordingly  
  
   //Get the session object  
   Properties props = new Properties();  
   props.put("mail.smtp.host",host);  
   props.put("mail.smtp.auth", "true");  
     
   Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {  
      protected PasswordAuthentication getPasswordAuthentication() {  
    return new PasswordAuthentication(user,password);  
      }  
    });  
  
   //Compose the message  
    try {  
     MimeMessage message = new MimeMessage(session);  
     message.setFrom(new InternetAddress(user));  
     message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
     message.setSubject("javatportal");  
     message.setText("This is simple program of sending email using JavaMail API");  
       
    //send the message  
     Transport.send(message);  
  
     System.out.println("message sent successfully...");  
   
     } catch (MessagingException e) {e.printStackTrace();}  
 }  
}  

As should be obvious in the above sample, userid and secret key should be verified. As this system outlines, you can send email effectively. Change the username and secret word appropriately. How about we perceive how to run it at the end of the day by basic strategy:

Load the jar file c:\> set classpath=mail.jar;activation.jar;.;
compile the source file c:\> javac SendMailBySite.java
run by c:\> java SendMailBySite