Note:
1) Please include all the Jar File that is needed for this import including Java Mail API Jar.
2) This Code can be used in web application and console application.
package com.test.util;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.TransportAdapter;
import javax.mail.event.TransportEvent;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* Mail utility.Sends mail.
*
* @author agrajm
*
*/
public class Mailer {
public final static String TEXT = "text/plain";
public final static String HTML = "text/html";
public final static String MULTIPART = "multipart/alternative";
private String encoding;
private String subject;
private String mailMessage;
private String sender;
private String mailType;
private List toList;
private List ccList;
private List bccList;
private String fileName;
private byte[] fileContent;
private String fileType;
private Session mailSession;
/**
* Constructor
*
* @param subject
* @param bodyText
* @param sender
* @param mailType
* @param toList
* @param ccList
* @param bccList
* @param fileName
* @param fileContent
*/
public Mailer(String subject, String bodyText, String sender,
String mailType, List toList, List ccList,
List bccList, String fileName, byte[] fileContent) {
this.subject = subject;
this.mailMessage = bodyText;
this.sender = sender;
this.mailType = mailType;
this.toList = toList;
this.ccList = ccList;
this.bccList = bccList;
this.fileName = fileName;
this.fileContent = fileContent;
}
/**
* Default Constructor
*/
public Mailer() {
this.subject = null;
this.mailMessage = null;
this.sender = "prodcat.support@st.com";
this.toList = new ArrayList();
this.ccList = new ArrayList();
this.bccList = new ArrayList();
this.fileName = null;
this.fileContent = null;
this.mailType = HTML;
}
/**
* Intializes mail session for sending mail
*/
private void initalizeMailSession()
{
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.smtp.host", PcIntPropertyFileValues.MAIL_SMTP_HOST);
mailSession = Session.getInstance(props);
/*mailSession.setDebug(true);
mailSession.setDebugOut(System.err);*/
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBodyText() {
return mailMessage;
}
public void setBodyText(String bodyText) {
this.mailMessage = bodyText;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getMailType() {
return mailType;
}
public void setMailType(String mailType) {
this.mailType = mailType;
}
public List getToList() {
return toList;
}
public void setToList(List toList) {
this.toList = toList;
}
public List getCcList() {
return ccList;
}
public void setCcList(List ccList) {
this.ccList = ccList;
}
public List getBccList() {
return bccList;
}
public void setBccList(List bccList) {
this.bccList = bccList;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getFileContent() {
return fileContent;
}
public void setFileContent(byte[] fileContent) {
this.fileContent = fileContent;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Send mail to ToList,CcList,BccList
*
* @throws Exception
*/
public void sendMail() throws Exception
{
// Send mail for current object
if(mailSession==null)
initalizeMailSession();
MimeMessage mailMsg = new MimeMessage(mailSession);
InternetAddress recipient=null;
if(toList==null&&ccList==null&&bccList==null)
{
throw new Exception("No Recipents Found");
}
if(toList!=null)
{
for(int i=0; i<toList.size(); i++)
{
String toAddress = (String) toList.get(i);
recipient=new InternetAddress(toAddress);
mailMsg.addRecipient(javax.mail.Message.RecipientType.TO, recipient);
}
}
if(ccList!=null)
{
for(int i=0; i<ccList.size(); i++)
{
String toAddress = (String) ccList.get(i);
recipient=new InternetAddress(toAddress);
mailMsg.addRecipient(javax.mail.Message.RecipientType.CC, recipient);
}
}
if(bccList!=null)
{
for(int i=0; i<bccList.size(); i++)
{
String toAddress = (String) bccList.get(i);
recipient=new InternetAddress(toAddress);
mailMsg.addRecipient(javax.mail.Message.RecipientType.BCC, recipient);
}
}
if(sender==null)
throw new Exception("Sender not found");
InternetAddress sender=new InternetAddress(this.sender);
mailMsg.setFrom(sender);
if(encoding!=null)
{
mailMsg.setSubject(subject,encoding);
mailType += ";charset=" + encoding;
}
else
mailMsg.setSubject(subject);
MimeMultipart mult = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mailMessage, mailType);
mult.addBodyPart(messagePart);
String filename = fileName;
if(filename != null) {
MimeBodyPart filePart = new MimeBodyPart();
ByteDataSource bds = new ByteDataSource(fileContent, fileType);
filePart.setDataHandler(new DataHandler(bds));
filePart.setFileName(filename);
mult.addBodyPart(filePart);
}
mailMsg.setContent(mult);
Transport.send(mailMsg);
System.err.println("Receivers List: "+ mailMsg.getRecipients(javax.mail.Message.RecipientType.TO));
System.err.println("Mail send..");
}
/*
public String convertToString(Address[] addresses){
StringBuilder sbuffer = new StringBuilder();
for(int i=0; i<addresses.length; i++){
sbuffer.append(addresses[i]).append(", ");
}
sbuffer.delete(sbuffer.lastIndexOf(","), sbuffer.length());
return sbuffer.toString();
}*/
/**
* Prepares list of mails of admins from list of Admin objects
*
* @param adminList
* @return
public List getEmailListFromAdmins(List adminList)
{
if(adminList==null)
return null;
List adminMails=new ArrayList();
for(int i=0; i<adminList.size(); i++)
{
UserInfo admin = (UserInfo)adminList.get(i);
if(admin!=null)
adminMails.add(admin.getEmail());
}
return adminMails;
}
*/
}
class TransportHandler extends TransportAdapter {
public void messageDelivered(TransportEvent e) {
StringBuffer errMsg=new StringBuffer("Mail delivered[");
Address[] adds=e.getValidSentAddresses();
for(int i=0;i<adds.length;i++)
errMsg.append(adds[i].toString());
errMsg.append("] At " +java.util.Calendar.getInstance().getTime().toString());
System.err.println(errMsg);
}
public void messageNotDelivered(TransportEvent e)
{
StringBuffer errMsg=new StringBuffer("Mail NOT delivered[");
Address[] adds=e.getValidUnsentAddresses();
for(int i=0;i<adds.length;i++)
errMsg.append(adds[i].toString());
errMsg.append("].");
System.err.println(errMsg);
}
public void messagePartiallyDelivered(TransportEvent e)
{
System.err.println("Mail partially delivered.");
}
}
class ByteDataSource implements DataSource {
private String type;
private byte[] data;
public ByteDataSource(byte[] data, String type) {
this.data = data;
this.type = type;
}
public InputStream getInputStream() throws IOException {
if (data == null) throw new IOException("Null data");
return new ByteArrayInputStream(data);
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("ByteDataSource");
}
public String getContentType() {
return type;
}
public String getName() {
return "ByteDataSource";
}
}