📄 csmailform.java
字号:
//CSMailForm.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;
import com.coolservlets.*;
import com.coolservlets.email.*;
public class CSMailForm extends HttpServlet
{
/**
* 初始化全局变量
*/
public void init( ServletConfig config ) throws ServletException
{
//初始化配置信息
super.init( config );
propertiesLoaded = false;
}
/**
* 处理HTTP 的Get的请求
*/
public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException
{ doPost( req, res );
}
/**
* 处理HTTP 的Post请求
*/
public void doPost( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException
{
boolean error=false, doProps=false;//设置标志位
res.setContentType( "text/html" );//设置文件类型
PrintWriter out = res.getWriter();//为输出流
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." );
}
}
//检测如果Serverlet 在无参数的情况下被调用
if( !error )
{ Enumeration enum = req.getParameterNames();
if( !enum.hasMoreElements() )
{ error = true;
printError( out,"<html><body bgcolor=\"#ffffff\">\n"
+ "Error: no parameters were given." );
}
}
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><body bgcolor=\"#ffffff\">\n"
+ "Properties reloaded successfully.<br>"
+ "To display your properties, use the argument: <b>CSMailForm?properties=display</b>" );
}
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\"><b>Your CSMailForm Properties: </b></font><br>" );
Enumeration name = MailFormProperties.propertyNames();
Enumeration vals = MailFormProperties.elements();
out.println( "<ul>" );
while( name.hasMoreElements() )
{ out.println( "<li>" + "<b>" + (String)name.nextElement() + "</b>" + " = "
+ (String)vals.nextElement()
+ "<br>" );
}
out.println( "</ul>" );//打印信息
}
else
{ out.println( "<html><body bgcolor=\"#ffffff\">\n"
+ "Sorry, the administrator of this servlet has disallowed "
+ "viewing of the properties." );
}
}
}
}
if( !error && !doProps )
{ //检测是否有效
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><body bgcolor=\"#ffffff\">"
+ "Error invalid host referrer.<br>" );
}
else
{ //获取各类参数信息
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" );
//如果需要就添加邮戳
if( timestamp != null && timestamp.length() > 0 )
if( timestamp.toLowerCase().compareTo( "yes" ) == 0 )
message = "This message was sent on: " + (new Date()) + "\n\n" + message;
//检测是否需要的区域已经被填充
Vector errors = new Vector();
boolean fieldErrors = false;
if( required != null )
fieldErrors = checkRequiredFields( required,req,errors );
// 如果有错误,打印出来
if( fieldErrors )
{ if( reqError == null )
{ reqError = "<html><body bgcolor=\"#ffffff\">"
+ "<font face=\"arial,helvetica\"><b>"
+ "Oops! You forgot to fill in the following fields:"
+ "</b></font>";
}
//打印错误信息
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 //无错误,则继续
{ // 创建信息并发送
Message msg = new Message();
Transport tr = new Transport( smtpHost,smtpPort );
// 检测并重定向
boolean wasRedirect = false;
if( redirect != null && redirect.length() > 0 )
wasRedirect = true;
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 );
}
// 设置信息的剩余细节
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 ) );//设置信息来源
// 设置主体
if( subject != null && subject.length() > 0 )
msg.setSubject( subject );
// 设置信息的文本内容
if( message != null && message.length() > 0 )
msg.setText( message );
// 发送电子邮件
boolean sendError = false;
try
{ tr.send( msg );
}
catch( TransportException te )
{ out.println( "<p>" + te + "<p>" );
//设置为发送信息错误
sendError = true;
}
catch( Exception e )
{ out.println( "exception e: " + e + "<p>" );
}
// 检测是否有发送错误,如果没有则打印出来
if( wasRedirect && !sendError )
res.sendRedirect( redirect );
if( sendError )
{ if( onErrorPg != null && onErrorPg.length() > 0 )
//发送重定向信息
res.sendRedirect( onErrorPg );
else
{
out.println( "<font face=\"arial,helvetica\"><b>"
+ "Sorry, we're unable to send the email right now.<br><br>"
+ "Please try again later or contact the system administrator."
+ "</b></font>" );
}
}
else
{
// 如果没有被指定默认形式被使用 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>" + title + "</title></head>" );
// 使用缓冲,在实体部分添加各种信息
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><hr>" );
out.println( "<a href=\""+linkBack+"\">"+textBack+"</a>" );
}
}
}
}
out.println( "</body>" );
out.println( "</html>" );
out.close( );
}
/**
*通过循环方式检测被请求的区域
*/
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;//返回错误信息
}
/**
* 读取属性文件
*/
private synchronized Properties readProperties() throws IOException
{ Properties tempProperties = new Properties();
FileInputStream in = new FileInputStream("coolservlets/config/MailFormProperties");
tempProperties.load(in);
return tempProperties;//返回临时信息
}
/**
* 返回特殊的属性
*/
private String getProperty( String prop ) throws IOException
{ return ( MailFormProperties.getProperty( prop ) );
}
private void printError( PrintWriter out,String msg )
{ out.print( msg );//打印错误信息
}
/**
* 获取Servlet 信息
*/
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;//采用SMTP协议
private int smtpPort;
private boolean propertiesLoaded;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -