Sending HTML email with JavaMail

Posted on July 22nd, 2015

demo-002pic

JavaMail is an open source project which provides classes which simulate a mailing system. In this Java tutorial I will show you how to send an email via Microsofts Outlook SMTP and Googles very own Gmail SMTP

 

Some time ago I created a Java wedding invitation applet. To send out the applet instructions to the invitees I wrote a Java program which went through the 100+ invitee list sending the applet details to each recipient. This is the tutorial to view if you’re interested in finding out how I did it

SETUP

To start us off we will need to download the JavaMail API. Download the javax.mail.jar file from here and add it to your computers classpath. There are various ways of doing this but if you’re using the Eclipse IDE I’ve created screenshots showing how to add the javax.mail.jar file into your classpath. Click here to view them. Once you’ve done that you’ll need to import the different javax classes we will require to connect to the various SMTP servers and also some standard java classes which I’ll use to open a .html file:

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.Scanner;

CONNECTING TO A SMTP SERVER

I’ll demonstrate how to connect to the Hotmail and Gmail servers, but with a bit of Googling you’ll find more SMTP server settings for other email service providers.

Firstly get your systems properties and store them in a props variable:

Properties props = System.getProperties();

For Gmail, the connection settings are

props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

For Outlook, the settings are

props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.live.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");

Now for authentication. Here enter either your Gmail acount details (mail@gmail.com, password) or Outlook details.

Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("mail@gmail.com", "password");
    }
});

Send the email in a try and catch block:

try {
    String htmlString = readHTMLfile();
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("mail@gmail.com"));
    message.setSubject("Weekly newsletter!");
    message.setContent(htmlString, "text/html");
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@somewhere.com"));
    Transport.send(message);
    System.out.println("Message sent succesfully!");
} catch(Exception e) {
    System.out.println("Error in sending mail! Error message: " + e.getMessage());
}

Enter the email you’re sending from (the same one you used in the authentication step) in the .setFrom(new InternetAddress("mail@gmail.com")) method. Recipients email address goes in the .setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@somewhere.com")) method. Embed the html message into the email using the .setContent(htmlString, "text/html") method. The htmlString variable was created from a .html file using the readHTMLfile() function:

private static String readHTMLfile() {
    String str = "";
    try {
        Scanner sc = new Scanner(new File("src/htmlMessage.html")).useDelimiter("'");
        str += sc.next();
        str += "\'";
        while (sc.hasNext()) {
            str += "\'";
            str += sc.next();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return str;
}

Within local storage I created a html file housing all the mail code (view it on Github). Scanner class breaks file into tokens distinguished by what I set as the Delimiter (in this case a single quote ‘ mark). This is to then add the \ character before single quotes to include the special character in the String. These tokens are concatenated in the str variable before str variable is returned

Compile the program and run it to test it. This was my end product:

MailDevices

Other classes are available from the JavaMail API (e.g. adding attachments). Read its complete documentation here