About Antonio Santiago

A Computer Science as profession and hobby. Firm believer of Software Engineering and a lover of Agile methodologies. There is no ring to rule them all, every place needs to forge its own master ring.

Sending emails with Java

I start writing this post as a simple “how to send an email” using Java, but later I found I need to briefly explain more things. So, here is this kind of all in one summary about sending emails with Java.

Outside the Java SE platform, but included in JavaEE one, the JavaMail package provides a platform to build mail and messaging applications. Lets go with an example.

Sending a simple text message

// Common variables
String host = "your_smtp_server";
String from = "from_address";
String to = "to_address";

// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", "true");
 
// Get session
Session session = Session.getInstance(props);
 
try {
    // Instantiate a message
    Message msg = new MimeMessage(session);
 
    // Set the FROM message
    msg.setFrom(new InternetAddress(from));
 
    // The recipients can be more than one so we use an array but you can
    // use 'new InternetAddress(to)' for only one address.
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);
 
    // Set the message subject and date we sent it.
    msg.setSubject("Email from JavaMail test");
    msg.setSentDate(new Date());
 
    // Set message content
    msg.setText("This is the text for this simple demo using JavaMail.");
 
    // Send the message
    Transport.send(msg);
}
catch (MessagingException mex) {
    mex.printStackTrace();
}

Alternatively, instead using:

msg.setText("This is the text for this simple demo using JavaMail.");

you can use next to set the message content:

msg.setContent("This is the text for this simple demo using JavaMail.", "text/plain");

Checking an email address

Here is a little trick to check, using a regular expression, if an email address is well formed:

Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
if(rfc2822.matcher(EMAIL_ADDRESS).matches()) {
    // Well formed email
}

Multipart messages

That’s fine, but usually you don’t send simple text messages. Instead you send nice HTML body messages with bold or italic text, images, and so on.

NOTE: See below at references section to see about MIME format which extends the data you can attach to an email to allow multiparts, attachments, etc.

When you write a multipart message the content is composed of different parts, for example one part is the message written as simple text and a second part with the same message written in an enhanced way using HTML. Then the client that reads the message is responsible to render the appropriate part depending on its capabilities.

...
// Here create two parts and set as message contect
// Create and fill first part
MimeBodyPart part1 = new MimeBodyPart();
part1.setText("This is part one of this multipart message.");
 
// Create and fill second part
MimeBodyPart part2 = new MimeBodyPart();
part2.setText("This is part two of this multipart message.");
 
// Create the Multipart.
Multipart mp = new MimeMultipart();
mp.addBodyPart(part1);
mp.addBodyPart(part2);
 
// Set the message's content
msg.setContent(mp);
...

Sending attachments

Terrific, we know how to send a plain text email and something more incredible like a multipart message with HTML content. Next step is to send an email attaching too some files.

Create an email with attached file is similar to create a multipart message where one part can be the text of the message and another part is the attached file. The secret is in the next lines:

...
// Create a new part for the attached file
MimeBodyPart part3 = new MimeBodyPart();
 
// Put a file in the second part
FileDataSource fds = new FileDataSource("THE_FILE_NAME");
part3.setDataHandler(new DataHandler(fds));
part3.setFileName(fds.getName());
 
// 'mp' is the previously created 'MimeMultipart' object
mp.addBodyPart(part3);
 
// 'msg' is the previously created 'Message' object
msg.setContent(mp);
...

HTML messages

Create a message o multipart message with HTML content is really easy, simply specify the MIME type in the setContent method:

...
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part</p>", "text/html");
...

Attaching images within the HTML code

If you write a rich message using HTML you can, of course, add images using the ‘img‘ tag. If the image is referenced from an external server there is no problem, but: how to attach an image to the message and render within the HTML message body?

The idea is as follow:

  • first you need to attach the image file and set an identifier and
  • second you need to write your HTML code and reference the image identifier in the ‘img‘ tag.
...
// Create and fill html part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part with an attached image</p>" +
    "<img src='cid:some_image_id'>", "text/html");
 
// Create a new part for the attached image and set the CID image identifier
MimeBodyPart imagePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("THE_IMAGE_FILE_NAME");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "some_image_id");
 
mp.addBodyPart(htmlPart);
mp.addBodyPart(imagePart);
...

Anything more to say?

Arrived to this point you are almost a master of sending emails. You know how to send simple emails, multipart emails with richest HTML content and attach files and images on your message.

What more can a programmer desire?

Probably, a more easy to use API and that is what Apache Commons Email project offer you. See the ‘user guide‘ section http://commons.apache.org/email/userguide.html to understand what I say. It offers a more abstract API more close to humans than to protocols.

Resources

Reference: Sending emails with Java from our JCG partner Antonio Santiago at the “A Curious Animal” Blog.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

4 Responses to "Sending emails with Java"

  1. Aryan says:

    Disgusting,
    It’s not working

  2. If you want the code that actually works to add attachment in email in java language then Click Here it is one of the feature of Aspose.Email for Java it provides many features to get more codes related to emails in java visit the documentation page of this product.

  3. Ranjan says:

    very well explained..Thanks !! ..,but I want to know if we can attach multiple file while sending the mail through the interface..Hope to get a positive answer soon.

  4. Rahul says:

    when i am sending mail using smtp protocol, it gaves me an exception while adding the attachment, but still i see the mail in my inbox.
    Any help in this regard?

Leave a Reply


× 3 = eighteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close