• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Please Help, why this servlet is not working on mycgiserver

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
*************** Servlet ************************
package huzefa;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.net.*;
/**
* Form mailer servlet. Accepts the input from an HTML form and e-mails it to the specfied e-mail
* address. The form should contain a hidden variable specify the page to which the client should
* be redirected after the e-mail is sent.
*
* @author Dustin R. Callaway
*/
public class FormMailerServlet extends HttpServlet
{
private static final int PORT = 25;
private static final int LINELENGHT = 72;
private static final String MAILSERVER = "mycgiserver.com";
/**
* init method is called when servlet is first loaded
*/
public void init (ServletConfig config) throws ServletException
{
super.init (config);// pass ServletConfig to parent
}//init

public void doGet (HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType ("text/html");
PrintWriter out = res.getWriter();
out.println(" <HTML> ");
out.println(" <HEAD> ");
out.println(" <TITLE> Form Mailer </TITLE> ");
out.println(" </HEAD> ");
out.println(" <BODY> ");
out.println(" <FORM method='post'> ");// action='FormMailerServlet'> ");
out.println(" <P>To: <INPUT TYPE='text' NAME='To' SIZE='25'> </P> ");
out.println(" <P>From: <INPUT TYPE='text' NAME='From' SIZE='25'> </P> ");
out.println(" <P>Subject: <INPUT TYPE='text' NAME='Subject' SIZE='25'> </P> ");
out.println(" <P>Message: </P> ");
out.println(" <P> <TEXTAREA NAME='Message' ROWS='5' COLS='70'> </TEXTAREA> </P> ");
out.println(" ");
out.println(" <INPUT TYPE='hidden' NAME='NextPage' Value='http://www.mycgiserver.com/~huzefa/mailsent.html'> ");
out.println(" <INPUT TYPE='hidden' NAME='ErrorPage' Value='http://www.mycgiserver.com/~huzefa/mailerror.html'> ");
out.println(" ");
out.println(" <P> <INPUT TYPE='submit' NAME='Submit' Value='Submit'> </P> ");
out.println(" <P> <INPUT TYPE='reset' NAME='Reset' Value='Reset'> </P> ");
out.println(" </FORM> ");
out.println(" </BODY> ");
out.println(" </HTML> ");
out.close ();
}// doGet

/**
* doPost processes the information submitted by the client.
*/
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
String from, to, subject, message, host;
String nextPage, errorPage;
PrintWriter out = res.getWriter();
// get info form HTML form submitted by user
host = req.getServerName ();// host name of this server
from = req.getParameter ("From");
to = req.getParameter ("To");
subject = req.getParameter ("Subject");
message = req.getParameter ("Message");
message = wordWrap (message);
nextPage = req.getParameter ("NextPage");
errorPage = req.getParameter ("ErrorPage");
if (sendMail(from, to, subject, message, host))
{
// mail was sent successfully, redirect to next page
res.sendRedirect(nextPage);
//out.println (" <P> sent it </P> ");
}// if
else
{
// mail was not sent due to error, redirect to error page
res.sendRedirect(errorPage);
//out.println (" <P> did not sent it </P> ");
}// else
}// doPost
/**
* Simple implementation of SMTP protocol to send e-mail
*
* @param from The message sender address
* @param to The message recipient address
* @param subject The of the message
* @param message The message body
* @param host The name of server that is processing request
*/

boolean sendMail (String from, String to, String subject, String message, String host)
{
String line;// line of text recieved from mail server
Socket mailSocket;// socket to mail server
BufferedReader mailIn;// used to read input from mail server
PrintWriter out = null;// handle to out stream
try
{
// open socket to mail server
mailSocket = new Socket (MAILSERVER, PORT);

// get output stream to mail server
out = new PrintWriter (new OutputStreamWriter (mailSocket.getOutputStream ()));

// get input stream from mail server
mailIn = new BufferedReader (new InputStreamReader (mailSocket.getInputStream ()));
if (!checkResponse (mailIn, "220"))
{
return false;// operation failed
}
// send HELO handshake
out.println ("HELO " +host +"\r\n");
out.flush ();
if (!checkResponse (mailIn, "250"))
{
return false;// operation failed
}
// recipient information
out.print ("RCPT TO: " +to +"\r\n");
out.flush ();
if (!checkResponse (mailIn, "250"))
{
return false;// operation failed
}
// beginning of message's data portion
out.print ("DATA\r\n");
out.flush ();
if (!checkResponse (mailIn, "354"))
{
return false;// operation failed
}
// send data information
out.print ("Date: " +new Date().toString () +"\r\n");
out.flush ();
// send from information
out.print ("From " +from + "\r\n");
out.flush ();
// send subject information
out.print ("Subject " +subject +"\r\n");
out.flush ();
// tokenizer each line of message body
StringTokenizer stMessage = new StringTokenizer (message, "\n");
// send message
while (stMessage.hasMoreTokens ())
{
line = stMessage.nextToken ();// get next line (or token)
if (line.equals ("."))// replace single period with colon
line = ":";// prevents user from endin message
out.print ("\r\n.\r\n");// end message
out.flush ();
}// while
if (!checkResponse (mailIn, "250"))
{
return false;// operation failed
}
// close the session with mail server
out.print ("QUIT\r\n");
out.flush ();
if (!checkResponse (mailIn, "221"))
{
return false;// operation failed
}
}// try
catch(UnknownHostException e){ return false; }
catch(IOException e){ return false; }
finally
{
try{ out.close (); }
catch (Exception e){}
}// finally
return true;
}// sendMail
/**
* Verifies that the mail server's response is correct
*
* @param mailIn input stream from mail server
* @param valid indicates valid response code
*/
boolean checkResponse (BufferedReader mailIn, String valid)
{
String line;// stores the next line from server
try
{
line = mailIn.readLine ();// read next line from server

// return false if the line doesnot start with expected code
if (!line.startsWith (valid))
return false;
}// try
catch (IOException e){ return false; }
return true;
}// checkResponse
/**
* Wraps message lines longer than LINELENGTH
*
* @param message The message content
*/
String wordWrap(String message)
{
String word;// individual word
int column = 0, length;
StringBuffer messageBuffer = new StringBuffer ();
// tokenize the message by spaces (break into single words)
StringTokenizer words = new StringTokenizer (message, " ");
while (words.hasMoreTokens ())// iterate through each word
{
word = words.nextToken ();// set word to next token
length = word.length ();// set length of word
// words exceeds line, print on next line
if ((column > 0) && ((column + length) > LINELENGHT))
{
messageBuffer.append (word);
column = length+1;// increase column pointer
}// if external
else
{
if (word.endsWith ("\n"))
{
messageBuffer.append (word);
column = 0;// set's column pointer to zero
}// if internal
else
{
messageBuffer.append (word +" ");
column += length+1;// increase column pointer
}// else of internal if
}// else of external if
}// while

return messageBuffer.toString ();// return proceed message
}// wordWrap
/**
* Allows server to identify this servlet
*/
public String getServletInfo ()
{
return "Servlet sends e-mail based on info from HTML form";
}// getServletInfo
}// class FormMailerServlet

**************************************************
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Huzefa
That is quite a bitof code to got hrought for someone to try to help you out. Can you give us an idea of what the problem is? Are you getting an Exception or unexpected behavior?
Also, if you use the UBB code tags to surround your code it is much easier to read becasue it preserves the formatting.
 
Huzefa Zohaib
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code is not mailing.
Why?
 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would suggest that we use the code from sun which already implments SMTP protocol. If u have installed jdk from sun microsystems, then u can use the package com.sun.mail.smtp to send mails.
S.Mohamed Yousuff

Originally posted by Huzefa Zohaib:
This code is not mailing.
Why?

 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are many things that can be going wrong - you don't seem to be using any of the data contained in any exceptions that might tell us what is happening. That is a real debugging no-no.
One basic flaw is that you are using the servlet processing Thread to call the mail processor so your response may be held up interminably. Too many of these Threads hanging around can kill the servlet engine.
Mail should be sent in a separate Thread - I like to use a singleton object that has its own Thread and accepts mail data from servlets. It can write a log entry detailing whether or not the mail suceeds.
Bill
 
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by William Brogden:

Mail should be sent in a separate Thread - I like to use a singleton object that has its own Thread and accepts mail data from servlets. It can write a log entry detailing whether or not the mail suceeds.
Bill


Hi.. I have a question:
* I have a class that sends emails using javamail. The class has static methods, for example:

Whenever I need to send email from a servlet, i invoke this method. So I guess I'm using the same servlet's thread, right? and this is not good, right?
how can I solve this?
 
reply
    Bookmark Topic Watch Topic
  • New Topic