Introduction

This tutorial shows how do we send bulk emails at once. This tutorial uses one method sendBulkEmail() which takes three parameters such as ‘subject’ – Email Subject of String type, ’emailToAddresses’ – List of email addresses where email should be sent and ’emailBodyText’ – the message which has to be sent.

When do we 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.

For testing purpose you can also send the email to yourself and after sending the mail, you can open your mailbox, you will find an email has arrived.

Prerequisites

Java 6 or later version, Java Mail API

Example

Now we will create a main class which will send bulk emails to intended recipients.

Step 1. Create a Java project in any Java based IDE

Step 2. Configure the project to use the mail API jar file

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'
}

Step 3. Create a main class which will send mail to multiple recipients.

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

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class BulkEmailSender {

	public static void main(String[] args) {
		// create a list of emails
		List<String> emails = new ArrayList<String>();
		emails.add("[email protected]");
		emails.add("[email protected]");
		emails.add("[email protected]");
		emails.add("[email protected]");
		emails.add("[email protected]");
		
		// email subject
		String subject = "Test Email";
		
		// message which is to be sent
		String message = "Test Email Message";
		
		// send the email to multiple recipients
		sendBulkEmail(subject, emails, message);
	}

	public static void sendBulkEmail(final String subject, final List<String> emailToAddresses,
			final String emailBodyText) {

		// from email address
		final String username = "your email address";

		// make sure you put your correct password
		final String password = "your email password";

		// smtp email server
		final String smtpHost = "your mail smtp server host";

		// We will put some properties for smtp configurations
		Properties props = new Properties();

		// do not change - start
		props.put("mail.smtp.user", "username");
		props.put("mail.smtp.host", smtpHost);
		// props.put("mail.debug", "true");
		props.put("mail.smtp.auth", "true");
		// do not change - end

		// we authentcate using your email and password and on successful
		// we create the session
		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		String emails = null;

		try {
			// we create new message
			Message message = new MimeMessage(session);

			// set the from 'email address'
			message.setFrom(new InternetAddress(username));

			// set email subject
			message.setSubject(subject);

			// set email message
			// this will send html mail to the intended recipients
			// if you do not want to send html mail then you do not need to wrap the message
			// inside html tags
			String content = "<html>\n<body>\n";
			content += emailBodyText + "\n";
			content += "\n";
			content += "</body>\n</html>";
			message.setContent(content, "text/html");

			// form all emails in a comma separated string
			StringBuilder sb = new StringBuilder();

			int i = 0;
			for (String email : emailToAddresses) {
				sb.append(email);
				i++;
				if (emailToAddresses.size() > i) {
					sb.append(", ");
				}
			}

			emails = sb.toString();

			// set 'to email address'
			// you can set also CC or TO for recipient type
			message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(sb.toString()));

			System.out.println("Sending Email to " + emails + " from " + username + " with Subject - " + subject);

			// send the email
			Transport.send(message);

			System.out.println("Email successfully sent to " + emails);
		} catch (MessagingException e) {
			System.out.println("Email sending failed to " + emails);
			System.out.println(e);
		}
	}

}

 Step 4. Run the application.

Source Code

You can download source code.

That’s all. Thanks for reading.

Tags:

3 thoughts on “Send bulk emails using Java

  1. 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.

  2. 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?

Leave a Reply

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