Send Bulk Emails Using Java

Introduction

This tutorial shows how do you send bulk emails at once. This tutorial uses one method sendEmail(), which takes only one parameter – MimeMessage. This email sending example can be used to send different types of messages, such as, text, html, etc. Even you can send file attachements using this example.

When do you need to send bulk emails?

Newsletters Emails

A newsletter is a good way of keeping subscribers in the loop about what is going on in a business. In most cases, they provide insights, notifications or guides to customers in a bid to help them understand a particular service or product better.

Promotional Emails

Bulk email is effective at promoting sales, attracting customers with offers and deals, and building brand awareness. These emails can also be used to suggest appropriate products to existing and prospective customers.

Acquisition Emails

These emails are sent with the goal of acquiring new customers and are typically directed at prospects on a list who are yet to convert. These emails may be used to share special offers to convince these potential customers to make a purchase.

Retention Emails

These bulk emails are generally sent to existing clients to encourage them to keep purchasing from the company. They aim to boost a brand customer’s loyalty.

Prerequisites

Java 1.8+ (tested with 11/12), Java Mail API 1.6.2 or Jakarta Mail API 2.x.x, Maven 2.8.2 – 2.8.5, Gradle 5.6.1+

Project Setup

You can use below build.script in your gradle based project.

plugins {
    id 'java-library'
}

sourceCompatibility = 12
targetCompatibility = 12

repositories {
	mavenCentral()
}

dependencies {
    implementation 'javax.mail:javax.mail-api:1.6.2'
}

You can use below pom.xml file for maven based project:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.roytuts</groupId>
	<artifactId>java-bulk-email-send</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>jakarta.mail</artifactId>
			<version>2.0.1</version>
		</dependency>

		<dependency>
			<groupId>jakarta.mail</groupId>
			<artifactId>jakarta.mail-api</artifactId>
			<version>2.1.0</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
			</plugin>
		</plugins>
	</build>
</project>

Since version 2, Java mail API has been changed to Jakarta mail API. If you use Java mail API then you can use the following dependency:

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>javax.mail-api</artifactId>
	<version>1.6.2</version>
</dependency>

Send Bulk Emails using Java

The following code example will help you to send emails in different formats and even you will be able to send attachments using the following code.

The following POJO class has some attributes for helping with the email information:

public class EmailInfo {

	private String from;
	private List<String> toList;
	private List<String> ccList;
	private String subject;
	private String bodyTemplate;

	public EmailInfo(String from, String[] toList, String[] ccList, String subject) {
		this.from = from;
		this.toList = Arrays.asList(toList);
		this.ccList = Arrays.asList(ccList);
		this.subject = subject;
	}

	public EmailInfo(String from, List<String> toList, List<String> ccList, String subject) {
		this.from = from;
		this.toList = toList;
		this.ccList = ccList;
		this.subject = subject;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public List<String> getToList() {
		return toList;
	}

	public void setToList(List<String> toList) {
		this.toList = toList;
	}

	public List<String> getCcList() {
		return ccList;
	}

	public void setCcList(List<String> ccList) {
		this.ccList = ccList;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getBodyTemplate() {
		return bodyTemplate;
	}

	public void setBodyTemplate(String bodyTemplate) {
		this.bodyTemplate = bodyTemplate;
	}

}

The following class is used to send bulk emails to intended recipients:

package com.roytuts.java.bulk.email.send;

import java.util.Date;
import java.util.Objects;
import java.util.Properties;
import java.util.function.Function;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

public class BulkEmailSender {

	private EmailInfo emailInfo;
	private Properties emailConfig;
	private MimeMessage mimeMessage;

	public BulkEmailSender(EmailInfo emailInfo, Properties emailConfig) {
		this.emailInfo = emailInfo;
		this.emailConfig = emailConfig;
	}

	public EmailInfo getEmailInfo() {
		return emailInfo;
	}

	public void sendEmail(MimeMessage mimeMessage) {
		try {
			Transport.send(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public MimeMessage getMimeMessage() {
		mimeMessage = buildMimeMessage();
		return mimeMessage;
	}

	private MimeMessage buildMimeMessage() {
		Session session = Session.getInstance(emailConfig);
		MimeMessage mimeMessage = new MimeMessage(session);

		// if you want to use authentication for your email, so "mail.smtp.auth" need to
		// be set true
		// Session session = Session.getInstance(emailConfig, new Authenticator() {
		// @Override
		// protected PasswordAuthentication getPasswordAuthentication() {
		// return new PasswordAuthentication("username", "password");
		// }
		// });

		try {
			setFromAddress().andThen(setToAddress()).andThen(setCcAddress()).andThen(setSubject()).apply(mimeMessage);

			mimeMessage.setSentDate(new Date());
		} catch (Exception e) {
			mimeMessage = null;
			throw new RuntimeException("Error in setting from, to, cc address and subject of the email");
		}

		return mimeMessage;
	}

	private Function<MimeMessage, MimeMessage> setSubject() {
		return mimeMessage -> {
			if (!Objects.isNull(emailInfo.getSubject()) && !emailInfo.getSubject().isEmpty()) {
				try {
					mimeMessage.setSubject(emailInfo.getSubject());
				} catch (Exception e) {
					throw new RuntimeException("Could not set subject " + emailInfo.getSubject());
				}
			}
			return mimeMessage;
		};
	}

	private Function<MimeMessage, MimeMessage> setFromAddress() {
		return mimeMessage -> {
			if (!Objects.isNull(emailInfo.getFrom()) && !emailInfo.getFrom().isEmpty()) {
				try {
					mimeMessage.setFrom(new InternetAddress(emailInfo.getFrom().trim()));
				} catch (Exception e) {
					throw new RuntimeException("Could not resolve from address " + emailInfo.getFrom());
				}
			}
			return mimeMessage;
		};
	}

	private Function<MimeMessage, MimeMessage> setToAddress() {
		return mimeMessage -> {
			if (!Objects.isNull(emailInfo.getToList()) && !emailInfo.getToList().isEmpty()) {
				try {
					mimeMessage.setRecipients(Message.RecipientType.TO, emailInfo.getToList().stream().map(to -> {
						try {
							return new InternetAddress(to);
						} catch (AddressException e) {
							throw new RuntimeException("Could not resolve to address");
						}
					}).toArray(InternetAddress[]::new));
				} catch (MessagingException e) {
					throw new RuntimeException(
							"Could not set to address in message " + emailInfo.getToList().toString());
				}
			}
			return mimeMessage;
		};
	}

	private Function<MimeMessage, MimeMessage> setCcAddress() {
		return mimeMessage -> {
			if (!Objects.isNull(emailInfo.getToList()) && !emailInfo.getCcList().isEmpty()) {
				try {
					mimeMessage.setRecipients(Message.RecipientType.CC, emailInfo.getCcList().stream().map(to -> {
						try {
							return new InternetAddress(to);
						} catch (AddressException e) {
							throw new RuntimeException("Could not resolve cc address");
						}
					}).toArray(InternetAddress[]::new));
				} catch (MessagingException e) {
					throw new RuntimeException(
							"Could not set cc address in message " + emailInfo.getCcList().toString());
				}
			}
			return mimeMessage;
		};
	}

}

I have defined several methods to set to email addresses, cc email addresses, subject, etc.

Usage Example

Here is a class that shows how to send plain email as well as how to send attachment in the email:

public class App {

	public static void main(String[] args) {
		// Email config
		Properties emailConfig = new Properties();
		emailConfig.put("mail.smtp.user", "smtp username");
		emailConfig.put("mail.smtp.host", "smtp host");
		emailConfig.put("mail.smtp.auth", false);
		emailConfig.put("mail.smtp.starttls.enable", false);

		// Email Info
		EmailInfo emailInfo = new EmailInfo("email@email.com", Arrays.asList("email1@email.com", "email2@email.com"),
				Arrays.asList("email1@email.com", "email2@email.com"), "Subject");

		// Sending simple email
		BulkEmailSender bulkEmailSender = new BulkEmailSender(emailInfo, emailConfig);
		MimeMessage mimeMessage = bulkEmailSender.getMimeMessage();
		Multipart multipart = new MimeMultipart();
		BodyPart bodyPart = new MimeBodyPart();
		try {
			bodyPart.setContent("Please find the email regarding ....", "text/html;charset=utf-8");
			multipart.addBodyPart(bodyPart);
			mimeMessage.setContent(multipart);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		bulkEmailSender.sendEmail(mimeMessage);

		// Sending email with attachment
		BulkEmailSender bulkEmailSender2 = new BulkEmailSender(emailInfo, emailConfig);
		MimeMessage mimeMessage2 = bulkEmailSender2.getMimeMessage();
		Multipart multipart2 = new MimeMultipart();
		BodyPart bodyPart2 = new MimeBodyPart();
		MimeBodyPart attachPart = new MimeBodyPart();
		File attachment = new File("test.txt");
		try {
			bodyPart.setContent("Please find the attachment in the email regarding ....", "text/html;charset=utf-8");
			multipart2.addBodyPart(bodyPart2);
			attachPart.setFileName(attachment.getName());
			attachPart.attachFile(attachment);
			multipart2.addBodyPart(attachPart);
			mimeMessage2.setContent(multipart2);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		bulkEmailSender.sendEmail(mimeMessage2);
	}

}

Make sure you replaced the email addresses, subject and message according to your requirements.

Source Code

Download

2 thoughts on “Send Bulk Emails Using Java

  1. I won’t make such a project that will send bulk emails from a web app using Spring, JavaScript, and Java. I want to upload an email list by drag & drop and set up the necessary descriptions of mail from the front end side and attachment with scheduler after click send button mail will go to the given recipients from the bulk upload. Is there any example of this project or tutorial?

  2. Hi,

    Thank you for sharing the above code. I’m very new to java coding. Would like to implement the above into a simple Maven project I’m currently working on where I can allow administrator to send bulk email to user by retrieving the user’s emails from MySQL database.

    Would you be able to advise on how I should edit the Java class code to include connection to MySQL to retrieve the emails as well as the jsp page to allow administrator to click a button to send bulk email or single email to a user?

    I appreciate your help.

Leave a Reply

Your email address will not be published. Required fields are marked *