Java program to send mail to list of users (to list of carbon copy as well), with file attachment.

In project development we introduce communication module to communicate with customers, admin, users, and so on. The communication we use can be via mail and SMS functionality (as per the project requirement). Mail Functionality is very common and essential to send notifications, promotions, statements, invitations and so on. The program we creates to send mail should dynamic and easy maintainable so that communication should never cause issues.

Hence I have developed a program to send mail to list of users, a part of ‘To list’ or ‘CC list’ (BCC can also be added), with attachment (optional). This program can be configured with any mail server, just one has to configure it in properties file. Java Mail 1.4 dependency is used for communication helper.

Click here for configuration (host name, port number and authentication) of few mail servers.

Click here for communication helper maven project Github repository.

Note: For describing mail program, properties file is not used howsoever all configurable fields should be in properties file.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V2 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License V2 for more details.
 *
 */
package com.sanjay.communication.helper;

import java.io.File;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * Helper for sending mail to list of users with attachment.
 *
 * @author SANJAY
 * @see for list of mail servers and configuration details: https://sanjaymadnani.wordpress.com/
 */
public class CommunicationHelper {
	/**
	 * USER_ID String email-Id for sending email.
	 */
	private final String USER_ID = "email address";
	/**
	 * USER_PASSWORD String email-Password for sending email.
	 */
	private final String USER_PASSWORD = "password";

	/**
	 * Creates SMTP Session required for sending mail.
	 *
	 * @return Session.
	 */
	private Session getSendMailSession() {
		// Configurable Properties (as per Mail server).
		// SMTP_HOST ex: smtp.gmail.com
		final String SMTP_HOST = "smtp.gmail.com";
		// SMTP_PORT ex: 465 (gmail with SSL authentication), 587 (gmail with StartTLS authentication).
		final String SMTP_PORT = "465";
		// IS_AUTHENTICATION_REQUIRED for most of the mail server authentication is required.
		final String IS_AUTHENTICATION_REQUIRED = "true";
		// IS_STARTTLS_ENABLE ex: gmail & outlook mail can be send via startTLS authentication.
		// all servers don't use startTLS authentication like yahoo mail server don't have this authentication.
		final String IS_STARTTLS_ENABLE = "false";
		// IS_SSL_ENABLE ex: gmail mail can be send either by SSL or by startTLS.
		// For yahoo mail server it is compulsory to use SSL authentication for sending mail.
		final String IS_SSL_ENABLE = "true";

		final String IS_DEBUG = "false";

		Properties props = new Properties();
		props.put("mail.smtp.host", SMTP_HOST);
		props.put("mail.smtp.auth", IS_AUTHENTICATION_REQUIRED);
		props.put("mail.debug", IS_DEBUG);
		props.put("mail.smtp.ssl.enable", IS_SSL_ENABLE);
		props.put("mail.smtp.starttls.enable", IS_STARTTLS_ENABLE);
		props.put("mail.smtp.port", SMTP_PORT);
		if (IS_STARTTLS_ENABLE.equals("false") && IS_SSL_ENABLE.equals("true")) {
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(USER_ID, USER_PASSWORD);
			}
		});
		return session;
	}

	/**
	 * Sends Mail to list of user(to and cc list) with attachment. send mails to list of e-mail ids with list of carbon copy ids via secure socket
	 * layer Authentication. Simple mail Transfer Protocol is used.
	 *
	 * @param toList
	 *            List of email-Ids.
	 * @param ccList
	 *            (Optional) List of email-Ids, can be null.
	 * @param msgSubject
	 *            String subject line of mail.
	 * @param msgBody
	 *            String TEXT/PLAIN or HTML/PLAIN message to deliver.
	 * @param file
	 *            (Optional) File to send as attachment.
	 * @throws MessagingException.
	 */
	public boolean sendMail(List<String> toList, List<String> ccList, String msgSubject, String msgBody, File file) throws MessagingException {
		// Creates MimeMessage by SMTP Session.
		final MimeMessage message = new MimeMessage(this.getSendMailSession());
		message.setFrom(new InternetAddress(USER_ID));
		final Address[] toAddress = new InternetAddress[toList.size()];
		for (int i = 0; i < toAddress.length; i++) {
			toAddress[i] = new InternetAddress(toList.get(i));
		}
		// sets the to list for sending mail.
		message.addRecipients(Message.RecipientType.TO, toAddress);
		if (ccList != null && ccList.size() > 0) {
			final Address[] toCcAddress = new InternetAddress[ccList.size()];
			for (int i = 0; i < toCcAddress.length; i++) {
				toCcAddress[i] = new InternetAddress(ccList.get(i));
			}
			// sets the cc list for sending mail. the same way BCC list can also be added.
			message.addRecipients(Message.RecipientType.CC, toCcAddress);
		}
		final Multipart multipart = new MimeMultipart();
		// Attach a file with mail if present.
		if (file != null) {
			final MimeBodyPart messageBodyPart2 = new MimeBodyPart();
			final DataSource source = new FileDataSource(file);
			messageBodyPart2.setDataHandler(new DataHandler(source));
			messageBodyPart2.setFileName(file.getName());
			multipart.addBodyPart(messageBodyPart2);
		}

		message.setSubject(msgSubject);
		message.setSentDate(new java.util.Date());
		final BodyPart messageBodyPart1 = new MimeBodyPart();
		// Sends the message in html format.
		messageBodyPart1.setContent(msgBody, "text/html");
		multipart.addBodyPart(messageBodyPart1);

		message.setContent(multipart);
		Transport.send(message);
		return true;
	}
}
/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V2 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License V2 for more details.
 *
 */
package com.sanjay.communication.helper;

import static org.junit.Assert.assertTrue;

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

import org.junit.Before;
import org.junit.Test;

/**
 * JUnit test case for testing send mail functionality.
 *
 * @author SANJAY
 * @see CommunicationHelper
 */
public class CommunicationHelperTest {

	private CommunicationHelper communicationHelper;

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		communicationHelper = new CommunicationHelper();
	}

	/**
	 * Test method for
	 * {@link com.sanjay.communication.helper.CommunicationHelper#sendMail(java.util.List, java.util.List, java.lang.String, java.lang.String, java.io.File)}
	 * .
	 *
	 * @throws java.lang.Exception
	 */
	@Test
	public void testSendMail() throws Exception {
		final List<String> toList = new ArrayList<String>();
		toList.add("Your Email address to receive Mail");
		final String msgSubject = "Let's Plan to meet.";
		final String msgBody = "Hi,<br/><b>I think we should plan to meet.</b>";
		assertTrue(communicationHelper.sendMail(toList, null, msgSubject, msgBody, null));
	}

}

List of SMTP Servers with Host Name Port Numbers and Authentication Information.

Default Ports: Server: Authentication: Port:
SMTP Server (Outgoing Messages) Non-Encrypted AUTH 25 (or 587)
  Secure (TLS) StartTLS

587

  Secure (SSL) SSL

465

Googlemail – Gmail Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.gmail.com SSL

465

  smtp.gmail.com StartTLS

587

Outlook.com Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.live.com StartTLS

587

Hotmail Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.live.com SSL

465

Yahoo Mail Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.mail.yahoo.com SSL

465

Yahoo Mail Plus Server: Authentication: Port:
SMTP Server (Outgoing Messages) plus.smtp.mail.yahoo.com SSL

465

Yahoo UK Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.mail.yahoo.co.uk SSL

465

Yahoo Deutschland Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.mail.yahoo.com SSL

465

Yahoo AU/NZ Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.mail.yahoo.com.au SSL

465

AT&T Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.att.yahoo.com SSL

465

NTL @ntlworld.com Server: Authentication: Port:
SMTP Server (Outgoing Messages) smtp.ntlworld.com SSL

465

For more mail server configurations click here.

Advertisements

About Sanjay Madnani

Software Developer.
This entry was posted in Utility & Helper and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s