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.*;
import java.io.*;
    
    public class SendMailUsingAuthentication
    {
      private static final String SMTP_HOST_NAME = "gemini.jvmhost.com"; //or simply "localhost"
      private static final String SMTP_AUTH_USER = "me@domain.com";
      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 = "me@domain.com";
    
      // Add List of Email address to who email needs to be sent to
      private static final String[] emailList = {"he@domain.net"};
    
      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("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);
    
        session.setDebug(debug);
    
        // create a message
        Message msg = new MimeMessage(session);
    
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
    
        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.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
     }
    
    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 SendMailUsingAuthentication.java file. Download JavaMail from Sun website and unzip it. Then you can compile and execute the code:

[~]# unzip javamail1_4_4.zip
[~]# echo $JAVA_HOME
    /opt/jdk1.6.0_23
[~]# which java
    /opt/jdk1.6.0_23/bin/java
[~]#  javac -cp ./javamail-1.4.4/mail.jar SendMailUsingAuthentication.java
[~]# 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 = "mail.domainname.com";
    String user = "user@domain.com";
    String pass = "xxxxx";
    String to = "user@example.com";
    String from = "user@domain.com";
    String subject = "Test subject";
    String messageText = "Test body";
    boolean sessionDebug = false;
    
    Properties props = System.getProperties();
    props.put("mail.host", 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("mail.smtps.ssl.trust", host);
    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(sessionDebug);
    Message msg = new MimeMessage(mailSession);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(messageText);
    Transport transport = mailSession.getTransport("smtp");
// Transport transport = mailSession.getTransport("smtps");
transport.connect(host, user, pass);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    %>

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 mail.smtps.ssl.trust 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 http://yourdomain.com/mail.jsp.

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 https://support.google.com/mail/bin/answer.py?answer=78754 

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.