package au.edu.mq.comp.common.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;
import org.apache.commons.io.*;
import com.sun.mail.smtp.SMTPTransport;
public class Mailman extends Object
{
private static String decodeName(String name) throws Exception
{
if (name == null || name.length() == 0)
{
return "unknown";
}
String ret = java.net.URLDecoder.decode(name, "UTF-8");
// also check for a few other things in the string:
ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
ret = ret.replaceAll("\\?=", "");
ret = ret.replaceAll("=20", " ");
return ret;
}
private static int writeAttachmentFile(File saveFile, Part part) throws Exception
{
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile));
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while ((ret = is.read(buff)) > 0)
{
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
public static List<Email> receiveMails(Configuration config) throws Exception
{
List<Email> emails = new ArrayList<Email>();
// Get the session
Session session = Session.getInstance(config, null);
String host = config.getProperty("custom.hostURL");
String userName = config.getProperty("custom.userName");
String password = config.getProperty("custom.password");
String pathToAttachmentDirecotry = config.getProperty("custom.pathToAttachmentDirectory");
String storeString = config.getProperty("mail.store.protocol");
Store store = session.getStore(storeString);
store.connect(host, userName, password);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
try
{
// Get directory listing
Message messages[] = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
Email email = new Email();
// from
email.from = messages[i].getFrom()[0].toString();
// to list
Address[] toArray = messages[i] .getRecipients(Message.RecipientType.TO);
for (Address to : toArray)
{
email.to.add(to.toString());
}
// cc list
Address[] ccArray = null;
try
{
ccArray = messages[i] .getRecipients(Message.RecipientType.CC);
}
catch (Exception e)
{
ccArray = null;
}
if (ccArray != null)
{
for (Address c : ccArray)
{
email.cc.add(c.toString());
}
}
// subject
email.subject = messages[i].getSubject();
// received date
if (messages[i].getReceivedDate() != null)
{
email.received = messages[i].getReceivedDate();
}
else
{
email.received = new Date();
}
// body and attachments
email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String)
{
email.body = (String) content;
}
else if (content instanceof Multipart)
{
Multipart mp = (Multipart) content;
for (int j = 0; j < mp.getCount(); j++)
{
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain"))
{
// Plain
email.body += (String) mbp.getContent();
}
}
else if ((disposition != null) && (0 == disposition.compareToIgnoreCase(Part.ATTACHMENT) ||
0 == disposition.compareToIgnoreCase(Part.INLINE)))
{
// Check if plain
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain"))
{
email.body += (String) mbp.getContent();
}
else
{
Attachment attachment = new Attachment();
attachment.name = FilenameUtils.getName(Mailman.decodeName(part.getFileName()));
File savedir = new File(pathToAttachmentDirecotry);
if(false == savedir.exists())
savedir.mkdirs();
File savefile = new File(pathToAttachmentDirecotry, attachment.name);
attachment.path = savefile.getAbsolutePath();
attachment.size = Mailman.writeAttachmentFile(savefile, part);
email.attachments.add(attachment);
}
}
} // end of multipart for loop
} // end messages for loop
emails.add(email);
// Finally delete the message from the server.
messages[i].setFlag(Flags.Flag.DELETED, true);
}
// Close connection
folder.close(true); // true tells the mail server to expunge deleted messages
store.close();
}
catch (Exception e)
{
folder.close(true); // true tells the mail server to expunge deleted
store.close();
throw e;
}
return emails;
}
public static void sendMail(Configuration config, Email email) throws AddressException, MessagingException
{
Session session = Session.getInstance(config, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(email.from));
for(String destinationAddress : email.to)
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(destinationAddress, false));
//message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.to.get(0), false));
message.setSubject(email.subject);
message.setText(email.body, "utf-8");
message.setSentDate(new Date());
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(email.body);
// Create a multipar message
MimeMultipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// create the attachment part if require
if(email.attachments.size() > 0)
{
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
for(Attachment a : email.attachments)
{
DataSource source = new FileDataSource(a.path);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(a.path);
}
multipart.addBodyPart(attachmentBodyPart);
}
message.setContent(multipart);
SMTPTransport smtp = (SMTPTransport)session.getTransport("smtps");
String userName = config.getProperty("custom.userName");
String password = config.getProperty("custom.password");
smtp.connect("smtp.gmail.com", userName, password);
smtp.sendMessage(message, message.getAllRecipients());
smtp.close();
}
}