|
What this is
This file is included in the DevDaily.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn
Java by Example" TM.
Other links
The source code
/**
* CSMailForm.java
*
* Bill Lynch
* CoolServlets.com
* April 21 1999
*
* CSMailForm Version 1.1
*
* Copyright (C) 1999 Bill Lynch
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;
import com.coolservlets.*;
import com.coolservlets.email.*;
/**
* This is a servlet that takes input from HTML forms and sends an
* email with the given information. It uses the CSEmail package 1.1
*
* @author Bill Lynch
* @version 1.1
*/
public class CSMailForm extends HttpServlet
{
/**
* Initialize global variables
*/
public void init( ServletConfig config ) throws ServletException
{
super.init( config );
propertiesLoaded = false;
}
/**
* Process the HTTP Get request
*/
public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException
{ doPost( req, res );
}
/**
* Process the HTTP Post request
*/
public void doPost( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException
{
boolean error=false, doProps=false;
res.setContentType( "text/html" );
PrintWriter out = res.getWriter();
// Check to see if the properties are loaded. If not, load them.
// This also checks for errors (ie, if the property file is not there).
if( !propertiesLoaded )
{ propertiesLoaded = true;
try
{ MailFormProperties = readProperties();
smtpHost = getProperty( "smtpServer" );
smtpPort = Integer.parseInt( getProperty( "smtpPort" ) );
} catch( IOException ioe )
{ propertiesLoaded = false;
error = true;
out.println( "Error reading properties.<br>This error will be resolved as soon as possible." );
}
}
// Check to see if the servlet has been called with no parameters:
if( !error )
{ Enumeration enum = req.getParameterNames();
if( !enum.hasMoreElements() )
{ error = true;
printError( out, "<html>\n"
+ "Error: no parameters were given." );
}
}
// Check if we need to reload or display the properties:
if( !error )
{ String props = req.getParameter( "properties" );
if( props != null )
{ if( props.toLowerCase().compareTo( "reload" ) == 0 )
{ doProps = true;
try
{ MailFormProperties = readProperties();
smtpHost = getProperty( "smtpServer" );
smtpPort = Integer.parseInt( getProperty( "smtpPort" ) );
} catch( IOException ioe )
{ out.println( "Error reading properties" );
error = true;
}
out.println( "<html>\n"
+ "Properties reloaded successfully.<br>"
+ "To display your properties, use the argument: <b>CSMailForm?properties=display" );
}
else if( props.toLowerCase().compareTo( "display" ) == 0 )
{ doProps = true;
String allowPropsDisplay = null;
try
{ allowPropsDisplay = getProperty( "displayProperties" );
} catch( IOException ioe )
{ out.println( "Unable to read from properties file. Please try again.<br>" );
}
if( allowPropsDisplay != null && allowPropsDisplay.toLowerCase().compareTo( "yes" ) == 0 )
{ out.println( "<font face=\"arial,helvetica\">Your CSMailForm Properties: " );
Enumeration name = MailFormProperties.propertyNames();
Enumeration vals = MailFormProperties.elements();
out.println( "<ul>" );
while( name.hasMoreElements() )
{ out.println( "<li>" + "" + (String)name.nextElement() + "" + " = "
+ (String)vals.nextElement()
+ "<br>" );
}
out.println( "</ul>" );
}
else
{ out.println( "<html>\n"
+ "Sorry, the administrator of this servlet has disallowed "
+ "viewing of the properties." );
}
}
}
}
if( !error && !doProps )
{ // Check to see if the referrer is valid
boolean refererOk = true;
String httpReferer = req.getHeader( "Referer" );
String allowedRemoteHost = null;
try
{ allowedRemoteHost = getProperty( "validHostName" );
} catch( IOException ioe )
{ out.println( "Error reading properties." );
}
if( httpReferer != null )
{ URL u = new URL( httpReferer );
if( u.getHost().compareTo( allowedRemoteHost ) != 0 )
refererOk = false;
}
if( !refererOk )
{ out.println( "<html>"
+ "Error invalid host referrer.<br>" );
}
else
{ // Get the parameters
String to = req.getParameter( "to" );
String toName = req.getParameter( "toName" );
String toEmail = req.getParameter( "toEmail" );
String fromName = req.getParameter( "fromName" );
String fromEmail = req.getParameter( "fromEmail" );
String cc = req.getParameter( "cc" );
String bcc = req.getParameter( "bcc" );
String required = req.getParameter( "required" );
String timestamp = req.getParameter( "timestamp" );
String redirect = req.getParameter( "redirect" );
String subject = req.getParameter( "subject" );
String message = req.getParameter( "message" );
String response = req.getParameter( "response" );
String title = req.getParameter( "title" );
String fontFace = req.getParameter( "fontFace" );
String fontSize = req.getParameter( "fontSize" );
String linkBack = req.getParameter( "linkBack" );
String textBack = req.getParameter( "textBack" );
String background = req.getParameter( "background" );
String bgcolor = req.getParameter( "bgcolor" );
String text = req.getParameter( "text" );
String link = req.getParameter( "link" );
String vlink = req.getParameter( "vlink" );
String alink = req.getParameter( "alink" );
String reqError = req.getParameter( "reqError" );
String onErrorPg = req.getParameter( "onErrorPage" );
// Add a timestamp if so desired...
if( timestamp != null && timestamp.length() > 0 )
if( timestamp.toLowerCase().compareTo( "yes" ) == 0 )
message = "This message was sent on: " + (new Date()) + "\n\n" + message;
// Check that the required fields have actually been filled out
Vector errors = new Vector();
boolean fieldErrors = false;
if( required != null )
fieldErrors = checkRequiredFields( required, req, errors );
// If there are errors, print them out.
if( fieldErrors )
{ if( reqError == null )
{ reqError = "<html>"
+ "<font face=\"arial,helvetica\">"
+ "Oops! You forgot to fill in the following fields:"
+ "</b>";
}
out.println( reqError );
out.println( "<ul>" );
for( int i=0; i<errors.size(); i++ )
out.println( "<li>" + (String)errors.elementAt(i) );
out.println( "</ul>" );
}
else // no errors, so continue
{ // Create message and transport objects:
Message msg = new Message();
Transport tr = new Transport( smtpHost, smtpPort );
// Now check for a redirect
boolean wasRedirect = false;
if( redirect != null && redirect.length() > 0 )
wasRedirect = true;
// Add cc, bcc and to lists (comma-delimited strings of
// names and/or email addresses
if( to != null && to.length() > 0 )
{ Address[] toAddr = Address.parse( to );
msg.setRecipients( RecipientType.TO, toAddr );
}
else if( toEmail != null && toEmail.length() > 0 )
{ if( toName != null && toName.length() > 0 )
msg.setRecipient( RecipientType.TO, new Address( toName, toEmail ) );
else
msg.setRecipient( RecipientType.TO, new Address( toEmail ) );
}
if( cc != null && cc.length() > 0 )
{ Address[] ccAddr = Address.parse( cc );
msg.setRecipients( RecipientType.CC, ccAddr );
}
if( bcc != null && bcc.length() > 0 )
{ Address[] bccAddr = Address.parse( bcc );
msg.addRecipients( RecipientType.BCC, bccAddr );
}
// Set the rest of the details of the message
if( ( fromName != null && fromName.length() > 0 ) &&
( fromEmail!= null && fromEmail.length()> 0 ) )
msg.setFrom( new Address( fromName, fromEmail ) );
else
if( fromEmail != null && fromEmail.length() > 0 )
msg.setFrom( new Address( fromEmail ) );
// Set the subject
if( subject != null && subject.length() > 0 )
msg.setSubject( subject );
// Set the message text
if( message != null && message.length() > 0 )
msg.setText( message );
// Send the email!
boolean sendError = false;
try
{ tr.send( msg );
}
catch( TransportException te )
{ out.println( "<p>" + te + "" );
sendError = true;
}
catch( Exception e )
{ out.println( "exception e: " + e + "<p>" );
}
// Check if there were sending errors... If so, print them
if( wasRedirect && !sendError )
res.sendRedirect( redirect );
if( sendError )
{ if( onErrorPg != null && onErrorPg.length() > 0 )
res.sendRedirect( onErrorPg );
else
{
out.println( "<font face=\"arial,helvetica\">"
+ "Sorry, we're unable to send the email right now.<br> "
+ "Please try again later or contact the system administrator."
+ "</b>" );
}
}
else
{ // Here's where the return page is constructed:
// Default styles will be used if none are specified through parameters
if( response == null ) response = "Thank you for your feedback!";
if( title == null ) title = "Thanks!";
if( fontFace == null ) fontFace = "arial,helvetica";
if( fontSize == null ) fontSize = "3";
if( linkBack == null ) linkBack = "http://www.coolservlets.com/";
if( textBack == null ) textBack = "Go Back";
if( background == null ) background = "";
if( bgcolor == null ) bgcolor = "#ffffff";
if( text == null ) text = "#000000";
if( link == null ) link = "#0000ff";
if( vlink == null ) vlink = "#800080";
if( alink == null ) alink = "#ff0000";
out.println( "<html>" );
out.println( "<head>" + title + "" );
// use buffers for a little more string efficiency
StringBuffer body = new StringBuffer();
body.append( "<body background=\""+background+"\" " );
body.append( "bgcolor=\""+bgcolor+"\" " );
body.append( "text=\""+text+"\" " );
body.append( "link=\""+link+"\" " );
body.append( "vlink=\""+vlink+"\" " );
body.append( "alink=\""+alink+"\">" );
out.println( body.toString() ); // now BODY tag is out the door
out.println( "<font face=\""+fontFace+"\" size="+fontSize+">" );
out.println( response );
out.println( "<p> " );
out.println( "<a href=\""+linkBack+"\">"+textBack+"" );
}
} //else from field error check
} // if from ok host
} // if from !error
out.println( "</body>" );
out.println( "</html>" );
out.close( );
}
/**
* Checks required fields by looping through the list of specified fields
* and checks them against what was actually submitted.
*/
private boolean checkRequiredFields( String s, HttpServletRequest req, Vector errorsVec )
{ boolean errors=false;
StringTokenizer st = new StringTokenizer( s, "," );
String tok="";
while( st.hasMoreTokens() )
{ tok = st.nextToken();
if( req.getParameter( tok ) == null || req.getParameter( tok ).length() == 0 )
{ errorsVec.addElement( tok );
errors=true;
}
}
return errors;
}
/**
* Reads the properties file.
*/
private synchronized Properties readProperties() throws IOException
{ Properties tempProperties = new Properties();
FileInputStream in = new FileInputStream("coolservlets/config/MailFormProperties");
tempProperties.load(in);
return tempProperties;
}
/**
* Returns specified property
*/
private String getProperty( String prop ) throws IOException
{ return ( MailFormProperties.getProperty( prop ) );
}
/**
*
*/
private void printError( PrintWriter out, String msg )
{ out.print( msg );
}
/**
* Get Servlet information
*/
public String getServletInfo()
{ return "CSMailForm - A servlet to send email throught HTML forms.";
}
private StringTokenizer st;
private String token = "";
private Properties MailFormProperties;
private String smtpHost;
private int smtpPort;
private boolean propertiesLoaded;
}
|