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:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

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.

Last Updated: July 26th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms