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.

Eclipse 3.5 Galileo on Ubuntu Jaunty 9.04


Eclipse 3.5 (AKA Galileo) is the de facto standard for enterprise java development IDE. Eclipse on Linux platform is a perfect match with performance,proficiency and glory :-).

In order to begin playing with eclipse, we need to do some configurations.

1. Install Sun Java JDK

#sudo apt-get install sun-java6-jdk

2. Make Sun’s Java as your default Java installation

By default, Ubuntu 9.04 ships with a Java distribution called ‘icedTea’ or Open JDK and its littlebit slow. In order to make sure your system has that installation, open terminal window and type

#java -version

it’ll print the java version you are using right now. If it is set to Open JDK, then you have to change it to Sun’s JDK.

#sudo update-alternatives --config java

Then select the installation with path /usr/lib/jvm/java-6-sun/jre/bin/java.

3. Search for a pretty icon for eclipse

Download this one

http://commons.wikimedia.org/wiki/File:Vista-eclipse.png

Save it to your desktop

4. Download Eclipse Galileo

You can go to official site http://www.eclipse.org/downloads/ and choose your edition, here I choose eclipse for JEE developers edition. This will be nearly 188MB in size.

Save it to your desktop

5. Extract eclipse

Open the terminal and execute

#cd ~/Desktop
#tar xzf eclipse-jee-galileo-SR1-linux-gtk.tar.gz (replace your downloaded file name here)
#sudo mv eclipse /opt/eclipse
#sudo mv Vista-eclipse.png /opt/eclipse
#cd /opt
#sudo chown -R root:root eclipse
#sudo chmod -R +r eclipse
#cd /opt/eclipse
#sudo chmod +x eclipse

Here I’m gonna install eclipse into /opt, because I want eclipse to be installed for multiple user environment.

5. Create an executable shell for eclipse

Open terminal, execute the commands:

#sudo touch /usr/local/bin/eclipse (this assumes that /usr/local/bin is in the path)
#sudo chmod 755 /usr/local/bin/eclipse
#sudo gedit /usr/local/bin/eclipse

When file is opened with gedit, enter the following:

#!/bin/sh
export ECLIPSE_HOME=/opt/eclipse
$ECLIPSE_HOME/eclipse $*

6. Create GNOME menu item

Open Terminal, execute the following commands:

#sudo gedit /usr/share/applications/eclipse.desktop

Enter the following contents:

[Desktop Entry]
Encoding=UTF-8
Name=Eclipse
Comment=Eclipse Galileo IDE
Exec=eclipse
Icon=/opt/eclipse/Vista-eclipse.png
Terminal=false
Type=Application
Categories=GNOME;Application;Development
StartupNotify=True

7. Initialise eclipse

Open Terminal, execute:

#/opt/eclipse/eclipse –clean

8. From now on, you can choose to run Eclipse from menu Applications->Programming->Eclipse