Link to home
Start Free TrialLog in
Avatar of nasile
nasile

asked on

Mail Applet Hell.. Please help!

I am using this applet to send an email application to a recipient specified in an html parameter. Everything appears to work well and the applet completes saying transmission successful. However, I never recieve the email. If I run the applet in an appletviewer and hardcode the server address to my isp's mail server it works. I just cant get it working through a browser. At the end of this post there is a dump of the IE5.0 java console window. There are 2 exceptions being thrown and Im not sure where they are coming from but I think that they arent the problem. Id be most grateful if someone could solve this problem =)

I use Symantec Visual Cafe Professional Version 3.0c - JDK1.1.x

HERE IS THE MAIN APPLET CLASS:

/*
A basic extension of the com.sun.java.swing.JApplet class
*/
import java.io.*;
import java.net.*;
import com.sun.java.swing.*;
import java.awt.*;
import symantec.itools.awt.ImagePanel;
import com.symantec.itools.swing.models.StringComboBoxModel;
import com.symantec.itools.swing.borders.BevelBorder;
import com.symantec.itools.swing.borders.EtchedBorder;
import com.symantec.itools.swing.borders.SoftBevelBorder;

public class JApplet1 extends JApplet
{
      public void init()
      {
            // Take out this line if you don't use symantec.itools.net.RelativeURL or symantec.itools.awt.util.StatusScroller
            symantec.itools.lang.Context.setApplet(this);
            
            // This line prevents the "Swing: checked access to system event queue" message seen in some browsers.
            getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
            
            // This code is automatically generated by Visual Cafe when you add
            // components to the visual environment. It instantiates and initializes
            // the components. To modify the code, only use code syntax that matches
            // what Visual Cafe can generate, or Visual Cafe may be unable to back
            // parse your Java file into its visual environment.
            //{{INIT_CONTROLS
            getContentPane().setLayout(null);
            getContentPane().setBackground(java.awt.Color.black);
            getContentPane().setForeground(java.awt.Color.orange);
            setSize(333,337);
            submitButton.setText("Submit");
            submitButton.setActionCommand("Submit");
            submitButton.setBorder(etchedBorder1);
            getContentPane().add(submitButton);
            submitButton.setBackground(java.awt.Color.black);
            submitButton.setForeground(java.awt.Color.orange);
            submitButton.setBounds(228,300,84,24);
            resetButton.setText("Reset");
            resetButton.setActionCommand("Reset");
            resetButton.setBorder(etchedBorder1);
            getContentPane().add(resetButton);
            resetButton.setBackground(java.awt.Color.black);
            resetButton.setForeground(java.awt.Color.orange);
            resetButton.setBounds(24,300,84,24);
            JLabel1.setText("Name (In Game):");
            getContentPane().add(JLabel1);
            JLabel1.setBackground(new java.awt.Color(204,204,204));
            JLabel1.setForeground(java.awt.Color.orange);
            JLabel1.setBounds(24,48,120,24);
            JLabel2.setText("Race:");
            getContentPane().add(JLabel2);
            JLabel2.setBackground(new java.awt.Color(204,204,204));
            JLabel2.setForeground(java.awt.Color.orange);
            JLabel2.setBounds(24,84,108,24);
            JLabel3.setText("Class:");
            getContentPane().add(JLabel3);
            JLabel3.setBackground(new java.awt.Color(204,204,204));
            JLabel3.setForeground(java.awt.Color.orange);
            JLabel3.setBounds(24,120,108,24);
            JLabel4.setText("Current Level:");
            getContentPane().add(JLabel4);
            JLabel4.setBackground(new java.awt.Color(204,204,204));
            JLabel4.setForeground(java.awt.Color.orange);
            JLabel4.setBounds(24,156,108,24);
            JLabel5.setText("Character Sex:");
            getContentPane().add(JLabel5);
            JLabel5.setBackground(new java.awt.Color(204,204,204));
            JLabel5.setForeground(java.awt.Color.orange);
            JLabel5.setBounds(24,192,108,24);
            JLabel6.setText("E-mail Address:");
            getContentPane().add(JLabel6);
            JLabel6.setBackground(new java.awt.Color(204,204,204));
            JLabel6.setForeground(java.awt.Color.orange);
            JLabel6.setFont(new Font("Dialog", Font.BOLD, 12));
            JLabel6.setBounds(24,228,108,24);
            nameField.setCaretColor(java.awt.Color.yellow);
            nameField.setBorder(etchedBorder1);
            getContentPane().add(nameField);
            nameField.setBackground(java.awt.Color.black);
            nameField.setForeground(java.awt.Color.orange);
            nameField.setFont(new Font("Dialog", Font.BOLD, 12));
            nameField.setBounds(156,48,158,25);
            raceBox.setModel(stringComboBoxModel1);
            getContentPane().add(raceBox);
            raceBox.setBackground(java.awt.Color.black);
            raceBox.setForeground(java.awt.Color.orange);
            raceBox.setBounds(156,84,158,26);
            classBox.setModel(stringComboBoxModel2);
            getContentPane().add(classBox);
            classBox.setBackground(java.awt.Color.black);
            classBox.setForeground(java.awt.Color.orange);
            classBox.setBounds(156,120,158,26);
            levelBox.setModel(stringComboBoxModel3);
            getContentPane().add(levelBox);
            levelBox.setBackground(java.awt.Color.black);
            levelBox.setForeground(java.awt.Color.orange);
            levelBox.setBounds(156,156,60,24);
            sexBox.setModel(stringComboBoxModel4);
            getContentPane().add(sexBox);
            sexBox.setBackground(java.awt.Color.black);
            sexBox.setForeground(java.awt.Color.orange);
            sexBox.setBounds(156,192,108,24);
            email1Field.setCaretColor(java.awt.Color.yellow);
            email1Field.setBorder(etchedBorder1);
            getContentPane().add(email1Field);
            email1Field.setBackground(java.awt.Color.black);
            email1Field.setForeground(java.awt.Color.orange);
            email1Field.setFont(new Font("Dialog", Font.BOLD, 12));
            email1Field.setBounds(156,228,158,25);
            {
                  String[] tempString = new String[12];
                  tempString[0] = "Barbarian";
                  tempString[1] = "Dark Elf";
                  tempString[2] = "Dwarf";
                  tempString[3] = "Erudite";
                  tempString[4] = "Gnome";
                  tempString[5] = "Half Elf";
                  tempString[6] = "Halfling";
                  tempString[7] = "High Elf";
                  tempString[8] = "Human";
                  tempString[9] = "Ogre";
                  tempString[10] = "Troll";
                  tempString[11] = "Wood Elf";
                  stringComboBoxModel1.setItems(tempString);
            }
            //$$ stringComboBoxModel1.move(0,360);
            {
                  String[] tempString = new String[14];
                  tempString[0] = "Bard";
                  tempString[1] = "Cleric";
                  tempString[2] = "Druid";
                  tempString[3] = "Enchanter";
                  tempString[4] = "Magician";
                  tempString[5] = "Monk";
                  tempString[6] = "Necromancer";
                  tempString[7] = "Paladin";
                  tempString[8] = "Ranger";
                  tempString[9] = "Rogue";
                  tempString[10] = "ShadowKnight";
                  tempString[11] = "Shaman";
                  tempString[12] = "Warrior";
                  tempString[13] = "Wizard";
                  stringComboBoxModel2.setItems(tempString);
            }
            //$$ stringComboBoxModel2.move(24,360);
            {
                  String[] tempString = new String[60];
                  tempString[0] = "1";
                  tempString[1] = "2";
                  tempString[2] = "3";
                  tempString[3] = "4";
                  tempString[4] = "5";
                  tempString[5] = "6";
                  tempString[6] = "7";
                  tempString[7] = "8";
                  tempString[8] = "9";
                  tempString[9] = "10";
                  tempString[10] = "11";
                  tempString[11] = "12";
                  tempString[12] = "13";
                  tempString[13] = "14";
                  tempString[14] = "15";
                  tempString[15] = "16";
                  tempString[16] = "17";
                  tempString[17] = "18";
                  tempString[18] = "19";
                  tempString[19] = "20";
                  tempString[20] = "21";
                  tempString[21] = "22";
                  tempString[22] = "23";
                  tempString[23] = "24";
                  tempString[24] = "25";
                  tempString[25] = "26";
                  tempString[26] = "27";
                  tempString[27] = "28";
                  tempString[28] = "29";
                  tempString[29] = "30";
                  tempString[30] = "31";
                  tempString[31] = "32";
                  tempString[32] = "33";
                  tempString[33] = "34";
                  tempString[34] = "35";
                  tempString[35] = "36";
                  tempString[36] = "37";
                  tempString[37] = "38";
                  tempString[38] = "39";
                  tempString[39] = "40";
                  tempString[40] = "41";
                  tempString[41] = "42";
                  tempString[42] = "43";
                  tempString[43] = "44";
                  tempString[44] = "45";
                  tempString[45] = "46";
                  tempString[46] = "47";
                  tempString[47] = "48";
                  tempString[48] = "49";
                  tempString[49] = "50";
                  tempString[50] = "51";
                  tempString[51] = "52";
                  tempString[52] = "53";
                  tempString[53] = "54";
                  tempString[54] = "55";
                  tempString[55] = "56";
                  tempString[56] = "57";
                  tempString[57] = "58";
                  tempString[58] = "59";
                  tempString[59] = "60";
                  stringComboBoxModel3.setItems(tempString);
            }
            //$$ stringComboBoxModel3.move(48,360);
            {
                  String[] tempString = new String[2];
                  tempString[0] = "Male";
                  tempString[1] = "Female";
                  stringComboBoxModel4.setItems(tempString);
            }
            //$$ stringComboBoxModel4.move(72,360);
            email2Field.setCaretColor(java.awt.Color.yellow);
            email2Field.setBorder(etchedBorder1);
            getContentPane().add(email2Field);
            email2Field.setBackground(java.awt.Color.black);
            email2Field.setForeground(java.awt.Color.orange);
            email2Field.setFont(new Font("Dialog", Font.BOLD, 12));
            email2Field.setBounds(156,264,158,25);
            JLabel7.setText("Verify E-mail:");
            getContentPane().add(JLabel7);
            JLabel7.setBackground(new java.awt.Color(204,204,204));
            JLabel7.setForeground(java.awt.Color.orange);
            JLabel7.setFont(new Font("Dialog", Font.BOLD, 12));
            JLabel7.setBounds(24,264,108,24);
            statusLabel.setHorizontalTextPosition(com.sun.java.swing.SwingConstants.CENTER);
            statusLabel.setHorizontalAlignment(com.sun.java.swing.SwingConstants.CENTER);
            statusLabel.setText("Complete All fields and click Submit.");
            statusLabel.setBorder(etchedBorder1);
            getContentPane().add(statusLabel);
            statusLabel.setBackground(java.awt.Color.black);
            statusLabel.setForeground(new java.awt.Color(255,255,128));
            statusLabel.setBounds(24,12,288,24);
            etchedBorder1.setShadowColor(java.awt.Color.lightGray);
            etchedBorder1.setHighlightColor(java.awt.Color.gray);
            //$$ etchedBorder1.move(96,360);
            //}}
      
            //{{REGISTER_LISTENERS
            SymAction lSymAction = new SymAction( this );
            resetButton.addActionListener(lSymAction);
            submitButton.addActionListener(lSymAction);
            //}}
            
            nameField.setText( "" );
            raceBox.setSelectedIndex(0);
            classBox.setSelectedIndex(0);
            levelBox.setSelectedIndex(0);
            sexBox.setSelectedIndex(0);
            email1Field.setText( "" );
            email2Field.setText( "" );
            
            try
        {
            server = getCodeBase().getHost();
                                      
          }
          catch (Exception e)
          {
              statusLabel.setText( "Failure: Error retrieving hostname." );
              System.out.println( e.toString() );
        }
        mailMan = new mailer( server, statusLabel );
      }

      //{{DECLARE_CONTROLS
      com.sun.java.swing.JButton submitButton = new com.sun.java.swing.JButton();
      com.sun.java.swing.JButton resetButton = new com.sun.java.swing.JButton();
      com.sun.java.swing.JLabel JLabel1 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel JLabel2 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel JLabel3 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel JLabel4 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel JLabel5 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel JLabel6 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JTextField nameField = new com.sun.java.swing.JTextField();
      com.sun.java.swing.JComboBox raceBox = new com.sun.java.swing.JComboBox();
      com.sun.java.swing.JComboBox classBox = new com.sun.java.swing.JComboBox();
      com.sun.java.swing.JComboBox levelBox = new com.sun.java.swing.JComboBox();
      com.sun.java.swing.JComboBox sexBox = new com.sun.java.swing.JComboBox();
      com.sun.java.swing.JTextField email1Field = new com.sun.java.swing.JTextField();
      com.symantec.itools.swing.models.StringComboBoxModel stringComboBoxModel1 = new com.symantec.itools.swing.models.StringComboBoxModel();
      com.symantec.itools.swing.models.StringComboBoxModel stringComboBoxModel2 = new com.symantec.itools.swing.models.StringComboBoxModel();
      com.symantec.itools.swing.models.StringComboBoxModel stringComboBoxModel3 = new com.symantec.itools.swing.models.StringComboBoxModel();
      com.symantec.itools.swing.models.StringComboBoxModel stringComboBoxModel4 = new com.symantec.itools.swing.models.StringComboBoxModel();
      com.sun.java.swing.JTextField email2Field = new com.sun.java.swing.JTextField();
      com.sun.java.swing.JLabel JLabel7 = new com.sun.java.swing.JLabel();
      com.sun.java.swing.JLabel statusLabel = new com.sun.java.swing.JLabel();
      com.symantec.itools.swing.borders.EtchedBorder etchedBorder1 = new com.symantec.itools.swing.borders.EtchedBorder();
      //}}

      

      void resetButton_actionPerformed(java.awt.event.ActionEvent event)
      {
            nameField.setText( "" );
            raceBox.setSelectedIndex(0);
            classBox.setSelectedIndex(0);
            levelBox.setSelectedIndex(0);
            sexBox.setSelectedIndex(0);
            email1Field.setText( "" );
            email2Field.setText( "" );
            statusLabel.setText( "Complete All fields and click Submit." );
          repaint();
      }
      
      private static String server = null;
      private mailer mailMan = null;

      void submitButton_actionPerformed(java.awt.event.ActionEvent event)
      {
            if( nameField.getText().trim().equals( "" ) ||
                email1Field.getText().trim().equals( "" ) ||
                email2Field.getText().trim().equals( "" ) )
            {
                statusLabel.setText( "All fields must be completed." );
                return;
            }
               
                  
          if( !email1Field.getText().trim().equals( email2Field.getText().trim() ) )
          {
              statusLabel.setText( "E-mail addresses do not match." );
              return;
          }
          
          String from = email1Field.getText().trim();
          
          if ( !checkAddy(from) )
          {
              statusLabel.setText("Invalid E-mail address.");
              return;
          }
          
          String msg = "Character Name: " + nameField.getText()
              + "\r\nRace: " + raceBox.getSelectedItem().toString()
              + "\r\nClass: " + classBox.getSelectedItem().toString()
              + "\r\nLevel: " + levelBox.getSelectedItem().toString()
              + "\r\nSex: " + sexBox.getSelectedItem().toString()
              + "\r\nE-mail: " + from;
              
          String recipient = getParameter( "recipient" );
          mailMan.send( recipient, from, "New Applicant", msg );
          repaint();         
      }
      
      public boolean checkAddy(String str)
    {
        if ((str.indexOf("@") > 1) &&
            (str.indexOf("@") < str.length() - 1) &&
            (str.indexOf("@") > 0) &&
            (str.indexOf("@") == str.lastIndexOf("@")))
          return true;

        else return false;
    }
}

** HERE IS THE CLASS RESPONSIBLE FOR SENDING THE MAIL:

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

public class mailer
{
    private Socket sock = null;
    private String server = null;
    private PrintWriter pw = null;
    private String to = new String();
    private String from = new String();
    private String sub = new String();
    private String msg = new String();
    private com.sun.java.swing.JLabel statusLabel = null;

    public mailer( String server_in, com.sun.java.swing.JLabel status_in )
    {
        server = server_in;
        statusLabel = status_in;
        System.out.println( server );
    }
     
    public void send( String to_in, String from_in, String sub_in, String msg_in )
    {
        to = to_in.trim();
        from = from_in.trim();
        sub = sub_in.trim();
        msg = msg_in;
        sendMail();        
    }
       
    public void sendMail()
    {
        try
        {
            connect();
            System.out.println( "Connected." );
        }
        catch( Exception e )
        {
            statusLabel.setText( "1. " + e.toString() );
            System.out.println( e.toString() );
            //statusLabel.setText( "FAILURE: Error contacting Server." );
            return;
        }
        try
        {
            write();
            System.out.println( "Transmission Complete." );
        }
        catch ( Exception e )
          {
              statusLabel.setText( "2. " + e.toString() );
              System.out.println( e.toString() );
              //statusLabel.setText( "FAILURE: Error during communication." );
              return;
          }
        try
        {
            disconnect();
            System.out.println( "Disconnected from " + server );
        }
        catch ( Exception e )
        {
            statusLabel.setText( "3. " + e.toString() );
            System.out.println( e.toString() );
            //statusLabel.setText( "FAILURE: Error closing connection." );
            return;
        }        
    }

    public void connect() throws Exception
    {
        System.out.println( "Connecting to " + server );
        statusLabel.setText( "Connecting to " + server );
        sock = new Socket(server, 25);
        pw = new PrintWriter( sock.getOutputStream() );
       
    }

    public void write() throws Exception
    {
        System.out.println( "Transmitting data..." );
        pw.println("helo");
          pw.print("mail from:");
          pw.println(from);
          pw.print("rcpt to:");
          pw.println(to);
          pw.println("data");
          pw.println("To: " + to);
          pw.println("From: " + from);
          pw.println("Subject: " + sub);
          pw.println(msg);
          pw.println(".");         
    }

    public void disconnect() throws Exception
    {
        System.out.println( "Closing connection..." );
        pw.println( "quit" );
        pw.close();            
        statusLabel.setText( "Transmission Successful." );
    }
}

AND HERE IS THE EVENT HANDLER CLASS:



public class SymAction implements java.awt.event.ActionListener
{
    JApplet1 parent;
   
      public SymAction( JApplet1 parent_in )
      {
          parent = parent_in;
      }      
      
      public void actionPerformed(java.awt.event.ActionEvent event )
      {
            Object object = event.getSource();
            if (object == parent.resetButton)
                  parent.resetButton_actionPerformed(event);
            else if (object == parent.submitButton)
                  parent.submitButton_actionPerformed(event);
      }
}

Here is a dump from the IE5.0 Java Console.. according to this the mail has been sent.

Microsoft (R) VM for Java (tm), 4.0 Release 4.79.0.2424
==============================================
?  help
c  clear
f  run finalizers
g  garbage collect
m  memory usage
q  quit
t  thread list
==============================================
com.ms.security.SecurityExceptionEx[JApplet1.<init>]: java.io.IOException: bad path: C:\WINDOWS\Java\lib\swing.properties
      at com/ms/security/permissions/FileIOPermission.check
      at com/ms/security/PolicyEngine.deepCheck
      at com/ms/security/PolicyEngine.checkPermission
      at com/ms/security/StandardSecurityManager.chk
      at com/ms/security/StandardSecurityManager.checkRead
      at java/io/FileInputStream.<init>
      at java/io/FileInputStream.<init>
      at com/sun/java/swing/UIManager.loadSwingProperties
      at com/sun/java/swing/UIManager.initialize
      at com/sun/java/swing/UIManager.maybeInitialize
      at com/sun/java/swing/UIManager.getDefaults
      at com/sun/java/swing/UIManager.getColor
      at com/sun/java/swing/JPanel.<init>
      at com/sun/java/swing/JPanel.<init>
      at com/sun/java/swing/JRootPane.createGlassPane
      at com/sun/java/swing/JRootPane.<init>
      at com/sun/java/swing/JApplet.createRootPane
      at com/sun/java/swing/JApplet.<init>
      at JApplet1.<init>
      at com/ms/applet/BrowserAppletFrame.newInstance
      at com/ms/applet/AppletPanel.processSentEvent
      at com/ms/applet/AppletPanel.processSentEvent
      at com/ms/applet/AppletPanel.run
      at java/lang/Thread.run
com.ms.security.SecurityExceptionEx[JApplet1.<init>]: Event queue access denied.
      at com/ms/security/permissions/UIPermission.check
      at com/ms/security/PolicyEngine.deepCheck
      at com/ms/security/PolicyEngine.checkPermission
      at com/ms/security/StandardSecurityManager.chk
      at com/ms/security/StandardSecurityManager.checkAwtEventQueueAccess
      at java/awt/Toolkit.getSystemEventQueue
      at com/sun/java/swing/SystemEventQueueUtilities.initSystemEventQueue
      at com/sun/java/swing/SystemEventQueueUtilities.postRunnable
      at com/sun/java/swing/SwingUtilities.invokeLater
      at com/sun/java/swing/JComponent.revalidate
      at com/sun/java/swing/JTextField.setFont
      at com/sun/java/swing/plaf/basic/BasicTextUI.installDefaults
      at com/sun/java/swing/plaf/basic/BasicTextUI.installUI
      at com/sun/java/swing/plaf/metal/MetalTextFieldUI.installUI
      at com/sun/java/swing/JComponent.setUI
      at com/sun/java/swing/text/JTextComponent.setUI
      at com/sun/java/swing/text/JTextComponent.updateUI
      at com/sun/java/swing/text/JTextComponent.<init>
      at com/sun/java/swing/JTextField.<init>
      at com/sun/java/swing/JTextField.<init>
      at JApplet1.<init>
      at com/ms/applet/BrowserAppletFrame.newInstance
      at com/ms/applet/AppletPanel.processSentEvent
      at com/ms/applet/AppletPanel.processSentEvent
      at com/ms/applet/AppletPanel.run
      at java/lang/Thread.run
Swing: checked access to system event queue.
watchtower.mobis.com
Connecting to watchtower.mobis.com
Connected.
Transmitting data...
Transmission Complete.
Closing connection...
Disconnected from watchtower.mobis.com

Let me know if you need anything else from me that would help you, help me ;)

Thank you!
Avatar of nasile
nasile

ASKER

Edited text of question.
you never check the server answers (according to the SMTP) protoclo - it's possible that the server has rejected your e-mail or ...
I'll post a sample SMTP code, after several minutes
// class MailManager

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

public class MailManager
{
   private static final char SMTP_ERROR_CODE1 = '4';
   private static final char SMTP_ERROR_CODE2 = '5';
   
   protected static final String CRLF = "\r\n";
   
   private int SMTPPort;
   private String SMTPHost;
   private String senderHost;
   private String mailClient;
   private String senderName;
   private String senderEmail;
   private String charset = "us-ascii";
   private Vector logVector;
     
   MailAddress sender;
   String subject;
   Vector recipients; // vector of MailAddress-es
   Vector cc, bcc; // vector of all cc and bcc MailAddress-es


   String messageBody;
   
   Writer out;        // the socket streams
   BufferedReader in;
   
   public boolean init ()
   {
        SMTPHost = ServerConfig.getSMTPHost();
       senderHost = ServerConfig.getSenderHost();
       mailClient = ServerConfig.getMailClient();
       
       senderName = ServerConfig.getSenderName();
       senderEmail = ServerConfig.getSenderEmail();

       sender = new MailAddress(senderName, senderEmail);
       return true;
   }
   
   public boolean init (String _host, int _port)
   {
        SMTPHost = _host;
        SMTPPort = _port;
        return init();
   }

   public void sendMail (Vector _recipients,
       String _subject, String _data) throws Exception
   {
     recipients = _recipients;
//     bcc = new Vector();
//     bcc.addElement(new MailAddress(null, "<administrator@l.com"));
     subject = _subject;
     messageBody = _data;
       
      logVector = new Vector();
       try {
            send();
       } catch (Exception e)
       {
           ErrLog.log("Can't send e-mail. Nested exception is " + e.getMessage());
           ErrLog.log("==== Follows complete communication dump ====");
           for (int i = 0; i < logVector.size(); i++)
           {
               String st = (String)logVector.elementAt(i);
               ErrLog.log("| " + st);
           }
           ErrLog.log("==== End of communication dump ====");
           throw new Exception("Can't send e-mail report [" + e.getMessage() +"]");
       }
/*      
       for (int i = 0; i < logVector.size(); i++)
       {
           String st = (String)logVector.elementAt(i);
           System.out.println(st);
       }
*/      
   }


private synchronized void send () throws Exception
{
    if (sender == null)
        throw new Exception("SMTP Error: no sender address.");
    if (recipients == null || recipients.size() == 0)
        throw new Exception("SMTP Error: no recipients addresses.");

    Socket s = null;
    try {
        s = new Socket(SMTPHost, SMTPPort);
        out = new PrintWriter(s.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        readAndCheck("220");
        writeAndLog("HELO " + senderHost) ;
        readAndCheck("250");
        writeAndLog("MAIL FROM: " + sender.getFullAddress());
        readAndCheck("250");

        sendRecipients();
        sendData();
       
        writeAndLog("QUIT");
        readAndCheck("221");

    } finally
    {
        try {s.close() ;} catch (Exception e) {}
    }
}


/**
 * send the RCPT TO: commands
 */
private void sendRecipients () throws Exception
{
    if (recipients != null) // ???
        for (int i = 0; i < recipients.size(); i++)
        {
            MailAddress ma = (MailAddress)recipients.elementAt(i);
            writeAndLog("RCPT TO: " + ma.getFullAddress());
            readAndCheck("250");
        }
    if (cc != null) // ???
        for (int i = 0; i < cc.size(); i++)
        {
            MailAddress ma = (MailAddress)cc.elementAt(i);
            writeAndLog("RCPT TO: " + ma.getFullAddress());
            readAndCheck("250");
        }
    if (bcc != null) // ???
        for (int i = 0; i < bcc.size(); i++)
        {
            MailAddress ma = (MailAddress)bcc.elementAt(i);
            writeAndLog("RCPT TO: " + ma.getFullAddress());
            readAndCheck("250");
        }
}

/**
 * send the header.
 */
private void sendHeader () throws Exception
{

    StringBuffer buf = new StringBuffer();

    if (mailClient != null) buf.append("X-Mailer: " + mailClient + CRLF);
    buf.append("Date: " + Globals.getEmailFormattedDate(new FixedDate())+ CRLF);

    int n = recipients.size();
    if (n > 0)
    {
        buf.append("To: ");
        for (int i = 0; i < n; i++)
        {
            MailAddress add = (MailAddress)recipients.elementAt(i);
            if (i > 0) buf.append(", ");
            buf.append(add.getFullAddress());
        }
        buf.append(CRLF);
    } // else n == 0 ? :)

    n = (cc == null)? 0 : cc.size();
    if (n > 0)
    {
        buf.append("CC: ");
        for (int i = 0; i < n; i++)
        {
            MailAddress add = (MailAddress)cc.elementAt(i);
            if (i > 0) buf.append(", ");
            buf.append(add.getFullAddress());
        }
        buf.append(CRLF);
    }
/*
    n = (bcc == null)? 0 : bcc.size();
    if (n > 0)
    {
        buf.append("BCC: ");
        for (int i = 0; i < n; i++)
        {
            MailAddress add = (MailAddress)bcc.elementAt(i);
            if (i > 0) buf.append(", ");
            buf.append(add.getFullAddress());
        }
        buf.append(CRLF);
    }
*/        
    buf.append("From: " + sender.getFullAddress());
    if (subject != null)
        buf.append(CRLF + "Subject: " + subject); // - CRLF

    writeAndLog(buf.toString());
}

private void sendData () throws Exception
{
    writeAndLog("DATA") ;
    readAndCheck("354");
    sendHeader();
   
    writeAndLog("Mime-Version: 1.0");
    writeAndLog("Content-Type: text/plain; charset=\"" + charset + "\"");
    writeAndLog("");
   
//    main body loop
    int pos;
    String st;
    String mes = messageBody;
    while (mes != null)
    {
       
        pos = mes.indexOf(CRLF);    
        if (pos != -1)
        {
            st = mes.substring(0, pos);
            mes = mes.substring(pos + 2);
        } else
        {
            st = mes;
            mes = null;
        }
        if (st != null && st.length() > 0 && st.charAt(0) == '.')
        {
            writeAndLog("." + st);
        }
        else
            writeAndLog(st);
    }
    writeAndLog(CRLF + ".");
    readAndCheck("250");
}

public void writeAndLog (String st) throws Exception
{
    logVector.addElement("->" + st);
    out.write(st + CRLF);
    out.flush();
}

private void readAndCheck (String expected) throws Exception
{
    String st = in.readLine();
    logVector.addElement("<-" + st);
    if (st == null || st.length() < 4)
           throw new Exception("SMTP Error: Bad server response. [" + st + "]");
    if (!st.startsWith(expected))
           throw new Exception(
            "SMTP Error: expected code [" + expected + "], received response [" + st +"]");
}
}
// class MailAddress

public class MailAddress
{

    private String name;
    private String email;

    public MailAddress (String _name, String _email)
    {
        name = _name;
        email = _email;
        if (name != null) name = name.trim();
        if (email != null) email = email.trim();
    }

    String getName()
    {
        return name;
    }

    String getEmail()
    {
        return email;
    }

    String getFullAddress ()
    {
        if (name == null)
            return "<" + email + ">";
        else
            return name + " <" + email + ">";
    }

}

   
there are several other classes ServerConfig / ErrLog, but you don't really need them.

it's very simple to use the MailManager class:

String mailBody = "sdsdf"; // whatever


Vector v = new Vector();
MailAddress ua = new MailAddress(user.firstName + " " + user.lastName , user.email);
v.addElement(ua);

if (user.pemail != null)
{
MailAddress aa = new MailAddress(null, user.pemail);
v.addElement(aa);
}
               
mailManager.sendMail(v, "Results on test " , mailBody);


of course there a lot of (better) SMTP examples on the web.
Avatar of nasile

ASKER

After analyzing my problem further, I realized that the problem was on the server side. The server wasnt set up to relay and I was using a recipient address from another domain. But now I have run into an even stranger problem. The server isnt accepting my DATA..?? I have posted only the portion of code that applies and the servers response codes.

CODE:
public boolean write() throws Exception
    {
        boolean error;
       
        System.out.println( "Transmitting data..." );
        pw.println("helo watchtower.mobis.com");
        error = pw.checkError();
        pw.print("mail from:");
      pw.println(from);
      error = pw.checkError();
          
      pw.print("rcpt to:");
      pw.println(to);
      error = pw.checkError();
                   
      pw.println("data");
              
      /*pw.println("To: " + to);
      pw.println("From: " + from);
      pw.println("Subject: " + sub);
      pw.println(msg);*/
          
      pw.println(".");         
      pw.println("quit");
                   
      error = pw.checkError();
      readData();
      pw.close();
      return error;
    }

Output from JAVA CONSOLE:

Connecting to watchtower.mobis.com
Connected.
Transmitting data...
RESPONSE: 220 watchtower.mobis.com ESMTP Sendmail 8.9.3/8.9.3; Sun, 4 Jul 1999 14:20:40 -0500
RESPONSE: 250 watchtower.mobis.com Hello ipa20.trenton2.nj.pub-ip.psi.net [38.26.139.20], pleased to meet you
RESPONSE: 250 mo@mo... Sender ok
RESPONSE: 250 shril@watchtower.mobis.com... Recipient ok
RESPONSE: 354 Enter mail, end with "." on a line by itself
RESPONSE: 250 OAA03656 Message accepted for delivery
RESPONSE: 503 Need MAIL before RCPT
RESPONSE: 503 Need MAIL command
RESPONSE: 500 Command unrecognized: "."
RESPONSE: 221 watchtower.mobis.com closing connection
Completed.
Transmission Complete.

According to RFC 821 I am communicating properly. ARGH!

??


Avatar of nasile

ASKER

Adjusted points to 500
please post all messages (not only the server answers).
according to logs it seems that you've sent ONE message, and you've tried to sent another one....
I can't help you if you don't post the WHOLE code (btw. the code that I've posted worked for me, so you can always take a look at it)


if you don't want to post your code :), please generate message log like this one:

A Typical SMTP Transaction Scenario

This SMTP example shows mail sent by Smith at host USC-ISIF, to
Jones, Green, and Brown at host BBN-UNIX.  Here we assume that
host USC-ISIF contacts host BBN-UNIX directly.  The mail is
accepted for Jones and Brown.  Green does not have a mailbox at
host BBN-UNIX.

-------------------------------------------------------------

R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready
S: HELO USC-ISIF.ARPA
R: 250 BBN-UNIX.ARPA

S: MAIL FROM:<Smith@USC-ISIF.ARPA>
R: 250 OK

S: RCPT TO:<Jones@BBN-UNIX.ARPA>
R: 250 OK

S: RCPT TO:<Green@BBN-UNIX.ARPA>
R: 550 No such user here

S: RCPT TO:<Brown@BBN-UNIX.ARPA>
R: 250 OK

S: DATA
R: 354 Start mail input; end with <CRLF>.<CRLF>
S: Blah blah blah...
S: ...etc. etc. etc.
S: .
R: 250 OK

S: QUIT
R: 221 BBN-UNIX.ARPA Service closing transmission channel
         
so ?
what's up ?
I've posted a working SMTP implementation - thta's why I'll post an 'answer'.

if you have any questions - feel free to ask.
ASKER CERTIFIED SOLUTION
Avatar of heyhey_
heyhey_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
heyhey is really Good!

I almost passed out when I first saw nasile's codes:)
Whow thanks :)

I wish I was Rich too :)
I am sure you will be RiCh sOOn.  
BTW, how old are you?  Don't tell me
you are only a teenager, which will
make me embarrassed:)
let's say 24 - 26 :)
I am also around that age..
poor me
why'poor me' ?
you have a lot of time ...
Avatar of nasile

ASKER

HeyHey! Thanks for your help.. I ended up getting the code to work.. I havent stopped back at this site till now. Sorry for the dealy. I want to thank you for your time and input on this problem. The points are yours bud.


Thanks :)