import java.awt.*;
import java.awt.event.*;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;
import java.io.*;


public class SendMail {
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		JFrame frame = new MailTestFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.show();
	}
}

class MailTestFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	public MailTestFrame() {
		
		//Se arma la interfaz grafica
		setSize(WIDTH, HEIGHT);
		setTitle("MailTest");
		getContentPane().setLayout(new GridBagLayout());

		//Layout usado
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0;
		gbc.weighty = 0;

		//Campo "From"
		gbc.weightx = 0;
		add(new JLabel("    From :"), gbc, 0, 0, 1, 1);
		gbc.weightx = 100;
		from = new JTextField(20);
		add(from, gbc, 1, 0, 1, 1);
		
		//Campo "Pass"
		gbc.weightx = 0;
		add(new JLabel("    Pass :"), gbc, 0, 1, 1, 1);
		gbc.weightx = 100;
		pass = new JPasswordField(20);
		add(pass, gbc, 1, 1, 1, 1);

		//Campo "To"
		gbc.weightx = 0;
		add(new JLabel("    To :"), gbc, 0, 2, 1, 1);
		gbc.weightx = 100;
		to = new JTextField(20);
		add(to, gbc, 1, 2, 1, 1);

		//Campo "SMTP server"
		gbc.weightx = 0;
		add(new JLabel("    SMTP server :"), gbc, 0, 3, 1, 1);
		gbc.weightx = 100;
		smtpServer = new JTextField(20);
		add(smtpServer, gbc, 1, 3, 1, 1);

		//Campo "Port"
		gbc.weightx = 0;
		add(new JLabel("    Port :"), gbc, 0, 4, 1, 1);
		gbc.weightx = 100;
		port = new JTextField(20);
		add(port, gbc, 1, 4, 1, 1);

		//Campo para escribir el contenido del email
		gbc.fill = GridBagConstraints.BOTH;
		gbc.weighty = 100;
		message = new JTextArea();
		add(new JScrollPane(message), gbc, 0, 5, 2, 1);

		//Campo para comunicar el estado de la coneccion y envio del email
		communication = new JTextArea();
		communication.setBackground(Color.LIGHT_GRAY);
		add(new JScrollPane(communication), gbc, 0, 6, 2, 1);
		
		//Se redirecciona la salida estandar del sistema
		//al JTextField communication
		PrintStream out = System.out;
		System.setOut(new TextAreaPrintStream(communication, out));
		System.out.println("**WELCOME");

		//Boton de envio
		gbc.weighty = 0;
		JButton sendButton = new JButton("Send");
		
		//ActionListener para el boton de envio
		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				new Thread() {
					public void run() {
						try {
							
							//Se prepara y envia el email
							sendMail();
							
							//Se espera 1 segundo, para no enviar
							//muchos email seguidos si se sigue
							//apretando el boton "Send"
							Thread.sleep(1000);
							
						} catch (InterruptedException e) {
							e.printStackTrace();
						} catch (MessagingException e) {
							e.printStackTrace();
						}
					}
				}.start();
			}
		});
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(sendButton);
		
		//se agrega el boton a la interfaz grafica
		add(buttonPanel, gbc, 0, 7, 2, 1);
	}

	//inserta las componentes en la interfaz grafica
	private void add(Component c, GridBagConstraints gbc, int x, int y, int w,
			int h) {
		gbc.gridx = x;
		gbc.gridy = y;
		gbc.gridwidth = w;
		gbc.gridheight = h;
		getContentPane().add(c, gbc);
	}

	//prepara y envia el email segun los datos ingresados en la interfaz grafica
	public void sendMail() throws MessagingException, InterruptedException {

		//propiedades para leer la configuracion
		Properties props = new Properties();
		
		//Se agregan las propiedades para enviar el email
		props.put("mail.transport.protocol", "smtps");//protocolo
		props.put("mail.smtps.host", smtpServer.getText());//el servidor smtp
		props.put("mail.smtps.auth", "true");// coneccion segura ssl: true
		// props.put("mail.smtps.quitwait", "false");

		//Se agregan las propiedades anteriores a la sesion de correo
		Session mailSession = Session.getDefaultInstance(props);
		mailSession.setDebug(true);
		
		//Se prepara el transporte para el envio
		Transport transport = mailSession.getTransport();

		//Se agrega el contenido del email
		MimeMessage message = new MimeMessage(mailSession);//tipo de email
		message.setSubject("Tarea 4 - elo330 - Rodrigo Melo, Danilo Bize");//Subject o titulo
		message.setContent(this.message.getText(), "text/plain");// El contenido en texto plano

		// se agrega al receptor del email
		message.addRecipient(
				Message.RecipientType.TO, 
				new InternetAddress(to.getText()));

		//se conecta al servidor smtp
		transport.connect(
				smtpServer.getText(), 
				Integer.parseInt(port.getText()), 
				from.getText(), 
				pass.getText());

		//envia el email
		transport.sendMessage(
				message, 
				message.getRecipients(Message.RecipientType.TO));
		
		//cierra la coneccion y libera los recusos usados
		transport.close();
		
		//se avisa al usuario que el email fue correctamente enviado (aparece en JTextField communication)
		System.out.println("**THE E-MAIL HAS BEEN SENT SUCCESSFULLY");
	}

	private JTextField from;
	private JTextField pass;
	private JTextField to;
	private JTextField smtpServer;
	private JTextField port;
	private JTextArea message;
	private JTextArea communication;

	public static final int WIDTH = 600;
	public static final int HEIGHT = 600;
}
