Sending Emails with Java

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 use the port provided by the service as well.

Now let’s move further by creating 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("from@gmail.com"));
message.setRecipients(
  Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");

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

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");

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. Followed by a mimeBodyPartthat has an encoding of text/html, since our message is styled in HTML.

The next thing we did is to create 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 use the send()of Transport object to do the mail sending.

So, we can say that the mimeBodyPartis contained in the multipart that is contained in the message. Hence, 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 MimeBodyPartand 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 MimeMultipartobject 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. Conclusion

In conclusion, we’ve seen how to use the native Java mail library to send emails even with attachment.

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

Related posts:

Inject Parameters into JUnit Jupiter Unit Tests
Hướng dẫn Java Design Pattern – Interpreter
Converting a Stack Trace to a String in Java
Java Program to Implement Threaded Binary Tree
Initialize a HashMap in Java
Java Program to Implement LinkedBlockingDeque API
Java Program to Implement Variable length array
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Programmatic Transaction Management in Spring
Hướng dẫn sử dụng Java Generics
Java Program to Find the Vertex Connectivity of a Graph
Spring MVC Async vs Spring WebFlux
Sorting in Java
Java Program to Generate Random Numbers Using Middle Square Method
Converting a Stack Trace to a String in Java
How to Get a Name of a Method Being Executed?
Marker Interface trong Java
Setting Up Swagger 2 with a Spring REST API
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Hướng dẫn Java Design Pattern – Decorator
LinkedHashSet trong Java hoạt động như thế nào?
So sánh HashMap và Hashtable trong Java
Java Program to Find Inverse of a Matrix
The DAO with Spring and Hibernate
Introduction to Netflix Archaius with Spring Cloud
Spring’s RequestBody and ResponseBody Annotations
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Các nguyên lý thiết kế hướng đối tượng – SOLID
Java Program to Perform Naive String Matching
Java Program to Perform the Unique Factorization of a Given Number
XML Serialization and Deserialization with Jackson
Mệnh đề Switch-case trong java