// Applet Mail v1.0 - mail.java;

import java.applet.*;
import java.awt.*;
import java.net.*;
import java.io.*;
import java.util.*;
import MAILDIALOG;

public class mail extends Applet
{				  
	MAILDIALOG maildlg;
    String serverHostName = null;
    String toEmail = null;
    int smtpPort = 25;
    Socket socket;
    PrintStream ps;
    DataInputStream dis;
    InetAddress rina;
    InetAddress lina;
   
	public void init()
    {
        this.setBackground(Color.black);
        this.setLayout( new FlowLayout() );
        setBackground(new Color(210, 210, 232));

		serverHostName = this.getCodeBase().getHost();
		
		maildlg = new MAILDIALOG(this);
		maildlg.CreateControls();
    }
    
    public boolean action(Event e, Object arg)
    {
		if (e.target == maildlg.IDB_SEND)
		{
			try this.send();
			catch (Exception ex)
			{
				this.showStatus("Error; message send failed:\n  " + ex.toString());
				return true;
			}
			this.showStatus("Message sent");
		}
		if (e.target == maildlg.IDB_RESET)
		{
			maildlg.IDE_TO.setText("");
			maildlg.IDE_FROM.setText("");
			maildlg.IDE_BODY.setText("");
		}
		if (e.target == maildlg.IDB_CANCEL)
		{
			maildlg.IDE_BODY.setText("Cancel");
		}
		return true;
    }

	void send() throws IOException, Exception
    {
        socket = new Socket(serverHostName, smtpPort);
        try 
        {
            rina = socket.getInetAddress();
            lina = rina.getLocalHost();
            ps = new PrintStream(socket.getOutputStream());
            dis = new DataInputStream(socket.getInputStream());

            sendline("HELO " + lina.toString());
            sendline("MAIL FROM:" + getfrom());
            sendline("RCPT TO:" + getto());
            sendline("DATA");
            sendline(getmessage());
            sendline(".");
        }
        catch (Exception ex)
        {
            socket.close();
            throw ex;
        }
        socket.close();
    }

	void sendline(String sztemp) throws IOException
    {
        System.out.println("sent : " + sztemp);
        ps.println(sztemp);
        ps.flush();
        String s = dis.readLine();
        System.out.println("in : " + s);
    }

    public String getfrom()
    {
        return maildlg.IDE_FROM.getText();
    }

	public String getto()
    {
        return maildlg.IDE_TO.getText();
    }

    public String getmessage()
    {
        String sztemp = "";
        sztemp += "Date :";
        sztemp += (new Date()).toString();
        sztemp += "\n";
        sztemp += maildlg.IDE_BODY.getText();
        sztemp += "\n";
        
        return sztemp;
    }
}
