/*
//GMailer - Felix Source Code
//Project Name: GMailer
//Developed by: Ashok
//Developed for: AMO
//Home Page: http://www.ecerocks.com/
//Project Completed: 02 May, 2010
//IDE USED: None
//Executable JAR: Eclipse IDE
//External JAR's: mail.jar, activation.jar
//Status: Completed and Deployed Successfully
*/
package FelixMail;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.regex.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;

public class FelixMailAttachment extends JFrame implements ActionListener, WindowListener, FocusListener
{	
	private static final long serialVersionUID = 1L;
	String d_email;
	String d_password;
	String filename=null;

    JLabel label_to,label_subject,label_body,label_username,label_password,label_gmailcom,label_smtp,label_port,label_felix,label_info, label_head, label_attachment, label_attachmentName;
    JTextField t_to,t_subject,t_username,t_smtp,t_port;
	JPasswordField t_password;
    JTextArea t_body;
    JButton btn_send,btn_quit,btn_reset,btn_defaults, btn_attach;
	JScrollPane scrollPane;

    public FelixMailAttachment()
    {	
        label_head=new JLabel("GMAILER - FELIX");
		label_head.setForeground(Color.blue);
		label_head.setFont(new Font("Serif", Font.BOLD, 15));
        label_to=new JLabel(" TO : ");
        label_subject=new JLabel(" SUBJECT : ");
        label_attachment=new JLabel(" ATTACH FILES : ");
        label_attachmentName=new JLabel("");
        label_body=new JLabel(" E-Mail BODY : ");
        label_username=new JLabel(" GMAIL USERNAME : ");
        label_password=new JLabel(" PASSWORD             : ");
        label_gmailcom=new JLabel("@gmail.com");
        label_smtp=new JLabel("SMTP Address : ");
        label_port=new JLabel(" PORT NUMBER : ");
        label_felix=new JLabel("© Ashok Felix (www.ecerocks.com): AMO");
        label_info=new JLabel(" Enter Gmail Username,Password,To,Subject and Body - Click Send ");
        btn_send=new JButton(" SEND MAIL");
        btn_quit=new JButton(" QUIT ");
        btn_reset=new JButton(" RESET ");
        btn_defaults=new JButton(" DEFAULTS ");
        btn_attach=new JButton("ATTACH FILE");
            
        t_to=new JTextField(40);
		t_to.setText("DestinationMail@dummmyMail.com");
        t_subject=new JTextField(50);
		t_subject.setText("Hi, there...");
        t_username=new JTextField(20);
		t_username.setText("www.ecerocks.com");
        t_body=new JTextArea(5,20);
		t_body.setText("Write the content of your mail here....");
        t_password=new JPasswordField(20);
		t_password.setEchoChar('$');
		t_password.setText("011235813");
        t_port=new JTextField(5);
		t_port.setText("465");
        t_smtp=new JTextField(20);
		t_smtp.setText("smtp.gmail.com");
		scrollPane = new JScrollPane(t_body);
     
        
	setLayout(null);
    
		label_head.setBounds(180,5,300,20);	
		label_username.setBounds(70,30,120,20);	
		label_password.setBounds(70,60,120,20);
		t_username.setBounds(200,30,120,20);	
		label_gmailcom.setBounds(325,30,120,20);
		t_password.setBounds(200,60,120,20);

		label_to.setBounds(87,100,40,20);
		t_to.setBounds(130,100,300,20);

	    label_subject.setBounds(50,130,100,20);
		t_subject.setBounds(130,130,300,20);

	    label_attachment.setBounds(50,160,100,20);
		label_attachmentName.setBounds(150,160,300,20);
		btn_attach.setBounds(330,160,110,20);

		label_body.setBounds(38,185,100,50);
		scrollPane.setBounds(130,205,340,300);

		btn_send.setBounds(40,515,100,30);
		btn_reset.setBounds(150,515,100,30);
		btn_defaults.setBounds(260,515,100,30);
		btn_quit.setBounds(370,515,100,30);

		label_smtp.setBounds(40,560,100,20);
		t_smtp.setBounds(137,560,150,20);
		label_port.setBounds(300,560,100,20);
		t_port.setBounds(400,560,50,20);

		label_felix.setBounds(150,600,300,20);
		label_info.setBounds(10,620,500,20);

		add(label_username);
        add(label_password);
		add(t_username);
		add(t_password);
        add(label_gmailcom);
		add(label_to);
		add(t_to);
        add(label_subject);
        add(t_subject); 
        add(label_attachment);
        add(label_attachmentName);
        add(btn_attach); 
        add(label_body);
		add(scrollPane);
        add(btn_send);
        add(btn_quit);
        add(btn_reset);
        add(btn_defaults);
        add(label_smtp);
        add(t_smtp);
        add(label_port);
        add(t_port);
        add(label_felix);
        add(label_info);
        add(label_head);


		btn_send.addActionListener(this);
		btn_quit.addActionListener(this);
		btn_reset.addActionListener(this);
		btn_defaults.addActionListener(this);
		btn_attach.addActionListener(this);
		this.addWindowListener(this);
		t_to.addFocusListener(this);
		t_subject.addFocusListener(this);
		t_username.addFocusListener(this);
		t_smtp.addFocusListener(this);
		t_port.addFocusListener(this);
		t_password.addFocusListener(this);
		t_body.addFocusListener(this);


        setSize(500,670);
        setVisible(true);
		setResizable(false);
		setTitle("Gmailer - Felix");
		this.setDefaultCloseOperation ( JFrame.DO_NOTHING_ON_CLOSE );

}

	public void actionPerformed(ActionEvent ae){
		if(ae.getSource()==btn_send){
			Cursor hourglasscursor = new Cursor(Cursor.WAIT_CURSOR);
			setCursor(hourglasscursor);
			label_info.setText("Sending Mail. Please wait for a FEW Moments");	
			//System.out.println("Send Button Clicked");
			d_email=t_username.getText()+label_gmailcom.getText();
			char[] pwd=t_password.getPassword();
			d_password=new String(pwd);
			String m_to=t_to.getText();
			String m_subject=t_subject.getText();
			String m_text=t_body.getText();
			String d_host=t_smtp.getText();
			String d_port=t_port.getText();
			//Email Validation Start
					Pattern ptrn = Pattern.compile(".+@.+\\.[a-z]+");
					Matcher m = ptrn.matcher(m_to);
					boolean validEmail = m.matches();
					System.out.println(validEmail);
			//Email Validation End

					if(m_to.equals("") || m_to.equals("DestinationMail@dummmyMail.com")){
						JOptionPane.showMessageDialog(this,"Enter Valid Recipient E-Mail Address");
						t_to.requestFocus();
					}
					else if(!validEmail){
						JOptionPane.showMessageDialog(this,"Invalid Email. Enter Correct E-Mail Format");
						t_to.requestFocus();
					}
					else if(m_subject.equals("")){
						JOptionPane.showMessageDialog(this,"Enter Subject for E-Mail");
						t_subject.requestFocus();
					}
					else if(d_host.equals("")){
						JOptionPane.showMessageDialog(this,"Enter Valid SMTP Address (smtp.gmail.com)");
						t_smtp.requestFocus();
					}
					else if(d_port.equals("")){
						JOptionPane.showMessageDialog(this,"Enter Valid Port Number (465)");
						t_port.requestFocus();
					}
					else if(m_text.equals("")){
						JOptionPane.showMessageDialog(this,"Enter Body Content For Email");
						t_body.requestFocus();
					}
					else{
						//System.out.println(d_email+" "+d_password+" "+m_to+" "+m_subject+" "+m_text+" "+d_host+" "+d_port);
						//Mail Sending Code Start
								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");
						 
								try
								{
									Authenticator auth = new SMTPAuthenticator();
									Session session = Session.getInstance(props, auth);
									//session.setDebug(true);
						 
									MimeMessage msg = new MimeMessage(session);
									//msg.setText(m_text);

										      // create and fill the first message part
											  MimeBodyPart mbp1 = new MimeBodyPart();
											  mbp1.setText(m_text);

											  // create the Multipart and add its parts to it											  
											  Multipart mp = new MimeMultipart();
											  mp.addBodyPart(mbp1);


											  //File Attach Conditional Code
											  if(filename!=null){
												  // create the second message part
												  MimeBodyPart mbp2 = new MimeBodyPart();

												  // attach the file to the message
												  FileDataSource fds = new FileDataSource(filename);
												  mbp2.setDataHandler(new DataHandler(fds));
												  mbp2.setFileName(fds.getName());

												  mp.addBodyPart(mbp2);
											  }
///

											  // add the Multipart to the message
											  msg.setContent(mp);

											  // set the Date: header
											  msg.setSentDate(new Date());


									msg.setSubject(m_subject);
									//msg.setFrom(new InternetAddress("abc@gmail.com"));
									msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
									Transport.send(msg);
									System.out.println("success");
									label_info.setText("E-Mail Sent Successfully");
									Cursor normalcursor = new Cursor(Cursor.DEFAULT_CURSOR);
									setCursor(normalcursor);
									JOptionPane.showMessageDialog(this,"Message Sent Successfully to "+m_to);
								}
								catch (Exception mex)
								{
									JOptionPane.showMessageDialog(this,"Error Sending E-Mail: \n"+mex);
									mex.printStackTrace();
								}
						//Mail Sending Code End
					}//Validation Conditions
		}//Send Button End
		else if(ae.getSource()==btn_quit){
			System.out.println("Quit Button Clicked");
			label_info.setText("Wanna Quit? Confirm...");
			int confirm=JOptionPane.showConfirmDialog(this,"Do you want to Quit?");
				if(confirm==0){
					System.exit( 0 );
				}
				if(confirm==1){
					label_info.setText(" Wow, you decided to stick around then. Enjoy :) ");
				}
		}
		else if(ae.getSource()==btn_reset){
			label_info.setText("Reset");
			//System.out.println("Reset Button Clicked");
			t_to.setText("");
			t_subject.setText("");
			t_body.setText("");
			t_smtp.setText("smtp.gmail.com");
			t_port.setText("465");
			label_info.setText("All Fields Reset");
			JOptionPane.showMessageDialog(this,"All Fields Reset");
		}
		else if(ae.getSource()==btn_defaults){
			//System.out.println("Default Button Clicked");
			t_username.setText("www.ecerocks.com");
			t_password.setText("011235813");
			t_smtp.setText("smtp.gmail.com");
			t_port.setText("465");
			label_info.setText("Default Values Loaded");
			JOptionPane.showMessageDialog(this,"Default Values Loaded");

		}
		else if(ae.getSource()==btn_attach){
			//System.out.println("Default Button Clicked");
			JFileChooser chooser=new JFileChooser();
			int returnVal=chooser.showOpenDialog(this);
			if(returnVal == JFileChooser.APPROVE_OPTION) {
			   label_attachmentName.setText(chooser.getSelectedFile().getName());
			   File selectedFile = chooser.getSelectedFile();
			   this.filename=selectedFile.getPath();
			   //System.out.println("You chose to open this file: " +	chooser.getSelectedFile().getName());
			   JOptionPane.showMessageDialog(this,"File " +this.filename+" Attached Successfully");
			}
		}
	}
	
			private class SMTPAuthenticator extends javax.mail.Authenticator{
				public javax.mail.PasswordAuthentication getPasswordAuthentication(){
					return new javax.mail.PasswordAuthentication(d_email, d_password);
				}
			}

//WindowListener Interface Methods Start
	public void	windowActivated(WindowEvent e){	}
	public void	windowClosed(WindowEvent e){}
	public void	windowClosing(WindowEvent e){
		//System.out.println("Window Closing");
		int confirm=JOptionPane.showConfirmDialog(this,"Do you want to Quit?");
		if(confirm==0){
			System.exit( 0 );
		}
		if(confirm==1){
			label_info.setText(" Wow, you decided to stick around then. Enjoy :) ");
		}
	}
	public void	windowDeactivated(WindowEvent e){
			//label_info.setText(" Got Some Other Work? Or got to copy paste something else here?");
	}
	public void	windowDeiconified(WindowEvent e){
			label_info.setText(" Window is Deiconified. I'm not sure what that means.. :) ");
	}
	public void	windowIconified(WindowEvent e){
			label_info.setText(" Window Iconified. Don't worry, I don't know what that means :) ");
	}
	public void	windowOpened(WindowEvent e){} 
//WindowListener Interface Methods End


//FocusListener Interface Methods Start
	public void	focusGained(FocusEvent e){
		if((Component)t_username==e.getComponent()){
			label_info.setText(" Enter Your Gmail Username ");
		}
		else if((Component)t_password==e.getComponent()){
			label_info.setText(" Enter Password - Don't worry, its not stored anywhere ");
		}
		else if((Component)t_to==e.getComponent()){
			label_info.setText(" Enter the E-mail address of the person to whom you want to send this mail ");
		}
		else if((Component)t_subject==e.getComponent()){
			label_info.setText(" Enter a brief Subject about the purpose of this E-Mail ");
		}
		else if((Component)t_body==e.getComponent()){
			label_info.setText(" Enter Content for this E-Mail. And don't be a skinflint");
		}
		else if((Component)t_smtp==e.getComponent()){
			label_info.setText(" Enter a Valid SMTP address - Most problems arise from a wrong SMTP ");
		}
		else if((Component)t_port==e.getComponent()){
			label_info.setText(" Enter a Port Number for the respective SMTP (default: 25) ");
		}
		if((Component)t_body!=e.getComponent()){
			JTextField textField = (JTextField)e.getComponent();
			textField.selectAll();
		}
		else if((Component)t_body==e.getComponent()){
			JTextArea textArea = (JTextArea)e.getComponent();
			textArea.selectAll();
		}
	}
	public void	focusLost(FocusEvent e){}

//FocusListener Interface Methods End

    public static void main(String a[]){
		new FelixMailAttachment();
    }
}
