How to send mail with JavaMail (SMTP/SMTPS/SSL)?

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:

user@gemini [~]# unzip javamail1_4_4.zip
user@gemini [~]# echo $JAVA_HOME
/opt/jdk1.6.0_23
user@gemini [~]# which java
/opt/jdk1.6.0_23/bin/java
user@gemini [~]#  javac -cp ./javamail-1.4.4/mail.jar SendMailUsingAuthentication.java
user@gemini [~]# 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 JVMCP 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.

This entry was posted in Java. Bookmark the permalink.

16 Responses to How to send mail with JavaMail (SMTP/SMTPS/SSL)?

  1. rob says:

    thank you, this tutorial really helps! the best on the internet i can find

  2. XBVVBB says:

    How to send mail when clicking a submit button using jsp code

    • admin says:

      To send mail after clicking a button you may include a form in your JSP file or add a separate html file with the form.
      Before executing sending code you first test if this is form submission and if submitted parameters are fine.

      • Davy says:

        One thing:
        It may be better to add @Override on method getPasswordAuthentication.
        Or else, it would be a little confusing about such a method.

  3. Lahiru Supun says:

    Hi JVM Host,

    Firstly i thank your hosting packages.It’s Good and very user friendly.then i have a some problem in how to using java mail.but now i create some part of java mail.plz can you do “How to Create Java mail ” Video Tutorial.I think it’s very helpful my future mail create.
    Tnx you very much JVM HOST present this Tutorial.

    Thanks and Best Regards,
    Lahiru SupunChandra.

  4. Gowtham says:

    i jus used the same code given.. i get the following error
    Exception in thread “main” com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. y6sm23014805pbl.23 – gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)
    at javaapplication1.JavaApplication1.postMail(JavaApplication1.java:44)
    at javaapplication1.JavaApplication1.main(JavaApplication1.java:21)
    Java Result: 1

    • admin says:

      Make sure you have smtp related lines commented and these in place
      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);

    • Virupax says:

      I’M getting the same error 530 5.7.0 Must issue a STARTTLS command first. e2sm7156253pdo.11 – gsmtp.

      Please Help!!!!

      -Thank you

      • admin says:

        Again, make sure you use smtps properties instead of smtp ones (see previous reply).
        Also set ‘boolean sessionDebug = true;’ in the example JSP code to have more details in log.

  5. aman says:

    nice tutorial,
    modified the codend and the email is getting send to gmail, yahoo id’s from my gmail id with port 465. But I’m entering my gmail username and passowrd in the code for authentication. i want to avoid this thing for obvious reasons. Basically I want to create a simple contact us form. The form is with a submit button with Name, E-mail, Subject and Message. Thne mailid here can be any and it gets send to outlook id. So how can I avoid to code it in a way that user don’t need to enter his/her password when sending email to my gmail id

    • admin says:

      If you intend to code an online form that anyone can use to send you an email by submitting name, contact email, subject and message
      then the form will need to know SMTP credentials to be able to deliver the message to you. It will then connect to a mail (SMTP) server
      and send the message. You should place your SMTP credentials in a properties file or hardcode them in your java code.

  6. Rex says:

    Thank you, very good tutorial. I am having a problem with mail not being delivered after getting a 250 recturn code and message number. I am using ESMTP. Is there anyway to query the message number to determine its status?

    Thanks.

    • admin says:

      If you have session mode set to debug and you can see the email has been delivered successfully and message number returned you can: 1) check spam folder of the recipient mailbox or 2) contact mail server admin for him to trace the message in mail server logs. In ideal world you should either find the message in mailbox Inbox (or a subfolder) or get undeliverability notice.

  7. Gabriel G. says:

    Could you help me please, in this line : “Transport t = session.getTransport(“smtps”)” I keep getting the error: “javax.mail.NoSuchProviderException: No provider for smtps”

    • admin says:

      Make sure you have javax.mail.jar in WEB-INF/lib. In catalina.out (with sessionDebug=true) you should see similar lines:
      DEBUG: setDebug: JavaMail version 1.5.0
      DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
      DEBUG SMTP: trying to connect to host “smtp.gmail.com”, port 465, isSSL true

  8. Bernhard says:

    This example does really works, at least for JSP. Very good!

Leave a Reply

Your email address will not be published. Required fields are marked *


three × nine =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>