Send email using JavaMail API and your Gmail account


Hi folks! For your convenience, I’ve hosted the source code for this article at GitHub. Please feel free to try out that code and drop me a line if you get any queries. You can access the repository here.

Sending email using Java is not a difficult task and it’s just about writing few lines of codes. But when you are writing such an application, you’ll end up with lot of exceptions obviously. There are lots of reasons for that, but as my opinion, wrong email configuration settings would cause the exceptions.

If you need to write a Java application to send an email, you need an outgoing mail server such as SMTP (Simple Mail Transfer Protocol) server. There are many SMTP servers out there, but in order to send an email most servers require authentication (You have to have an account in your SMTP server and you must know account credentials). There exist free SMTP servers without authentication, but I’m not sure about their reliability and Quality of Service (QoS).

At the authentication process, most developers fail due to bad configurations. There are several configuration settings should be set in your code, before you submit the message to the SMTP server.

To demonstrate this settings, I’ll create a Java application from the scratch and it will use Gmail as the outgoing SMTP server (You can use any SMTP server with valid credentials. But here I used Gmail because I’m addicted to Google!).

You can download the complete source code and required libraries here. I developed it using NetBeans IDE, but you can use any IDE to proceed.

Prerequisites

Source Code

package com.dunithd.jmail;

import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;

import java.util.*;

/**
 * Simple Class to send an email using JavaMail API (javax.mail) and Gmail SMTP server
 * @author Dunith Dhanushka, dunithd@gmail.com
 * @version 1.0
 */
public class GmailSender {

    private static String HOST = "smtp.gmail.com";
    private static String USER = "your_username@gmail.com";
    private static String PASSWORD = "put_your_password_here";
    private static String PORT = "465";
    private static String FROM = "put_from_address_here";
    private static String TO = "put_to_address_here";

    private static String STARTTLS = "true";
    private static String AUTH = "true";
    private static String DEBUG = "true";
    private static String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static String SUBJECT = "Testing JavaMail API";
    private static String TEXT = "This is a test message from my java application. Just ignore it";

    public static synchronized void send() {
        //Use Properties object to set environment properties
        Properties props = new Properties();

        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.user", USER);

        props.put("mail.smtp.auth", AUTH);
        props.put("mail.smtp.starttls.enable", STARTTLS);
        props.put("mail.smtp.debug", DEBUG);

        props.put("mail.smtp.socketFactory.port", PORT);
        props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        try {

            //Obtain the default mail session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);

            //Construct the mail message
            MimeMessage message = new MimeMessage(session);
            message.setText(TEXT);
            message.setSubject(SUBJECT);
            message.setFrom(new InternetAddress(FROM));
            message.addRecipient(RecipientType.TO, new InternetAddress(TO));
            message.saveChanges();

            //Use Transport to deliver the message
            Transport transport = session.getTransport("smtp");
            transport.connect(HOST, USER, PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
       GmailSender.send();
       System.out.println("Mail sent successfully!");
    }
}

When writing the application, you have to set some Environment Properties that are used by the JavaMail APIs. The JavaMail javadocs contain additional information on properties supported by JavaMail.

You can use java.util.Properties class to set these properties.

  • mail.smtp.host: Specifies the protocol-specific default Mail server. In your application, set this property to smtp.gmail.com
  • mail.smtp.user: Specifies the protocol-specific default username for connecting to the Mail server. In your application, set this property to your Gmail username.
  • mail.smtp.auth: Specifies whether host requires authentication or not. In our application, set this property to true.
  • mail.smtp.debug: Specifies the initial debug mode. Setting this property to true will turn on debug mode, while setting it to false turns debug mode off. If you need deeper diagnosis, set this to true.
  • mail.smtp.port: Specifies the port that is used by SMTP server. In your application, set this to 465.
  • mail.smtp.starttls.enable: This is the most important one. If you miss this, you’ll definitely get an error. Most SMTP servers support SSL (Secure Socket Layer) connections which can be used for secure login to the server. They use STARTTLS command (see RFC 2487 and RFC 3501) to switch the connection to be secured by TLS.
    Use of the STARTTLS command is preferred in cases where the server supports both SSL and non-SSL connections. This SSL/TLS support in JavaMail works only when JavaMail is used on a version of J2SE that includes SSL support.
    The STARTTLS support is available in the standard “IMAP” and “SMTP” protocols, but must be enabled by setting the appropriate property, mail.imap.starttls.enable or mail.smtp.starttls.enable, to “true”. When set, if the server supports the STARTTLS command, it will be used after making the connection and before sending any login information.

If everything goes fine, you’ll see an output like this.

Output of the application
Output of the application

Notes

This application cannot be used in a network that uses a proxy server. You must have a direct connection to the internet otherwise you’ll get UnknownHostException.

UnknownHostException
UnknownHostException

In my next post, I’m gonna explain you how to send an email with an attachment.

Advertisements