Wednesday, 26 September 2012

Sending Plain Text Or HTML Emails In Java

This post describes how to send plain text or HTML emails from Java. The code examples are available from Github in the Java-Email-Sending directory. To make these work, you will need to set a proper 'to' email address in the code, and eventually a sending email server login and password.

Plain Text Email

The following creates a simple email with plain text content and sends it to the recipient:
String to = "jverstry@gmail.com";
String from = "ffff@ooop.com";

// Which server is sending the email?
String sender = "localhost";

// Setting sending mail server
Properties ps = System.getProperties();
ps.setProperty("mail.smtp.host", sender);

// Providing email and password access to mail server
ps.setProperty("mail.user", "jverstry@gmail.com");
ps.setProperty("mail.password", "xxxxxxxxxxxxx");

// Retrieving the mail session
Session session = Session.getDefaultInstance(ps);

// Create a default MimeMessage
MimeMessage m = new MimeMessage(session);

m.setFrom(new InternetAddress(from));
m.addRecipient(
    Message.RecipientType.TO, new InternetAddress(to));

m.setSubject("This an email test !!!");
m.setText("Some email message content");

// Sending the message
Transport.send(m);
The email will look like this:

Email with Plain Text Content

HTML Email

The same procedure can be used for an HTML email. The m.setText("Some email message content"); line should be replaced with:
StringBuilder htmlContent = new StringBuilder();
htmlContent.append("<h1>My Email Content Header</h1>");
htmlContent.append("Some body text");

m.setContent(htmlContent.toString(), "text/html" );
The email will look like this:

Email with HTML Content