Published on May 14 2012 in Java

Sending mail using JavaMail is most common method currently used by Java and JSP based web applications. It is mature, flexible and simple method.

Sending mail with Java class

Here goes a sample Java code with compilation and usage example:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
    public class SendMailUsingAuthentication
      private static final String SMTP_HOST_NAME = ""; //or simply "localhost"
      private static final String SMTP_AUTH_USER = "";
      private static final String SMTP_AUTH_PWD  = "secret";
      private static final String emailMsgTxt      = "Body";
      private static final String emailSubjectTxt  = "Subject";
      private static final String emailFromAddress = "";
      // Add List of Email address to who email needs to be sent to
      private static final String[] emailList = {""};
      public static void main(String args[]) throws Exception
        SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
        smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully Sent mail to All Users");
      public void postMail( String recipients[ ], String subject,
        String message , String from) throws MessagingException, AuthenticationFailedException
        boolean debug = false;
        //Set the host smtp address
        Properties props = new Properties();
        props.put("", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);
        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++)
            addressTo[i] = new InternetAddress(recipients[i]);
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        msg.setContent(message, "text/plain");
    private class SMTPAuthenticator extends javax.mail.Authenticator
        public PasswordAuthentication getPasswordAuthentication()
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);

Modify username, password, mailserver and put the above code into file. Download JavaMail from Sun website and unzip it. Then you can compile and execute the code:

[~]# unzip
[~]# echo $JAVA_HOME
[~]# which java
[~]#  javac -cp ./javamail-1.4.4/mail.jar
[~]# java -cp .:./javamail-1.4.4/mail.jar SendMailUsingAuthentication

Note: JavaMail 1.5.0 has been published in April 2013. It comes as javax.mail.jar.

Sending mail with Java Server Pages (JSP) script

If you prefer JSP test then create JSP file mail.jsp with the below contents

<%@ page import="java.util.*, javax.mail.*, javax.mail.internet.*" %>
    String host = "";
    String user = "";
    String pass = "xxxxx";
    String to = "";
    String from = "";
    String subject = "Test subject";
    String messageText = "Test body";
    boolean sessionDebug = false;
    Properties props = System.getProperties();
    props.put("", host);
    props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
    // props.put("mail.smtp.port", 26);
    // Uncomment 5 SMTPS-related lines below and comment out 2 SMTP-related lines above and 1 below if you prefer to use SSL
// props.put("mail.transport.protocol", "smtps");
// props.put("mail.smtps.auth", "true");
    // props.put("mail.smtps.port", "465");
    // props.put("", host);
    Session mailSession = Session.getDefaultInstance(props, null);
    Message msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSentDate(new Date());
    Transport transport = mailSession.getTransport("smtp");
// Transport transport = mailSession.getTransport("smtps");
transport.connect(host, user, pass);
    transport.sendMessage(msg, msg.getAllRecipients());

You don't need to use port property (default 25 will be used), but note that some ISPs block port 25, so you may prefer to add mail.smtp.port property with alternative port like 26. When connecting to local mail server default port 25 will work. If you prefer to encrypt your connections with SSL then make sure your properties include smtps instead of smtp and that is set. To send email to multiple recipients just add more addresses to the address list.

Put the file with above code to ~/appserver/apache-tomcat/webapps/ROOT and make sure mail.jar is in ~/appservers/apache-tomcat/lib then restart the application server with JCP or command line. Check results at

See also JavaMail API FAQ.

JavaMail and GMail - javax.mail.AuthenticationFailedException

Gmail may block sending if they detect it is first login try from a device. You will then see

javax.servlet.ServletException: javax.mail.AuthenticationFailedException: 534-5.7.9 Please log in with your web browser and then try again. Learn more at
534 5.7.9 

Read the instructions at the link. You will need to login to your Gmail account via web browser first and allow new application to access your account (you will be given information and prompt after logging in). Then try using the JSP script again and the email should be sent correctly this time.