How to send mail with JavaMail?

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

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

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 these 3 lines below and comment out 2 lines above if you prefer to use SSL
// 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.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

Bookmark and Share
This entry was posted in Java. Bookmark the permalink.

4 Responses to How to send mail with JavaMail?

  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.

Leave a Reply

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

*


+ six = 11

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>