import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage.RecipientType;
import com.orga.application.vo.EmailVO;
import com.orga.utility.loggers.Logger;
import com.orga.utility.loggers.LoggerFactory;
import com.orga.utility.utils.CommonUtils;
import com.orga.utility.utils.DateUtils;
import com.sun.mail.pop3.POP3SSLStore;
/**
* This Class represents the global
* Email Interaction and pop 3 configuration
* to read the emails..
*
* @version 0.1, 05 Sept 2012 - Base version
*
*/
public class EmailIntegration {
/**
* The logger instance for this class.
*/
private static final Logger LOGGER = LoggerFactory.
getInstance().getLogger(EmailIntegration.class);
/**
* Represent the Mail session object.
*/
private Session session = null;
/**
* Represent the store Object.
*/
private Store store = null;
/**
* Represent the Folder object of mail.
*/
private Folder folder;
private String username, password;
/**
* Closing Folder method
*
* @throws Exception
*/
public void closeFolder() throws Exception {
folder.close(false);
}
/**
* Method to get the Message Count.
*
* @return no of messages<tt>int</tt>.
*
* @throws Exception
*/
public int getMessageCount() throws Exception {
return folder.getMessageCount();
}
/**
* Method to get the unread Message Count.
*
* @return no of messages<tt>int</tt>.
*
* @throws Exception
*/
public int getUnreadMessageCount() throws Exception {
return folder.getUnreadMessageCount();
}
/**
* Method to get the new Message Count.
*
* @return no of messages<tt>int</tt>.
*
* @throws Exception
*/
public int getNewMessageCount() throws Exception {
return folder.getNewMessageCount();
}
public void disconnect() throws Exception {
store.close();
}
public void setUserPass(String username, String password) {
this.username = username;
this.password = password;
}
/**
* Method represent the mail Connection.
*
* @throws Exception throws exception in
* case not able to connect.
*/
public void connect() throws Exception {
try {
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
pop3Props.setProperty("javax.net.ssl.trustStorePassword", "chimera");
pop3Props.setProperty("mail.pop3.ssl.enable", "true");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "", username,
password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
} catch (Exception exception) {
LOGGER.error("Not able to Connect the mail server!!");
exception.printStackTrace();
}
}
/**
* Method to Open the Mail Folder to read and Write.
*
* @param folderName name of the folder to open.
*
* @throws Exception throws exception in
* case not able to connect.
*/
public void openFolder(String folderName) throws Exception {
/*
* Open the Folder
*/
folder = store.getDefaultFolder();
folder = folder.getFolder(folderName);
if (folder == null) {
throw new Exception("Invalid folder");
}
/*
* try to open read/write and if that fails try read-only
*/
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
}
/**
* Method to filter to get the recent and todays mails.
*
* @return an instance of <tt>List<EmailVO></tt>.
*
* @throws MessagingException
* @throws IOException
* @throws ParseException
*/
public List<EmailVO> todaysDateMail() throws MessagingException,
IOException, ParseException {
Date sendDate = null;
Date todaysDate = null;
List<EmailVO> emailList = null;
EmailVO emailVO = null;
int recentMessage = 0;
try {
LOGGER.info("Folder to Scan :" + folder.getName());
LOGGER.info("No of Msg in folder :"
+ folder.getMessageCount());
Message msgs[] = folder.getMessages();
recentMessage = msgs.length;
LOGGER.info("No of Msg in folder :" + recentMessage);
if (recentMessage > 0) {
emailList = new ArrayList<EmailVO>();
for (int i = 0; i < recentMessage; i++) {
Message message = msgs[i];
/*
* Getting the Send Date.
*/
String sdate = DateUtils.convertDateTOString(
message.getSentDate(), "MM/dd/yyyy");
sendDate = DateUtils.convertStringToDate(sdate,
"MM/dd/yyyy");
LOGGER.info("Mail Send date :" + sendDate);
/*
* Getting the Todays Date.
*/
String tdate = DateUtils.convertDateTOString(new Date(),
"MM/dd/yyyy");
todaysDate = DateUtils.convertStringToDate(tdate,
"MM/dd/yyyy");
LOGGER.info("Today date :" + todaysDate);
// date compare between todays Date & mail sent Date.
if (sendDate.compareTo(todaysDate) == 0) {
String bcc = "";
Address[] address;
/*if ((address = message.getRecipients(Message.RecipientType.BCC)) != null) {
for (int j = 0; j < address.length; j++) {
bcc = address[j].toString();
LOGGER.info("BCC: " + bcc);
}
}*/
/* if (message.getRecipients(RecipientType.BCC) != null
&& bcc.contains("bloomberg.interaction@gmail.com")) {*/
emailVO = new EmailVO();
/*
* Setting the Bcc field.
*/
//emailVO.setBcc(bcc);
/*
* Setting the send Date field.
*/
if (sendDate != null) {
LOGGER.info("Sent Date:" + sendDate);
emailVO.setSendDate(sendDate);
}
/*
* Setting the to field.
*/
String to = "";
if ((address = message
.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < address.length; j++) {
to = address[j].toString();
LOGGER.info("TO: " + to);
EmailVO emailVOMul = new EmailVO();
CommonUtils.copyBeanProperties(emailVO, emailVOMul);
if (CommonUtils.isValidObject(emailVOMul)) {
if (to.contains("<")) {
emailVOMul.setTo(to.substring(
to.indexOf("<") + 1,
to.indexOf(">")));
} else {
emailVOMul.setTo(to);
}
}
emailList.add(getEmaiVOObject(message, emailVOMul));
}
}
//}
}// end if date compare
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return emailList;
}
/**
* Method to get the Email VO Objet.
*
* @param message Message class.
*
* @param an instance of <tt>EmailVO</tt>.
*
*/
private EmailVO getEmaiVOObject(Message message, EmailVO emailVO) {
try {
Address[] address;
if ((address = message.getFrom()) != null) {
for (int j = 0; j < address.length; j++) {
String from = address[j].toString();
LOGGER.info("FROM: " + from);
if (CommonUtils.isValidObject(emailVO)) {
if (from.contains("<")) {
emailVO.setFrom(from.substring(
from.indexOf("<") + 1,
from.indexOf(">")));
} else {
emailVO.setFrom(from);
}
}
}
}
if ((address = message
.getRecipients(Message.RecipientType.CC)) != null) {
for (int j = 0; j < address.length; j++) {
String cc = address[j].toString();
LOGGER.info("CC: " + cc);
if (CommonUtils.isValidObject(emailVO))
emailVO.setCc(cc);
}
}
if ((message.getSubject()) != null) {
String subject = message.getSubject();
LOGGER.info("Subject:" + subject);
if (CommonUtils.isValidObject(emailVO))
emailVO.setSubject(subject);
}
System.out
.println("---------------------------------");
// Reading mail body part
String contentType = message.getContentType();
String textMessage = "";
System.out.println("Message Content type:" + contentType);
if (message.isMimeType("multipart/related")) {
System.out.println("multipart/related".toUpperCase());
Multipart mp = (Multipart)message.getContent();
int partsCount = mp.getCount();
for (int k = 0; k < partsCount; k++) {
Part p = mp.getBodyPart(k);
parseMail(p, emailVO);
}
}
if (message.isMimeType("multipart/alternative")) {
System.out.println("multipart/alternative".toUpperCase());
Multipart mp = (Multipart)message.getContent();
int partsCount = mp.getCount();
for (int k = 0; k < partsCount; k++) {
Part p = mp.getBodyPart(k);
parseMail(p, emailVO);
}
}
if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
LOGGER.info("Mail Content type is text/html!");
textMessage = message.getContent() != null ? message
.getContent().toString() : "";
} else if (contentType.contains("multipart")) {
LOGGER.info("Mail Content type is multipart!");
// possibly contains attachments
Multipart multiPart = (Multipart) message
.getContent();
int partCount = multiPart.getCount();
for (int j = 0; j < partCount; j++) {
BodyPart part = multiPart.getBodyPart(j);
if (Part.ATTACHMENT.equalsIgnoreCase(part
.getDisposition())) {
// absolutely an attachment
saveAttachmentToFile(part);
}
}
}
System.out.println("Final Email body :" + emailVO.getMailBody());
} catch (Exception exception) {
exception.printStackTrace();
}
return emailVO;
}
public void parseMail(Part message, EmailVO emailVO) throws Exception
{
System.out.println("parse mail Type:"+ message.getContentType());
if ((message.isMimeType("text/*")) &&
(message.getDisposition() != null && message.getDisposition().equals(Part.INLINE)))
{
System.out.println("Pares mail1:" + (String)message.getContent());
} else if (message.isMimeType("multipart/alternative")) {
Multipart mp = (Multipart)message.getContent();
int partsCount = mp.getCount();
for (int k = 0; k < partsCount; k++) {
Part p = mp.getBodyPart(k);
parseMail(p, emailVO);
}
} else if (message.isMimeType("multipart/related")) {
Multipart mp = (Multipart)message.getContent();
int partsCount = mp.getCount();
for (int k = 0; k < partsCount; k++) {
Part p = mp.getBodyPart(k);
parseMail(p, emailVO);
}
} else if (message.isMimeType("text/plain")) {
LOGGER.info("Mail Content type is text/*!");
System.out.println("Pares mail2:" + (String)message.getContent());
emailVO.setMailBody(message.getContent().toString().replaceAll("\\<.*?>", ""));
}
}
/*
* method use to save the attachment in mail.
*/
private void saveAttachmentToFile(BodyPart part) throws MessagingException,
IOException {
String destFilePath = "/home/sougatd/mailattachments/"
+ part.getFileName();
FileOutputStream output = new FileOutputStream(destFilePath);
InputStream input = part.getInputStream();
byte[] buffer = new byte[input.available()];
int byteRead;
while ((byteRead = input.read(buffer)) != -1) {
output.write(buffer, 0, byteRead);
}
output.close();
}
}
/* Calling the email integration*/EmailIntegration emailIntegration = new EmailIntegration();
emailIntegration.setUserPass("mail@gmail.com", "password");
emailIntegration.connect();
emailIntegration.openFolder("inbox");
int totalMessages = emailIntegration.getMessageCount();
int unreadmessage = emailIntegration.getUnreadMessageCount();
LOGGER.info("Total messages = " + totalMessages);
LOGGER.info("unread messages = " + unreadmessage);
LOGGER.info("-------------------------------");
emailVOList = emailIntegration.todaysDateMail();
emailIntegration.closeFolder();
emailIntegration.disconnect();