Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

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 a dependency on the Java mail library:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</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 in constructing 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", "smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "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.

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 MimeMessage 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 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 Transport object to do the mail sending.

So, we can say that the mimeBodyPart is contained in the multipart that is contained in the message. This way, 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 do the mail sending.

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 <b> tag. For coloring the text, we can use the style tag. 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. Conclusion

In this article, we've seen how to use the native Java mail library to send emails even with attachments.

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

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!