Monday, May 12, 2008

New File Notifier

/* This code scans a particular directory and sends an email if a new file is added / downloaded to that same directory */

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.mail.internet.MimeMessage;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Properties;
import javax.mail.Message;
import java.util.Date;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import java.io.File;
import java.util.ArrayList;
public class FilesLister extends TimerTask
{
static String d_email = "email@gmail.com",
d_password = "",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "jawaharlal@gmail.com";

static Timer timer = new Timer();
ArrayList existingFiles = new ArrayList();
boolean firstTime = true;


public static void main(String[] args) {
//d_password=args[0];
TimerTask tt = new FilesLister();
timer.schedule(tt, 0, 5*60 * 1000);
}

public void sendMail(String str) {
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
//props.put("mail.smtp.debug", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

SecurityManager security = System.getSecurityManager();

try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
//session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(str);
msg.setSubject(str);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport.send(msg);
}
catch (Exception mex)
{
mex.printStackTrace();
}

}

public void run() {
System.out.println("in run ... " + new Date());
File dir = new File("D:\\Muvi");

String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i // Get filename of file or directory
String filename = children[i];
if (!(existingFiles.contains(filename)))
{
if (!firstTime)
{
sendMail("New file name : " + filename + " downloaded at : " + new Date());
}
existingFiles.add(filename);
}
//System.out.println(i + ". " + filename);
}
}
firstTime = false;
}

private class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(d_email, d_password);
}
}



}

No comments: