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.*;
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 = "[email protected]";
      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 = "[email protected]";
    
      // Add List of Email address to who email needs to be sent to
      private static final String[] emailList = {"[email protected]"};
    
      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 = "[email protected]";
    String pass = "xxxxx";
    String to = "[email protected]";
    String from = user;
    String subject = "Test subject";
    String messageText = "Test body";
    boolean sessionDebug = true;  // change to false after testing suceeded

    Properties props = System.getProperties();
    props.put("mail.host", host);
    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);

    /* TLSv1, SSLv3 or SSLv2 protocol support, which is required for old email clients/old PCs, is disabled in Postfix/Dovecot configuration.
     * By default, SSL protocols SSLv2 and SSLv3 are disabled in Postfix/Dovecot configuration as these protocols are vulnerable to the POODLE attack.
     * We need to enable safer protocols */

     props.setProperty("mail.smtps.ssl.protocols", "TLSv1.1 TLSv1.2");

    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("smtps");
    transport.connect(host, user, pass);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
    out.println("Sent - check tomcat log for details." );
    %>

These days SSL is omnipresent so let’s use it with SSL and port 465. Some ISPs block port 25 anyway or force SSL/TLS. When connecting to a local mail server that accepts non-SSL connections, default ports 25, 26, 587 should work for non-SSL connections but you will need to slightly modify the above code (rename smtps to smtp and comment 2 other SSL related lines) . If you prefer to encrypt your connections with TLS 1.1+ (what we recommend) then make sure your properties include smtps instead of smtp and that mail.smtps.ssl.trust and mail.smtps.ssl.protocols 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.

If you are using jakarta jars jakarta.mail-2.0.1.jar and jakarta.activation-2.0.1.jar please replace first line (import) with

<%@ page import="java.util.*, jakarta.mail.*, jakarta.mail.internet.*" %>

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.