Thursday 1 August 2013

Top Most Sending Mail by Java Mail API With Attachment or Without Attachment ?


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";
}
}

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt