package edu.uchicago.cs.java.finalproject.tronscan.lib;

/*
Some SMTP servers require a username and password authentication before you
can use their Server for Sending mail. This is most common with couple
of ISP's who provide SMTP Address to Send Mail.

This Program gives any example on how to do SMTP Authentication
(User and Password verification)

This is a free source code and is provided as it is without any warranties and
it can be used in any your code for free.

Author : Sudhir Ancha
*/

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import java.util.*;
import java.awt.HeadlessException;
import java.io.*;

/*
  To use this program, change values for the following three constants,

    SMTP_HOST_NAME -- Has your SMTP Host Name
    SMTP_AUTH_USER -- Has your SMTP Authentication UserName
    SMTP_AUTH_PWD  -- Has your SMTP Authentication Password

  Next change values for fields

  emailMsgTxt  -- Message Text for the Email
  emailSubjectTxt  -- Subject for email
  emailFromAddress -- Email Address whose name will appears as "from" address

  Next change value for "emailList".
  This String array has List of all Email Addresses to Email Email needs to be sent to.


  Next to run the program, execute it as follows,

  SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();

*/


//modfified to take attachments and use dialog boxes
public class SendMailUsingAuthentication
{

  private static  String strSmtp_host_name;
  private static String strSmpt_auth_user;
  private static String strSmtp_auth_pwd;


  private static  String strFrom;
  private static  String strRecip;

  
  private static  String strBody;
  private static  String strSubject;
  

  private static  String strFilePath;
  private static  String strFileName;
  


  //returns true of everything went ok, otherwise false
  public static boolean sendEmail(String strSmtp_host_name,String strSmpt_auth_user,  String strSmtp_auth_pwd,
		  String strFrom,  String strRecip, String strBody, String strSubject, String strFilePath, String strFileName){

	  try {

		   SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
		   smtpMailSender.postMail( strRecip, strSubject, strBody, strFrom, strFilePath, strFileName);
		   return  true;
	} catch (HeadlessException exp) {
		exp.printStackTrace();
		return false;
		
	} catch (MessagingException exp) {
		// TODO Auto-generated catch block
		exp.printStackTrace();
		return false;
	}
		 
	//return true;
		 
  
	  
  }
  
  
  
  
  //returns true of everything went ok, otherwise false
  //the no-args method is used for testing only
  public static boolean sendEmail(){

	  try {
		  //I've used a dialog box for expediency 
		 //you must get the following values from the config file; data are entered in the config tab
		
		  
		  //you will use variables to set these depending on the quizz name and
		  //calcuated values
		  strBody = "Your quizz score for quizz 051032-02 is 49/50 \n Your percentage correct is 98%";
		  strSubject = "Quizz 051032-02 evaluation";

		  
		//host
		  JLabel lblHost = new JLabel("SMTP host name e.g for yahoo it's \"smtp.mail.yahoo.com\"  --this should be in the config tab");
		  JTextField txtHost = new JTextField("smtp.mail.yahoo.com");
		  
		  //user
		  JLabel lblUser = new JLabel("Email user-name example \"joe.smith\" -- without the @domain.com");
		  JTextField txtUser = new JTextField();
		  
		  //pass
		  JLabel lblPass = new JLabel("Password");
		  JTextField txtPass = new JPasswordField();
		  
		  //from
		  JLabel lblFrom = new JLabel("From email address -- must be a valid email address!");
		  JTextField txtFrom = new JTextField();
		  
		  //recipient
		  JLabel lblRecip = new JLabel("Recipient email address");
		  JTextField txtRecip = new JTextField();

		  
		  
		  //file path
		  JLabel lblPath = new JLabel("Full path of file to be sent inluding file name and file extension");
		  JTextField txtPath = new JTextField(System.getProperty("user.dir") + "/");
		
		  
		  
		  //file name
		  JLabel lblName = new JLabel("name of the file that will appear in inbox, example: gerbera5106202.jpg");
		  JTextField txtName = new JTextField();
		  
		  
		  Object[] objFields = {lblHost, txtHost, lblUser, txtUser, 
				  lblPass, txtPass, lblFrom, txtFrom, lblRecip, txtRecip, lblPath, txtPath, lblName, txtName};
		  
		  
		  int nResult = JOptionPane.showConfirmDialog(null, objFields, "Please fill out fields", JOptionPane.OK_CANCEL_OPTION);

		  if (nResult == JOptionPane.OK_OPTION) {
			  strSmtp_host_name = txtHost.getText();
			  strSmpt_auth_user = txtUser.getText();
		      strSmtp_auth_pwd = txtPass.getText();
		      strFrom = txtFrom.getText();
		      strRecip =  txtRecip.getText();
		      strFilePath = txtPath.getText();
		      strFileName =  txtName.getText();

		  }
		  else {
			  return false;
		  }
		  
		   SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
		   smtpMailSender.postMail( strRecip, strSubject, strBody, strFrom, strFilePath, strFileName);
		   
   
		   return true;
		   
	} catch (HeadlessException exp) {
		exp.printStackTrace();
		return false;
		
	} catch (MessagingException exp) {
		// TODO Auto-generated catch block
		exp.printStackTrace();
		return false;
	}
		 
	
		 
  
	  
  }
  
  
  public static void main(String args[]) throws Exception
  {
	        sendEmail();
  }

  public void postMail( String strRecip, String subject,
                            String message , String from, 
                            String strFilePath, String strFileName) throws MessagingException
  {
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", strSmtp_host_name);
     props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);
    MimeMessage mms = 
        new MimeMessage(session);
      mms.setFrom(
        new InternetAddress(strFrom));
      mms.addRecipient(
        Message.RecipientType.TO, 
        new InternetAddress(strRecip));
      mms.setSubject(strSubject);
    
    // create the message part 
    MimeBodyPart mbp = 
      new MimeBodyPart();

    //fill message
    mbp.setText(strBody);

    Multipart mpt = new MimeMultipart();
    mpt.addBodyPart(mbp);

    // Part two is attachment
   // String fileAttachment = "/home/adam/somename.jpg";
   // String strFileName = "somename.jpg";
    
    
    
    mbp = new MimeBodyPart();
    DataSource source = 
      new FileDataSource(strFilePath);
    mbp.setDataHandler(
      new DataHandler(source));
    mbp.setFileName(strFileName);
    mpt.addBodyPart(mbp);

    // Put parts in message
    mms.setContent(mpt);
    mms.setSubject(subject);
    mms.setContent(mpt, "text/plain");
    Transport.send(mms);
 }


/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
 private class SMTPAuthenticator extends javax.mail.Authenticator
{

    public PasswordAuthentication getPasswordAuthentication()
    {
        String strUser = strSmpt_auth_user;
        String strPass = strSmtp_auth_pwd;
        return new PasswordAuthentication(strUser, strPass);
    }
}




}

