Exception errors in running Java application

Posted on 2005-02-26
Medium Priority
Last Modified: 2013-11-23
Hi all,
  I have developed a simple Java application that connects to a given SMTP server and sends a one message. However, i have problems running the code in the Java runtime environment. The same problem occurs in different configurations for both Windows and Linux.

C:\Documents and Settings\Dark Angel\Desktop\Java>java MailClient.java
Exception in thread "main" java.lang.NoClassDefFoundError: MailClient/java

I will post the code for the files: MailClient.java Envelope.Java Message.java SMTPConnection.java
The main is in the class MailClient.java, running should produce a window with text input areas and such.

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

 * A simple mail client with a GUI for sending mail.
 * @author Jussi Kangasharju
public class MailClient extends Frame {
    /* The stuff for the GUI. */
    private Button btSend = new Button("Send");
    private Button btClear = new Button("Clear");
    private Button btQuit = new Button("Quit");
    private Label serverLabel = new Label("Local mailserver:");
    private TextField serverField = new TextField("", 40);
    private Label fromLabel = new Label("From:");
    private TextField fromField = new TextField("", 40);
    private Label toLabel = new Label("To:");
    private TextField toField = new TextField("", 40);
    private Label subjectLabel = new Label("Subject:");
    private TextField subjectField = new TextField("", 40);
    private Label messageLabel = new Label("Message:");
    private TextArea messageText = new TextArea(10, 40);

     * Create a new MailClient window with fields for entering all
     * the relevant information (From, To, Subject, and message).
    public MailClient() {
      super("Java Mailclient");
      /* Create panels for holding the fields. To make it look nice,
         create an extra panel for holding all the child panels. */
      Panel serverPanel = new Panel(new BorderLayout());
      Panel fromPanel = new Panel(new BorderLayout());
      Panel toPanel = new Panel(new BorderLayout());
      Panel subjectPanel = new Panel(new BorderLayout());
      Panel messagePanel = new Panel(new BorderLayout());
      serverPanel.add(serverLabel, BorderLayout.WEST);
      serverPanel.add(serverField, BorderLayout.CENTER);
      fromPanel.add(fromLabel, BorderLayout.WEST);
      fromPanel.add(fromField, BorderLayout.CENTER);
      toPanel.add(toLabel, BorderLayout.WEST);
      toPanel.add(toField, BorderLayout.CENTER);
      subjectPanel.add(subjectLabel, BorderLayout.WEST);
      subjectPanel.add(subjectField, BorderLayout.CENTER);
      messagePanel.add(messageLabel, BorderLayout.NORTH);      
      messagePanel.add(messageText, BorderLayout.CENTER);
      Panel fieldPanel = new Panel(new GridLayout(0, 1));

      /* Create a panel for the buttons and add listeners to the
         buttons. */
      Panel buttonPanel = new Panel(new GridLayout(1, 0));
      btSend.addActionListener(new SendListener());
      btClear.addActionListener(new ClearListener());
      btQuit.addActionListener(new QuitListener());
      /* Add, pack, and show. */
      add(fieldPanel, BorderLayout.NORTH);
      add(messagePanel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.SOUTH);

    public static void main(String args[]) {
      new MailClient();

    /* Handler for the Send-button. */
    class SendListener implements ActionListener {
      public Envelope envelope;

      public void actionPerformed(ActionEvent event) {
          System.out.println("Sending mail");
          /* Check that we have the local mailserver */
          if ((serverField.getText()).equals("")) {
            System.out.println("Need name of local mailserver!");

          /* Check that we have the sender and recipient. */
          if((fromField.getText()).equals("")) {
            System.out.println("Need sender!");
          if((toField.getText()).equals("")) {
            System.out.println("Need recipient!");

          /* Create the message */
          Message mailMessage = new Message(fromField.getText(),

          /* Check that the message is valid, i.e., sender and
             recipient addresses look ok. */
          if(!mailMessage.isValid()) {

          /* Create the envelope, open the connection and try to send
             the message. */
          try {
            envelope = new Envelope(mailMessage,
          } catch (UnknownHostException e) {
            /* If there is an error, do not go further */
          try {
            SMTPConnection connection = new SMTPConnection(envelope);
          } catch (IOException error) {
            System.out.println("Sending failed: " + error);
          System.out.println("Mail sent succesfully!");

    /* Clear the fields on the GUI. */
    class ClearListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
          System.out.println("Clearing fields");

    /* Quit. */
    class QuitListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {

import java.io.*;
import java.net.*;
import java.util.*;

 * SMTP envelope for one mail message.
 * @author Jussi Kangasharju
public class Envelope {
    /* SMTP-sender of the message (in this case, contents of From-header. */
    public String Sender;

    /* SMTP-recipient, or contents of To-header. */
    public String Recipient;

    /* Target MX-host */
    public String DestHost;
    public InetAddress DestAddr;

    /* The actual message */
    public Message Message;

    /* Create the envelope. */
    public Envelope(Message message, String localServer) throws UnknownHostException {
      /* Get sender and recipient. */
      Sender = message.getFrom();
      Recipient = message.getTo();

      /* Get message. We must escape the message to make sure that
         there are no single periods on a line. This would mess up
         sending the mail. */
      Message = escapeMessage(message);

      /* Take the name of the local mailserver and map it into an
       * InetAddress */
      DestHost = localServer;
      try {
          DestAddr = InetAddress.getByName(DestHost);
      } catch (UnknownHostException e) {
          System.out.println("Unknown host: " + DestHost);
          throw e;

    /* Escape the message by doubling all periods at the beginning of
       a line. */
    private Message escapeMessage(Message message) {
      String escapedBody = "";
      String token;
      StringTokenizer parser = new StringTokenizer(message.Body, "\n", true);

      while(parser.hasMoreTokens()) {
          token = parser.nextToken();
          if(token.startsWith(".")) {
            token = "." + token;
          escapedBody += token;
      message.Body = escapedBody;
      return message;

    /* For printing the envelope. Only for debug. */
    public String toString() {
      String res = "Sender: " + Sender + '\n';
      res += "Recipient: " + Recipient + '\n';
      res += "MX-host: " + DestHost + ", address: " + DestAddr + '\n';
      res += "Message:" + '\n';
      res += Message.toString();
      return res;

import java.util.*;
import java.text.*;

 * Mail message.
 * @author Jussi Kangasharju
public class Message {
    /* The headers and the body of the message. */
    public String Headers;
    public String Body;

    /* Sender and recipient. With these, we don't need to extract them
       from the headers. */
    private String From;
    private String To;

    /* To make it look nicer */
    private static final String CRLF = "\r\n";

    /* Create the message object by inserting the required headers from
       RFC 822 (From, To, Date). */
    public Message(String from, String to, String subject, String text) {
      /* Remove whitespace */
      From = from.trim();
      To = to.trim();
      Headers = "From: " + From + CRLF;
      Headers += "To: " + To + CRLF;
      Headers += "Subject: " + subject.trim() + CRLF;

      /* A close approximation of the required format. Unfortunately
         only GMT. */
      SimpleDateFormat format =
          new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'");
      String dateString = format.format(new Date());
      Headers += "Date: " + dateString + CRLF;
      Body = text;

    /* Two functions to access the sender and recipient. */
    public String getFrom() {
      return From;

    public String getTo() {
      return To;

    /* Check whether the message is valid. In other words, check that
       both sender and recipient contain only one @-sign. */
    public boolean isValid() {
      int fromat = From.indexOf('@');
      int toat = To.indexOf('@');

      if(fromat < 1 || (From.length() - fromat) <= 1) {
          System.out.println("Sender address is invalid");
          return false;
      if(toat < 1 || (To.length() - toat) <= 1) {
          System.out.println("Recipient address is invalid");
          return false;
      if(fromat != From.lastIndexOf('@')) {
          System.out.println("Sender address is invalid");
          return false;
      if(toat != To.lastIndexOf('@')) {
          System.out.println("Recipient address is invalid");
          return false;
      return true;
    /* For printing the message. */
    public String toString() {
      String res;

      res = Headers + CRLF;
      res += Body;
      return res;

import java.net.*;
import java.io.*;
import java.util.*;

 * Open an SMTP connection to a mailserver and send one mail.
public class SMTPConnection {

    private String response;

    /* The socket to the server */
    private Socket connection;

    /* Streams for reading and writing the socket */
    private BufferedReader fromServer;
    private DataOutputStream toServer;

    private static final int SMTP_PORT = 25;
    private static final String CRLF = "\r\n";

    /* Are we connected? Used in close() to determine what to do. */
    private boolean isConnected = false;

    /* Create an SMTPConnection object. Create the socket and the
       associated streams. Initialize SMTP connection. */
    public SMTPConnection(Envelope envelope) throws IOException {
      fromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      toServer = new DataOutputStream(connection.getOutputStream());

      /* Establish connection */
      connection = new Socket(envelope.DestAddr, SMTP_PORT);

      /* Read a line from server and check that the reply code is 220.
         If not, throw an IOException. */
      if(parseReply(fromServer.readLine()) != 220)
            throw new IOException("Remote peer not an SMTP server");

      /* SMTP handshake. We need the name of the local machine.
         Send the appropriate SMTP handshake command. */
      sendCommand("HELO " + InetAddress.getLocalHost().getHostName() + CRLF, 250);

      isConnected = true;

    /* Send the message. Write the correct SMTP-commands in the
       correct order. No checking for errors, just throw them to the
       caller. */
    public void send(Envelope envelope) throws IOException {
      /* Send all the necessary commands to send a message. Call
         sendCommand() to do the dirty work. Do _not_ catch the
         exception thrown from sendCommand(). */
      sendCommand("MAIL FROM:<" + envelope.Sender + ">" +  CRLF, 250);
      sendCommand("RCPT TO:<" + envelope.Recipient + ">" + CRLF, 250);
      sendCommand("DATA" + CRLF, 354);
      sendCommand(envelope.Message.toString() + CRLF + "." + CRLF, 250);

    /* Close the connection. First, terminate on SMTP level, then
       close the socket. */
    public void close() {
      isConnected = false;
      try {
          sendCommand("QUIT" + CRLF, 221);
      } catch (IOException e) {
          System.out.println("Unable to close connection: " + e);
          isConnected = true;

    /* Send an SMTP command to the server. Check that the reply code is
       what is is supposed to be according to RFC 821. */
    private void sendCommand(String command, int rc) throws IOException {
      /* Write command to server and read reply from server. */

      /* Check that the server's reply code is the same as the parameter
         rc. If not, throw an IOException. */
      response = fromServer.readLine();
      if(parseReply(response) != rc) throw new IOException(response);

    /* Parse the reply line from the server. Returns the reply code. */
    private int parseReply(String reply) {
      StringTokenizer st = new StringTokenizer(reply);
      return Integer.parseInt(st.nextToken());  

    /* Destructor. Closes the connection if something bad happens. */
    protected void finalize() throws Throwable {
      if(isConnected) {

Very Urgent. Thanks for looking.
Question by:x25
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2

Accepted Solution

lhankins earned 2000 total points
ID: 13412956
> C:\Documents and Settings\Dark Angel\Desktop\Java>java MailClient.java
> Exception in thread "main" java.lang.NoClassDefFoundError: MailClient/java

You're executing the command wrong.  Normally you execute a java program by typing :

   java packagename.classname

In your case, you're using this :

   java MailClient.java

Which is going to look for a class named "java" in a package named "MailClient".     To get around the problem, execute your program like this :

   java MailClient

Expert Comment

ID: 13412988
Just some additional information, if I have a class defined like this :

   package com.acme;

   class Foo {
      // etc...

Then I may COMPILE it by running javac ("javac" = "java compiler")

   javac Foo.java

But when I RUN it, I do it like ("java" = "java virtual machine")

   java com.acme.Foo

For compiling, I rarely run javac from the command line (create an ant build file to do this, or use your favorite IDE).


Author Comment

ID: 13413300
I appreciate you pointing me what is difference between compiling and running an app. Needless to say, many people still find this to be difficult.

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month9 days, 6 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question