Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Introduction to Simple Java Mail

$
0
0

1. Introduction

Simple Java Mail is a popular open-source library that simplifies sending emails in Java applications. It provides a user-friendly API compared to the standard JavaMail API, allowing us to focus on the content and recipients of our emails rather than low-level details.

In this tutorial, we’ll explore the process of setting up Simple Java Mail and learn how to send emails, including attachments and HTML content, handle exceptions, and more.

2. Setting up the Project

We start by adding the Simple Java Mail dependency into our project’s configuration file pom.xml:

<dependency>
    <groupId>org.simplejavamail</groupId>
    <artifactId>simple-java-mail</artifactId>
    <version><span class="pl-token">8</span>.<span class="pl-token">7</span>.<span class="pl-token">0</span></version>
</dependency>

3. Sending Email

Let’s start by sending a simple email using Simple Java Mail.

Emails can have two main parts for the body content: plain text and HTML. Plain text refers to the unformatted content that is displayed in most email clients without any special formatting or styling. They’re guaranteed to be readable by all email clients, regardless of their ability to display HTML content.

Here’s a basic example demonstrating how to construct a simple email:

Email email = EmailBuilder.startingBlank()
  .from("sender@example.com")
  .to("recipient@example.com")
  .withSubject("Email with Plain Text!")
  .withPlainText("This is a test email sent using SJM.")
  .buildEmail();

In this example, we use the startingBlank() method in the EmailBuilder class to initialize a new Email object with default values. It provides a starting point for constructing an email message by creating a blank email template without any predefined content or configuration.

Subsequently, we can then gradually fill in this template with the sender, recipient, subject, body, and other attributes using various methods provided by the EmailBuilder class. For instance, the withPlainText() method takes a string argument containing the actual text message we want to include in the email body.

Following this, we utilize MailerBuilder to configure the SMTP server particulars, encompassing the server’s address, port, username, and password. Finally, the Mailer class is used to dispatch the email:

Mailer mailer = MailerBuilder
  .withSMTPServer("smtp.example.com", 25, "username", "password")
  .buildMailer();
mailer.sendMail(email);

Additionally, to send an email to multiple recipients, we can simply specify multiple email addresses separated by commas in the to() method:

Email email = EmailBuilder.startingBlank()
  // ...
  .to("recipient1@example.com, recipient2@example.com, recipient3@example.com")
  // ...
  .buildEmail();

4. Sending Attachments

Adding attachments to an email is straightforward. We can attach files of various types, such as images, documents, or archives, to the email messages using the withAttachment() method of the EmailBuilder class.

Below is an example of using the withAttachment() method to attach a file in our email:

Email email = EmailBuilder.startingBlank()
  .from("sender@example.com")
  .to("recipient@example.com")
  .withSubject("Email with Plain Text and Attachment!")
  .withPlainText("This is a test email with attachment sent using SJM.")
  .withAttachment("important_document.pdf", new FileDataSource("path/to/important_document.pdf"))
  .buildEmail();

In the example, the withAttachment() method takes the filename and a FileDataSource object representing the attachment data. Moreover, if we need to attach multiple files to our email, we can use a list of AttachmentResource objects:

List<AttachmentResource> arList = new ArrayList<>();
arList.add(new AttachmentResource("important_document.pdf", new FileDataSource("path/to/important_document.pdf")));
arList.add(new AttachmentResource("company_logo.png", new FileDataSource("path/to/company_logo.png")));

Instead of using the withAttachment() method, we’ll utilize the withAttachments() method. This method allows us to pass in a collection of attachment resources:

Email email = EmailBuilder.startingBlank()
  // ...
  .withAttachments(arList)
  .buildEmail();

5. Sending HTML Content

Simple Java Mail allows us to send emails with HTML content and embed images directly within the email. This is useful for creating visually appealing and informative emails. To include embedded images in the HTML email content, we need to reference the images using the CID scheme.

This mechanism acts like a unique identifier that connects an image reference in the HTML content to the actual image data attached to the email. Essentially, it tells the email client where to locate the image for proper display.

Here’s how to create an HTML email that includes an image reference using a CID:

String htmlContent = "<h1>This is an email with HTML content</h1>" +
  "<p>This email body contains additional information and formatting.</p>" +
  "<img src=\"cid:company_logo\" alt=\"Company Logo\">";

In this example, the <img> tag references the image using the identifier cid:company_logo. This establishes the link within the HTML content. While constructing the email, we use the withEmbeddedImage() method to associate the image attachment with the chosen identifier company_logo. This ensures it matches the identifier used in the HTML content.

Here’s an example demonstrating how to send an email with HTML content and an embedded image:

Email email = EmailBuilder.startingblank()
  .from("sender@example.com")
  .to("recipient@example.com")
  .withSubject("Email with HTML and Embedded Image!")
  .withHTMLText(htmlContent)
  .withEmbeddedImage("company_logo", new FileDataSource("path/to/company_logo.png"))
  .buildEmail();

The image data itself isn’t directly embedded within the HTML content. It’s typically included as a separate attachment to the email.

It’s also recommended to provide a plain text version alongside the HTML content using withPlainText(). This offers a fallback option for recipients with email clients that don’t support HTML rendering:

Email email = EmailBuilder.startingBlank()
  // ...
  .withHTMLText(htmlContent)
  .withPlainText("This message is displayed as plain text because your email client doesn't support HTML.")
  .buildEmail();...

6. Replying to and Forwarding Emails

Simple Java Mail provides functionalities for constructing email objects for replying to and forwarding existing emails. When replying to an email, the original email is quoted in the body of the reply itself. Similarly, when forwarding an email, the original email is included as a separate body inside the forward.

To reply to an email, we use the replyingTo() method and provide the received email as a parameter. Then, we configure the email as desired and build it using the EmailBuilder:

<span class="hljs-type">Email</span> <span class="hljs-variable">email</span> <span class="hljs-operator">=</span> EmailBuilder
  .replyingTo(receivedEmail)
  .from("sender@example.com")
  .prependText("This is a Reply Email. Original email included below:")
  .buildEmail();

To forward an email, we use the forwarding() method and provide the received email as a parameter. Then, we configure the email as desired, including any additional text, and build it using the EmailBuilder:

<span class="hljs-type">Email</span> <span class="hljs-variable">email</span> <span class="hljs-operator">=</span> EmailBuilder
  .forwarding(receivedEmail)
  .from("sender@example.com")
  .prependText("This is a Forwarded Email. See below email:")
  .buildEmail();

However, it’s important to understand that Simple Java Mail itself cannot directly retrieve emails from the email server. We’ll need to utilize additional libraries like javax.mail to access and retrieve emails for replying or forwarding.

7. Handling Exceptions

When sending emails, it’s crucial to handle exceptions that may occur during the transmission process to ensure robust functionality. Simple Java Mail throws a checked exception called MailException when errors occur while sending emails.

To effectively handle potential errors, we can enclose our email sending logic within a trycatch block, catching the instances of the MailException class. Below is a code snippet demonstrating how to handle MailException using a try-catch block:

try {
    // ...
    mailer.sendMail(email);
} catch (MailException e) {
    // ...
}

Moreover, validating email addresses before dispatching them can mitigate the likelihood of errors during the email transmission process. We can achieve this by using the validate() method provided by the mailer object:

boolean validEmailAdd = mailer.validate(email);
if (validEmailAdd) {
    mailer.sendMail(email);
} else {
    // prompt user invalid email address
}

8. Advanced Configuration Options

Additionally, Simple Java Mail offers various configuration options beyond the basic functionalities. Let’s explore additional configuration options available, such as setting custom headers, configuring delivery or reading receipts, and limiting email size.

8.1. Setting Custom Headers

We can define custom headers for the emails using the withHeader() method on the MailerBuilder class. This allows us to include additional information beyond the standard headers:

Email email = Email.Builder
  .from("sender@example.com")
  .to("recipient@example.com")
  .withSubject("Email with Custom Header")
  .withPlainText("This is an important message.")
  .withHeader("X-Priority", "1")
  .buildEmail();

8.2. Configure Delivery/Read Receipt

A delivery receipt confirms that an email has been delivered to the recipient’s mailbox, while a read receipt confirms that the recipient has opened or read the email. Simple Java Mail provides built-in support for configuring these receipts using specific email headers: Return-Receipt-To for delivery receipts and Disposition-Notification-To for reading receipts.

We can explicitly define the email address to which the receipts should be sent. If we don’t provide an address, it’ll default to using the replyTo address if it’s available, or it uses the fromAddress.

Here’s how we can configure these receipts:

Email email = EmailBuilder.startingBlank()
  .from("sender@example.com")
  .to("recipient@example.com")
  .withSubject("Email with Delivery/Read Receipt Configured!")
  .withPlainText("This is an email sending with delivery/read receipt.")
  .withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
  .withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
  .buildEmail();

8.3. Limit Maximum Email Size

Many email servers have restrictions on the maximum size of emails they can accept. Simple Java Mail provides a feature to help us prevent sending emails that exceed these limitations. This can save us from encountering errors during email delivery attempts.

We can configure the maximum allowed email size using the withMaximumEmailSize() method on the MailerBuilder object. This method takes an integer value representing the size limit in bytes:

Mailer mailer = MailerBuilder
  .withMaximumEmailSize(1024 * 1024 * 5)
  .buildMailer();

In this example, the maximum email size is set to 5 Megabytes. If we attempt to send an email that surpasses the defined limit, Simple Java Mail throws a MailerException with a cause of EmailTooBigException.

9. Conclusion

In this article, we’ve explored various aspects of Simple Java Mail, including sending emails with attachments and HTML content with embedded images. Additionally, we dove into its advanced functionalities, such as managing delivery, read receipts, and handling email replies and forwards.

Overall, it’s best suited for Java applications that require sending emails straightforwardly and efficiently.

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

       

Viewing all articles
Browse latest Browse all 4536

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>