The JavaMail API defines classes that represent the components of a mail system. JavaMail does not implement an email server, instead, it allows you to access an email server using a Java API. In order to test the code presented, you must have access to an email server. While the JavaMail API specification does not mandate support for specific protocols, JavaMail typically includes support for POP3, IMAP, and SMTP.
Â
How does Email Work?
Prerequisite:Â
Â
- Have access to an SMTP server. You must know the hostname, port number, and security settings for your SMTP server. Webmail providers may offer SMTP access, view your email account settings or help to find further information. Be aware that your username is often your full email address and not just the name that comes before the @ symbol.Â
 - A Java EE IDE and Application Servers such as GlassFish or Oracle WebLogic Server. JavaMail can be downloaded as a library in a Java SE application but this tutorial assumes the use of a Java EE application server which would already include JavaMail.
There are the following three steps to send email using JavaMail. They are as follows:Â
Â
Get the session object – javax.mail.Session class provides object of session, Session.getDefaultInstance() method and Session.getInstance() method.
Â
// Setup mail server properties.setProperty("mail.smtp.host", host); // mail username and password properties.setProperty("mail.user", "user"); properties.setProperty("mail.password", "password$$");
Compose the message– javax.mail.Transport class provides method to send the message.Â
Â
// javax.mail.internet.MimeMessage class is // mostly used for abstraction. MimeMessage message = new MimeMessage(session); // header field of the header. message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("subject"); message.setText("Hello, aas is sending email ");
Send the message
Transport.send(message);
Following is the Send Mail in Java using SMTP without authentication full implementation in java-
Â
Java
import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; Â
public class SendEmail {          public static void main(String[] args)     {         // change below lines accordingly         String to = "got@gmail.com" ;         String from = "akash@gmail.com" ;         String host = "localhost" ; // or IP address Â
        // Get the session object         // Get system properties         Properties properties = System.getProperties(); Â
        // Setup mail server         properties.setProperty( "mail.smtp.host" , host); Â
        // Get the default Session object         Session session = Session.getDefaultInstance(properties); Â
        // compose the message         try { Â
            // javax.mail.internet.MimeMessage class             // is mostly used for abstraction.             MimeMessage message = new MimeMessage(session); Â
            // header field of the header.             message.setFrom( new InternetAddress(from));             message.addRecipient(Message.RecipientType.TO,                                 new InternetAddress(to));             message.setSubject( "subject" );             message.setText( "Hello, aas is sending email " ); Â
            // Send message             Transport.send(message);             System.out.println( "Yo it has been sent.." );         }         catch (MessagingException mex) {             mex.printStackTrace();         }     } } |
OutputÂ
Â
Yo it has been sent...
The program is simple to understand and works well, but in real life, most of the SMTP servers use some sort of authentication such as TLS or SSL authentication. So, we will now see how to create a Session object for these authentication protocols. For TLS & SSL you can know the port in which the mail server running those services. We will provide you code taking Gmail into consideration. Following is the Send Mail in Java using SMTP with TLS authentication full implementation in java-Â
Â
Java
import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; Â
public class SendMail { Â
    public static void main(String[] args) {                  // change accordingly         final String username = "username@gmail.com" ;                   // change accordingly         final String password = "password" ;                  // or IP address         final String host = "localhost" ; Â
        // Get system properties         Properties props = new Properties();                             // enable authentication         props.put( "mail.smtp.auth" , "true" );                               // enable STARTTLS         props.put( "mail.smtp.starttls.enable" , "true" );                    // Setup mail server         props.put( "mail.smtp.host" , "smtp.gmail.com" );                     // TLS Port         props.put( "mail.smtp.port" , "587" );               Â
        // creating Session instance referenced to         // Authenticator object to pass in         // Session.getInstance argument         Session session = Session.getInstance(props,           new javax.mail.Authenticator() {                         //override the getPasswordAuthentication method             protected PasswordAuthentication                            getPasswordAuthentication() {                                                         return new PasswordAuthentication(username,                                                  password);             }           }); Â
        try {                          // compose the message             // javax.mail.internet.MimeMessage class is             // mostly used for abstraction.             Message message = new MimeMessage(session);                            // header field of the header.             message.setFrom( new InternetAddress( "from-email@gmail.com" ));                          message.setRecipients(Message.RecipientType.TO,                 InternetAddress.parse( "to-email@gmail.com" ));             message.setSubject( "hello" );             message.setText( "Yo it has been sent" ); Â
            Transport.send(message);        //send Message Â
            System.out.println( "Done" ); Â
        } catch (MessagingException e) {             throw new RuntimeException(e);         }     } } |
Following is the Send Mail in Java using SMTP with SSL authentication full implementation in java-
Â
Java
import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; Â
public class SendEmail { public static void main(String[] args)     {          // change accordingly         String to = "got@gmail.com" ;                  // change accordingly         String from = "akash@gmail.com" ;                  // or IP address         String host = "localhost" ;                  // mail id         final String username = "username@gmail.com"                  // correct password for gmail id         final String password = "mypassword" ; Â
        System.out.println( "TLSEmail Start" );         // Get the session object                  // Get system properties         Properties properties = System.getProperties();                  // Setup mail server         properties.setProperty( "mail.smtp.host" , host);                  // SSL Port         properties.put( "mail.smtp.port" , "465" );                  // enable authentication         properties.put( "mail.smtp.auth" , "true" );                  // SSL Factory         properties.put( "mail.smtp.socketFactory.class" ,                 "javax.net.ssl.SSLSocketFactory" ); Â
        // creating Session instance referenced to         // Authenticator object to pass in         // Session.getInstance argument         Session session = Session.getDefaultInstance(props,             new javax.mail.Authenticator() {                                  // override the getPasswordAuthentication                 // method                 protected PasswordAuthentication                         getPasswordAuthentication() {                     return new PasswordAuthentication( "username" ,                                                     "password" );                 }             }); } Â
 //compose the message try {     // javax.mail.internet.MimeMessage class is mostly     // used for abstraction.     MimeMessage message = new MimeMessage(session);          // header field of the header.     message.setFrom( new InternetAddress(from));          message.addRecipient(Message.RecipientType.TO,                           new InternetAddress(to));     message.setSubject( "subject" );     message.setText( "Hello, aas is sending email " ); Â
    // Send message     Transport.send(message);     System.out.println( "Yo it has been sent.." ); } catch (MessagingException mex) {     mex.printStackTrace(); } } } |
Multiple clients we can have the following changes in the above code
Â
Java
// This is an array of e-mail ID. You would // need to use InternetAddress() method // while specifying email IDs void addRecipients(Message.RecipientType type, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Address[] addresses) |