/*

PROGRAM THAT SENDS EMAIL TO A HOTMAIL ACCOUNT...

Author: Matthew W. Coan
Date: Sun Mar  4 21:14:45 EST 2018

*/

import java.util.*;
import java.io.*;
import java.net.*;
import javax.mail.*;
import javax.mail.internet.*;
//import sun.misc.Signal;
//import sun.misc.SignalHandler;
 
public class hotmail implements Runnable {
   private Folder inbox = null;
   private String user = null;
   private String password = null;
   private String host = "pop3.live.com";
   private String smtp = "smtp.live.com";
   private String proto = "pop3s";
   private String my_host = "slack.net";
   private Session session = null;
   private Store store = null;
   private ServerSocket svr = null;

   private String getMyIP() {
      try {
         URL url = new URL("http://plain-text-ip.com/");
         Object obj = url.getContent();
         if(obj instanceof String) {
            String s = (String)obj;
            return s;
         }
         else if(obj instanceof InputStream) {
            InputStream in = (InputStream)obj;
            int ch;
            StringBuffer sb = new StringBuffer();
            while((ch = in.read()) != -1) {
               sb.append((char)ch);
            }
            return sb.toString();
         }
      }
      catch(Exception ex) {
         System.err.print("error: " + ex.getMessage() + "\n");
      }
      return "";
   }

   private boolean sendFromHotmail(String from, String pass, String[] to, String subject, String body) {
      boolean ret = false;
      Properties props = System.getProperties();
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", smtp);
      props.put("mail.smtp.user", from);
      props.put("mail.smtp.password", pass);
      props.put("mail.smtp.port", "587");
      props.put("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(props);
      MimeMessage message = new MimeMessage(session);

      try {
         message.setFrom(new InternetAddress(from));
         InternetAddress[] toAddress = new InternetAddress[to.length];

         for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
         }

         for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
         }

         message.setSubject(subject);
         message.setText(body);
         Transport transport = session.getTransport("smtp");
         transport.connect(smtp, from, pass);
         transport.sendMessage(message, message.getAllRecipients());
         transport.close();
         ret = true;
      }
      catch (AddressException ae) {
         System.err.print("bad address...\n");
         System.err.print("error: " + ae.getMessage() + "\n");
      }
      catch (MessagingException me) {
         System.err.print("unable to send address..\n");
         System.err.print("error: " + me.getMessage() + "\n");
      }
      return ret;
   }

   public void process(Socket sock) throws Exception {
      System.out.println("accept: " + sock.getInetAddress().getHostAddress());
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      PrintStream out = new PrintStream(sock.getOutputStream());
      String to=null,subject=null,text="",line=null;

      out.print("220 " + my_host + " " + (new Date().toString()) + "\r\n");
      while((line = br.readLine()) != null) {
         line = line.trim();
         System.out.println(line);
         if(line.startsWith("HELO")) {
            out.print("250 "+my_host+" Hello localhost [127.0.0.1] pleased to meet you\r\n");
         }
         else if(line.startsWith("MAIL FROM: ")) {
            user = line.substring(11);
            out.print("250 2.1.0 Sender ok\r\n");
         }
         else if(line.startsWith("RCPT TO: ")) {
            to = line.substring(9);
            out.print("250 2.1.5 Recipient ok\r\n");
         }
         else if(line.equals("DATA")) {
            out.print("354 Enter mail, end with \".\" on a line by itself\r\n");
            while((line = br.readLine()) != null) {
               line = line.trim();
               if(line.startsWith("Subject: ")) {
                  subject = line.substring(9);
               }
               else if(line.startsWith("From: ")) {
               }
               else if(line.startsWith("To: ")) {
               }
               else if(line.equals(".")) {
                  break;
               }
               else {
                  text += line + "\r\n";
               }
            }
            out.print("250 2.0.0 Message accepted for delivery\r\n");
         }
         else if(line.equals("QUIT")) {
            out.print("221 2.0.0 "+my_host+" closing connection\r\n");
            break;
         }
      }

      Properties pr = new Properties();
      pr.load(new FileInputStream("hotmail.conf"));

      password = pr.getProperty("password");
      host = pr.getProperty("host");//"pop3.live.com";
      smtp = pr.getProperty("smtp");//"smtp.live.com";
      proto = pr.getProperty("proto");//"pop3s";
      my_host = getMyIP();//pr.getProperty("my_host");//"matthewcoan.dsn2go.com";
      user = pr.getProperty("user");//"matthewcoan.dsn2go.com";

      //synchronized(this) {

      Properties props = System.getProperties();
      Session session = Session.getDefaultInstance(props);
      Store store = session.getStore(proto);
      store.connect(host, user, password);
      Folder inbox = store.getFolder("Inbox");
      inbox.open(Folder.READ_ONLY);

      if(!sendFromHotmail(user, password, new String[]{to}, subject, text)) {
         System.out.println("not sent...");
      }
      else {
         System.out.println("sent...");
      }

      inbox.close(true);
      store.close();
      //}

      sock.close();
   }

   public class SMTPThread extends Thread {
      private Socket connection;

      public SMTPThread(Socket connection) {
         this.connection = connection;
      }

      public void run() {
         try {
            process(connection); 
         }
         catch(Exception ex) {
            System.out.println("error: " + ex.getMessage());
         }
      }
   }

   public void run() {
      try {
/*
         Signal.handle(new Signal("INT"), new SignalHandler() {
            public void handle(Signal signal) {
               System.exit(0);
            }
         });
         Signal.handle(new Signal("TERM"), new SignalHandler() {
            public void handle(Signal signal) {
               System.exit(0);
            }
         });
         Signal.handle(new Signal("HUP"), new SignalHandler() {
            public void handle(Signal signal) {
               System.exit(0);
            }
         });
*/

         host = "smtp.live.com";
         user = "matthewcoan1976@hotmail.com";

         System.out.println(">>>hotmail smtp server...");
         System.out.println("version: 1.0.0");
         System.out.println("author: matthewcoan1976@hotmail.com");
         System.out.println();
 
         InetAddress bind_address = InetAddress.getByName("localhost");

         int port = 2600;

         svr = new ServerSocket(port, 1024, bind_address);

         System.out.println("bound and listening on localhost:"+port+"...");

         Socket connection = null;

         while((connection = svr.accept()) != null) {
            try {
               //new SMTPThread(connection).start();
               process(connection);
            }
            catch(Exception ex) {
               System.err.println("error: " + ex.getMessage() + "\n");
            }
         }
      }
      catch(Exception ex) {
         System.err.print("error: " + ex.getMessage() + "\n");
      }
   }

   public static void main(String args[]) {
      hotmail mail = new hotmail();
      mail.run();
   }
}
