Sending a mail using Java Code.

Java Mail API provides the collection of classes and interfaces which models sending of mail.

For working with Java Mail we require two jar files to be set in classpath or imported in some IDE.


You can download both the jar files from above provided links.
In case you are new to setting class path you can check out with the following video.

Java Mail API consists of some very important classes and interfaces.
We will cover at least those required for sending a mail.

All the classes and interfaces required to work with Java Mail API are in package

1. javax.mail
Classes here models the mail system.

2. javax.mail.internet
Classes here are specific to internet mailing systems,


-Session class represents the session acquired with the mail account.
For getting this session all the required properties as well as authentications have to be passed.

public static Session getDefaultInstance(Properties prop, Authenicator auth)

getDefaultInstance() is the static method used of session to acquire the session with the mail account.

It requires the Properties object filled as well as an Authenticator object.

Let us have a look how to fill up that Properties objet.

Properties props=new Properties();
  1. props.put("mail.smtp.auth", "true");
  2. props.put("mail.smtp.socketFactory.port", "465");
  3. props.put("mail.smtp.host","smtp.gmail.com");
  4. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  5. props.put("mail.smtp.socketFactory.fallback", "false");
mail.smtp.auth: Attempts to authenticate the user with AUTH command.

mail.smtp.socketFactory.port: Specifies the port to connect when using specified socket factory . If not set default port will be used which is 25.

mail.smtp.host: Determines the SMTP server where we need to connect to.

mail.smtp.socketFactory.class: If set, specifies the name of the class that implements the javax.net.SocketFactory interface.

mail.smtp.socketFactory.fallback: If set to true, failure to create a socket using the specified socket factory, will cause socket to be created using java.net.Socket class.
Once properties is created Authenticator object is required to be made.
Authenticator is an abstract class, it requires to be sub classed to be used.
Authenticator auth=new SMTPAuthenticator();
public class SMTPAuthenticator extends Authenticator
public PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(email,password);
Now let us see how session object is created.
Session session=Session.getDefaultInstance(props,auth);
Once session is acquired we need to create a MimeMessage to be sent. 


- MimeMessage represents the Mime(MultiPurpose Internet Mailing Extension) style message.
MimeMessage(Session session)
- Constructs an empty message to be sent on this session.

Important Methods
public void setSubject(String subject)
- Sets the subject for this message.
public void setFrom(Address address)
- Sets the address from where the message is originated.
public void setContent(Object o, String type)
- This is a convenience method for setting the content of the message. Type has to be specified for the message and it should be the one which is available to Java Mail Implementation.
Used when we need to send HTML Mails.
public void setContent(MultiPart multipart)
- Sends a message which is of multipart. Used to send mails with attachment.
public void addRecipient(Message.RecipientType type, Address address)
- Adds the recipient for this message.
Type of recipient can be
Message.RecipientType.CC-- Carbon Copy
Message.RecipientType.BCC-- Blind Carbon Copy

MimeMessage msg = new MimeMessage(session);
msg.setSubject("My first mail");
msg.setText("This is message body");
msg.setFrom(new InternetAddress("youremail@gmail.com"));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress("someone@gmail.com"));

Once set we need to send the message using Transport object


- Abstract class that models message transport.
- Sub class provides actual implementation
public static void send(Message msg)
- Sends message.
Here is the full code to send a normal text mail;
Please change the email ids and passwords for its proper working.

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

public class SendMail
 String myEmail,myPassword;
  myEmail = "youremail@gmail.com";
  String host="smtp.gmail.com";
  String port="465";
  String recAdd="someone@gmail.com";

  Properties prop = new Properties();

  SecurityManager manager=System.getSecurityManager();

   Authenticator auth= new SMTPAuthenticator();
   Session session =Session.getDefaultInstance(prop,auth);
            System.out.println("Session Acquired");
   MimeMessage msg = new MimeMessage(session);
   msg.setSubject("My first mail");
   msg.setFrom(new InternetAddress(myEmail));
   msg.setText("This is message body");
   msg.setRecipient(Message.RecipientType.TO,new InternetAddress(recAdd));
    System.out.println("Message ready ");
     System.out.println("Mail Sent");
  catch (Exception e)
 public static void main(String[] args) 
  new SendMail();
 private class SMTPAuthenticator extends Authenticator
  public PasswordAuthentication getPasswordAuthentication()
   return new PasswordAuthentication(myEmail,myPassword);


Post a Comment