How to Send Emails in Java

Overview

Most websites today offer a subscription to a newsletter of any sort to let us know about their great deals, discounts, new products, services, and receipts.

When signing up on a website, we also (in most cases) receive an email to verify our email address and link it to the account you're signing up for.

This can be a great marketing tactic and can really grow your business and platform, so knowing how to build a simple system to send emails is a must, especially if you're launching a platform that offers a product or service of any sort.

To achieve this, we'll use one of Java's core libraries - javax.mail.

Sending a Plain Text Email

Although our example email below isn't as exciting as the well-designed emails with custom buttons and pictures, a simple email like this is often sent for registration or password reset means:

public class EmailSender {  
    public static void main(String[] args) {
        String recipient = "[email protected]";
        String sender = "[email protected]";
        String host = "localhost";

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sender));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            message.addRecipients(Message.RecipientType.TO, new Address[...]); // email to multiple recipients
            message.setSubject("Hello World!");
            message.setText("And hello from the body of the message!");

            Transport.send(message);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

We're introduced with a couple of classes here:

  • Properties - Represents any set of properties and defaults.
  • Session - Collects the properties and defaults used by the mail's API.
  • MimeMessage - Represents the MIME style email message.
  • InternetAddress - Represents a RFC882 syntax internet address - "[email protected]"

Sending Email with HTML

HTML emails are very common and you probably see them every day in your inbox. All the new fancy catalogs and eye-popping products are decorated to appeal as much as possible, just like their website counter-parts.

Sending an email with HTML is a bit different from the preceding example in just a single line:

public class EmailSender {

    public static void main(String[] args) {
        String recipient = "[email protected]";
        String sender = "[email protected]";
        String host = "localhost";

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sender));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            message.setSubject("Hello World!");

            message.setContent("<h1>Message Header</h1>" +
                    "<p>This is a paragraph </p>" +
                    "<p>This is another paragraph</p>", "text/html");

            Transport.send(message);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

By using the .setContent() method, and setting the type to be "text/html", we're able to add HTML to our email message.

The method accepts either a MultiPart object or an Object/String, and simply sets the arguments as the content of the message.

Sending Email with an Attachment

In many cases you might like to send an email with an attachment of any kind. For example, after a customer orders your product or pays for your service - you'd want to send a receipt to confirm the purchase.

If your product or service requires legal documents, a customer may also receive a legal document to sign and send back, all of which can be done with email.

In any of these cases, this requires a bit of a different approach than our previous examples:

public class EmailSender {

    public static void main(String[] args) {
        String recipient = "[email protected]";
        String sender = "[email protected]";
        String host = "localhost";

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sender));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            message.setSubject("Receipt for your product!");

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText("Thank you for buying with us, here's a receipt for your product.");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource("receipt.txt");
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);

            Transport.send(message);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Here, we're being introduced to a few new classes:

  • BodyPart - An abstract class that represents a part of a Multipart
  • Multipart - A container for multiple BodyPart objects
  • DataSource - Provides a type for an arbitrary collection of data, as well as access to it in the form of InputStreams and OutputStreams

When adding a Multipart as content, we can add as many BodyParts into it, and after adding one, we can use the same reference variable to initialize a new one, and store it into the Multipart as well.

Conclusion

These are the three of the most common things you'd need to know to send emails of any sort in plain old Java, without any additional third-party libraries.

Author image
About David Landup
Serbia Twitter Github