Sending Email in Java

Sending Email in Java

In this guide we will discuss about 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.adglob.in (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.

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.

Method of Session class

No.MethodDescription
1public static Session getDefaultInstance(Properties props)returns the default session.
2public static Session getDefaultInstance(Properties props,Authenticator auth)returns the default session.
3public static Session getInstance(Properties props)returns the new session.
4public 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 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);  

Now message object has been created but to store information in this object MimeMessage class provides many methods. Let’s see methods provided by the MimeMessage class:

Commonly used methods of MimeMessage class

No.MethodDescription
1public void setFrom(Address address)is used to set the from header field.
2public void addRecipient(Message.RecipientType type, Address address)is used to add the given address to the recipient type.
3public void addRecipients(Message.RecipientType type, Address[] addresses)is used to add the given addresses to the recipient type.
4public void setSubject(String subject)is used to set the subject header field.
5public void setText(String textmessage)is used to set the text as the message content using text/plain MIME type.
6public void setContent(Object msg, String contentType)is used to set the content as the message content using given MIME type.

Example to compose the message:

MimeMessage message=new MimeMessage(session);  
message.setFrom(new InternetAddress("sonoojaiswal@sssit.org"));  
message.addRecipient(Message.RecipientType.To,   
new InternetAddress("sonoojaiswal@adglob.in"));  
message.setHeader("Hi, everyone");  
message.setText("Hi, This mail is to inform you...");  

3) Send the message

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

Commonly used methods of Transport class

No.MethodDescription
1public static void send(Message message)is used send the message.
2public static void send(Message message, Address[] address)is used send the message to the given addresses.

Example to send the message:

Transport.send(message);  

Simple example of sending email in Java

In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one.

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

  • mail.jar
  • activation.jar

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 = "sonoojaiswal1988@gmail.com";//change accordingly  
      String from = "sonoojaiswal1987@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();}  
   }  
}  

This Example to send Email

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
 public static void main(String [] args){
      String to = "sonoojaiswal1988@gmail.com";//change accordingly
      String from = "sonoojaiswal1987@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 example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one.

To run this example, you need to load two jar files. There are 4 ways to load the jar file. One of the way is set classpath. Let’s see how to run this example:

Load the jar filec:\> set classpath=mail.jar;activation.jar;.;
compile the source filec:\> javac SendEmail.java
run byc:\> java SendEmail

Example of sending email in Java through SMTP server provided by the host provider

If you are using the SMTP server provided by the host provider e.g. mail.adglob.in , you need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.

If you are sending the email using JavaMail API, load the two jar files:

  • mail.jar
  • activation.jar
import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;  
  
public class SendMailBySite {  
 public static void main(String[] args) {  
  
  String host="mail.adglob.in";  
  final String user="sonoojaiswal@adglob.in";//change accordingly  
  final String password="xxxxx";//change accordingly  
    
  String to="sonoojaiswal1987@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("adglob");  
     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();}  
 }  
}  

This Example to Send Email

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class SendMailBySite {
 public static void main(String[] args) {

  String host="mail.adglob.in";
  final String user="sonoojaiswal@adglob.in";//change accordingly
  final String password="xxxxx";//change accordingly
  
  String to="sonoojaiswal1987@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("adglob");
     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 you can see in the above example, userid and password need to be authenticated. As this program illustrates, you can send email easily. Change the username and password accordingly. Let’s see how to run it once again by simple technique:

Load the jar filec:\> set classpath=mail.jar;activation.jar;.;
compile the source filec:\> javac SendMailBySite.java
run byc:\> java SendMailBySite

Next Topic : Click Here

This Post Has 2 Comments

  1. jelajahi situs web ini

    Spot on with this write-up, I actually believe this amazing site needs far more attention. I’ll probably be returning to see more, thanks for the information.

Leave a Reply