Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 444
  • Last Modified:

Error in java code

Still having rookie issues with creating a java package from scratch.  I have the following classes, MailClient, Message, Envelope, SMTPConnection.

I am assuming that MailClient should be the main class and used to invoke all of this instead of having a MailAgent class that would call MailClient.

Anyway, I have created the package in NetBeans, but when I clean and build, I receive an error for 'envelope' in MailClient and I cannot figure out why.

Please take a look at if and see if you can assist.  Thanks


Envelope.java
MailClient.java
Message.java
SMTPConnection.java
0
jjackson2004
Asked:
jjackson2004
  • 21
  • 14
  • 5
2 Solutions
 
jjackson2004Author Commented:
the error is that it cannot find the symbol 'envelope'
0
 
CEHJCommented:
The variable is out of scope, being in a *different* try/catch block. You need to access it in the same try/catch block
0
 
for_yanCommented:
This would be corrected code:
//MailClient.java

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

/* $Id: MailClient.java,v 1.7 1999/07/22 12:07:30 kangasha Exp $ */

/**
 * 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));
	fieldPanel.add(serverPanel);
	fieldPanel.add(fromPanel);
	fieldPanel.add(toPanel);
	fieldPanel.add(subjectPanel);

	/* 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());
	buttonPanel.add(btSend);
	buttonPanel.add(btClear);
	buttonPanel.add(btQuit);

	/* Add, pack, and show. */
	add(fieldPanel, BorderLayout.NORTH);
	add(messagePanel, BorderLayout.CENTER);
	add(buttonPanel, BorderLayout.SOUTH);
	pack();
	show();
    }

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

    /* Handler for the Send-button. */
    class SendListener implements ActionListener {
	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!");
		return;
	    }

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

	    /* Create the message */
	    Message mailMessage = new Message(fromField.getText(),
					      toField.getText(),
					      subjectField.getText(),
					      messageText.getText());

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

	    /* Create the envelope, open the connection and try to send
	       the message. */
        Envelope envelope = null;
	    try {
		envelope = new Envelope(mailMessage,
						 serverField.getText());
	    } catch (UnknownHostException e) {
		/* If there is an error, do not go further */
		return;
	    }
	    try {
		SMTPConnection connection = new SMTPConnection(envelope);
		connection.send(envelope);
		connection.close();
	    } catch (IOException error) {
		System.out.println("Sending failed: " + error);
		return;
	    }
	    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");
	    fromField.setText("");
	    toField.setText("");
	    subjectField.setText("");
	    messageText.setText("");
	}
    }

    /* Quit. */
    class QuitListener implements ActionListener {
	public void actionPerformed(ActionEvent e) {
	    System.exit(0);
	}
    }
}

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
No - you don't need two try/catch blocks - just one
0
 
for_yanCommented:
One or two is really not that important - it actually even excutes and shows gui, though I didn't try to ssend a message.

What is really very important is never do like this:

 try {
		envelope = new Envelope(mailMessage,
						 serverField.getText());
	    } catch (UnknownHostException e) {
		/* If there is an error, do not go further */
		return;
	    }

Open in new window



Here you catch exception but does not print anyting in the catch block
This is teribl practicve - even in the quickets and dirtiest code
that will give you so much pain - never eever do that!

Best thing in every catch loop to put  ex.printStackTrace()




0
 
for_yanCommented:
Eeven though you have return;
but it may be difficult to understand that you have exception
So always put ex.printStacktrace() inside catch loop - it will save you a lot of time, believe me I made this mistake many times in the beginning
0
 
CEHJCommented:
Avoid also using return statements in error handling. This makes the code difficult to maintain and somewhat negates the point of exceptions, which have their own flow control.

You should also really log errors in order to determine what is happening in your code
0
 
CEHJCommented:
Your code in the area in question should look more like the following, although in place of stack trace printing should really be error logging AND stack trace logging
try {
                Envelope envelope = new Envelope(mailMessage, serverField.getText());
                connection = new SMTPConnection(envelope);
                connection.send(envelope);
            } catch (UnknownHostException e) {
                /* If there is an error, do not go further */
		e.printStackTrace();	
            }
            catch (IOException e) {
                e.printStackTrace();	
            }
	    finally {
                try { connection.close(); } catch(Exception e) { /* ignore */ }	
	    }

            System.out.println("Mail sent succesfully!");

Open in new window

0
 
for_yanCommented:
printStackTrace() will print for you the exact line where the error occured so in case of longer blocks
iit would be convenient to poinpoint the problem,
but much more importantly, it will give you long printourt of exceptiion trace and would not allow you
to leave the error unnoticed - and this is where you'll spend most of your debugging time if you forget to
make some explicit printout inside the block.

Compiler sometimes requires you to put the try/catch loop and if you are starting programming in java
you tend to do it quickly just to satsify compiler and leave
that place inside the loop empty. Then you forget about it and later on there is an error which is being caught and disappears into
thin air - and to find such error is sometimes almost impossible.
So even if you are writing code while jumping with parashute (perhpas still not the best practice),
still take additional second and add printStackTrace() within the loop.
0
 
jjackson2004Author Commented:
you guys are awesome.  I thought it might be that envelope was in the try/catch but I am still not sure of myself on these things.

Now, would somebody mind looking into why the send button does not seem to do anything when I am testing it?

Thanks

0
 
for_yanCommented:
I am afraid it will send something somewhere ?
0
 
for_yanCommented:
Guaranteed, that it would not?
0
 
for_yanCommented:
what are those hosts doing:
ultra.allegheny.edu
adsl.meadville-1
0
 
for_yanCommented:
it asks for local smtp server but is it using it or is it rather going to these serevrs above?
0
 
jjackson2004Author Commented:
never mind,  it is trying in the background.

Changed that server listed in the code to gsu-edu.mail.eo.outlook.com

getting error:  "Sending failed:  java.net.ConnectException:  Connection timed out:  connect"

guess I chose the wrong mail server.  Working on trying to figure out nslookup to do a MX query.
0
 
for_yanCommented:
So it does not use the local smtp server which I'd provide in the text box - true?
So I should explicitly put my loacl serevr thhere to try?

And why there are twio of them?
0
 
jjackson2004Author Commented:
um, these would seem like my questions to you.  Two of them what?
0
 
for_yanCommented:
You amy want to look at this trail - it has solution some information on how to use Gmail
and Hotmail as public smtp servers
http://www.experts-exchange.com/Programming/Languages/Java/Q_27326341.html
0
 
for_yanCommented:

I mean you mention two servers explicitly in your code:
ultra.allegheny.edu
adsl.meadville-1

besides you require to enter local SMTP server

how are those three servers playing ?

In order to send email you normally need to connect just to one SMTP server

So why do you have three in your code?


0
 
jjackson2004Author Commented:
my mistake, reusing some old code.  I believe that now I have corrected them.
0
 
for_yanCommented:
post your new smtp connection java file - I'll replace with my local smtp serevr and try if it works for me
0
 
jjackson2004Author Commented:
how would I check to see what my local mail server.  I use Uverse.  should I nsloopup att.net?

Do you know how to verify the sender's address?  Something about javas System class has something in it for that I am told.
SMTPConnection.java
0
 
jjackson2004Author Commented:
think I found the answer to my local mail server.  it would appear to be one of three

scc-mailrelay.att.net
aln-mailrelay.att.net
frf.mailrelay.att.net
0
 
for_yanCommented:
may be reasonable.
0
 
for_yanCommented:
worked nicely for me with my smtp server
though I have different localhost and smtp server - maybe you happen to have the same -
don'tknow why you had them identical.
I provided our smtp serevre for the server and IP of my local machine for localhost and got nice email
0
 
jjackson2004Author Commented:
I have added a Cc: field.  Would you mind testing it for me.  I still have issues with the local mailserver on my system.

Thanks again.  this is very informative and extremely helpful.
Message.java
MailClient.java
0
 
for_yanCommented:
Look at this - if you can go away form sockets and do it through higher level with JavaMail, you can try this
using Gmail SMTP server (you'll of course need gmail account and hat your company allows you to comnnect):
see here:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
0
 
for_yanCommented:
Yes, works fine for me this variant; and sends CC also
0
 
jjackson2004Author Commented:
I try not to do anything involving google except searches that I don't mind them keeping forever.  But I will look into it in my endeavor to try to learn as much as I can about different subjects.

When this is over, if you have any suggestions of how to remove some of the hidden google stuff on my computer i would greatly appreciate.  Or I can submit a new question.  Yeah, I know, conspiracy theory.

Do you know how to verify the sender address using System class and the InetAddress class for finding the name of the local host?
0
 
for_yanCommented:
No don't knwo about use of System class in this respect

This is something about sender verification:
http://www.rgagnon.com/javadetails/java-0452.html
0
 
for_yanCommented:
I think you could ask your IT guys about your smtp server

we have it named like that:

mailhub.company_name.com

check maybe you have such server either
0
 
jjackson2004Author Commented:
thank you again so much.  I will have only one more thing to ask of you.  I am making one more change to the program.  Would you mind testing it one last time?

Thanks
0
 
for_yanCommented:
sure, let me know what is the change and post the file
0
 
jjackson2004Author Commented:
Added Message-ID to the headers (supposedly according to RFC 822)


Message.java
MailClient.java
0
 
jjackson2004Author Commented:
maybe I am supposed to have the messageid show up on the email client where the other fields are shown?  hard to read the RFC.
0
 
for_yanCommented:
works OK. Don't know what you mean about messageId but sends fine
0
 
jjackson2004Author Commented:
A unique message id I generated with uuid.  I take it does not show up in your email client.
0
 
for_yanCommented:
No, but it showed in the protocol of email sending
0
 
CEHJCommented:
I would strongly urge you to use the JavaMail api instead of trying to reinvent it. You'll get a lot more functionality and it will be a lot less error-prone
0
 
jjackson2004Author Commented:
great responses.  Thanks!
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 21
  • 14
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now