JavaMail - Sending email example

[Last Updated: Jul 31, 2018]

This tutorial shows how to use JavaMail API to send email via an outgoing SMTP server.


Maven dependency



Using JavaMail API

package com.logicbig.example;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailClient {
  private static final String senderEmail = "";//change with your sender email
  private static final String senderPassword = "12345678";//change with your sender password

  public static void sendAsHtml(String to, String title, String html) throws MessagingException {
      System.out.println("Sending email to " + to);

      Session session = createSession();

      //create message using session
      MimeMessage message = new MimeMessage(session);
      prepareEmailMessage(message, to, title, html);

      //sending message

  private static void prepareEmailMessage(MimeMessage message, String to, String title, String html)
          throws MessagingException {
      message.setContent(html, "text/html; charset=utf-8");
      message.setFrom(new InternetAddress(senderEmail));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

  private static Session createSession() {
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");//Outgoing server requires authentication
      props.put("mail.smtp.starttls.enable", "true");//TLS must be activated
      props.put("", ""); //Outgoing server (SMTP) - change it to your SMTP server
      props.put("mail.smtp.port", "587");//Outgoing port

      Session session = Session.getInstance(props, new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(senderEmail, senderPassword);
      return session;

  public static void main(String[] args) throws MessagingException {
              "Test email",
              "<h2>Java Mail Example</h2><p>hi there!</p>");


Sending email to

On gmail client:

Above sender and email accounts were created for demo purpose only; they were deleted afterwards.

If you are going to use gmail smtp server then use following configuration:

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("", "");
        props.put("mail.smtp.port", "587");

Example Project

Dependencies and Technologies Used:

  • javax.mail 1.6.1 JavaMail API
  • JDK 10
  • Maven 3.5.4

Sending email using JavaMail Select All Download
  • java-mail-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

    See Also