1. Overview

In this quick tutorial, we’re going to look at sending an email with and without attachments using the core Java mail library.

2. Project Setup and Dependency

For this article, we’ll be using a simple Maven-based project with Angus Mail as its dependency. In detail, this library is the Eclipse implementation of the Jakarta Mail API specification:

<dependency>
    <groupId>org.eclipse.angus</groupId>
    <artifactId>angus-mail</artifactId>
    <version>2.0.1</version>
</dependency>

The latest version can be found here.

3. Sending a Plain Text and an HTML Email

First, we need to configure the library with our email service provider’s credentials. Then, we’ll create a Session that’ll be used to construct our message for sending.

The configuration is via a Java Properties object:

Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "sandbox.smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "sandbox.smtp.mailtrap.io");

In the properties configuration above, we configured the email host as Mailtrap and used the port provided by the service as well.

Note: To set up the configurations above correctly, we must check the official documentation from Mailtrap, as the host may vary depending on the type of SMTP integration we want to achieve.

Now, let’s create a session with our username and password:

Session session = Session.getInstance(prop, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
});

The username and password are given by the mail service provider alongside the host and port parameters.

Now that we have a mail Session object let’s create a Mime**Message for sending:

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(
  Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
message.setSubject("Mail Subject");

String msg = "This is my first email using JavaMailer";

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html; charset=utf-8");

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

message.setContent(multipart);

Transport.send(message);

In the snippet above, we first created a message instance with the necessary properties to, from, and subject. This is followed by a mimeBodyPart that has an encoding of text/html since our message is styled in HTML.

Next, we created an instance of the MimeMultipart object that we can use to wrap the mimeBodyPart we created.

Finally, we set the multipart object as the content of our message and used the send() of the Transport object to send mail.

*So, we can say that the mimeBodyPart is contained in the message‘s multipart. A multipart can contain more than one mimeBodyPart.*

This is going to be the focus of the next section.

4. Sending Email With an Attachment

Next, to send an attachment, we only need to create another MimeBodyPart and attach the file(s) to it:

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("path/to/file"));

We can then add the new body part to the MimeMultipart object we created earlier:

multipart.addBodyPart(attachmentBodyPart);

That’s all we need to do.

Once again, we set the multipart instance as the content of the message object, and finally, we’ll use the send() to send the mail.

5. Formatting Email Text

To format and style our email text, we can use HTML and CSS tags.

For example, if we want our text to be bold, we will implement the  tag. We can use the style tag to color the text. We can also combine HTML tags with CSS tags if we want to have additional properties, such as bold.

Let’s create a String containing bold-red text:

String msgStyled = "This is my <b style='color:red;'>bold-red email</b> using JavaMailer";

This String will hold our styled text to be sent in the email body.

6. Sending Email to Multiple Recipients

To send emails to multiple recipients, we can use the setRecipients() and addRecipients() methods which take an array of recipient addresses and recipient types such as TO, CC, and BCC  :

6.1. Using setRecipients()

We can set multiple recipients using the setRecipients() method. For the recipient list, we can pass the recipient type and the array of recipient addresses as arguments:

Address[] recipients = new InternetAddress[2];
recipients[0] = new InternetAddress("[email protected]");
recipients[1] = new InternetAddress("[email protected]");

message.setRecipients(Message.RecipientType.TO, recipients);

Additionally, we can also use InternetAddress.parse() method to pass the CSV of the email address as strings:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]"));

The parse() method converts the CSV of email addresses to an InternetAddress instance.

6.2. Using addRecipients()

addRecipients() is another method that allows us to add multiple recipients to the email Message instance*.* The main difference between the setRecipients() and addRecipients() methods is that the setRecipients() method overrides any existing set recipient and starts a fresh recipient list, while the addRecipient() method adds the recipient to the existing recipients if there is any already set.

Let’s add more recipients on top of what we set in the earlier section:

Address[] recipients1 = new InternetAddress[2]; 
recipients1[0] = new InternetAddress("[email protected]"); 
recipients1[1] = new InternetAddress("[email protected]");

message.addRecipients(Message.RecipientType.TO, recipients1);

Additionally, similar to the earlier section, we can also use the InternetAddress.parse() method to pass the CSV of the email address as strings:

message.addRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected], [email protected]"));

The parse() method converts the CSV of email addresses to an InternetAddress instance.

7. Conclusion

In this article, we’ve seen how to use the Jakarta Mail API to send emails, even with attachments. Additionally, we also learned how to send emails to multiple recipients.

As always, the complete source code is available over on GitHub.