javaduke 原创于 www.dukejava.com 主页上附带演示!
MailService.java//源代码如下:(在www.mycgiserver.com调试成功)
package javaduke.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class MailService extends HttpServlet {
int index=0;
String err=null;
//Initialize global variables
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
//Service the request
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mailto=null;
String messageText="\n以下为表单内容";
mailto=request.getParameter("Email");
Enumeration keys;
String key,value;
keys=request.getParameterNames ();
while(keys.hasMoreElements ()){
key=(String)keys.nextElement ();
value=request.getParameter (key);
messageText+="\n"+key+":"+value;
}
messageText+="\n转发邮件处理程序来自\nwww.dukejava.com";
Properties pros=new Properties();
pros.put("mail.smtp.host","mycgiserver.com");
Session session=Session.getDefaultInstance(pros,null);
try{
Message message=new MimeMessage(session);
message.setSubject("DUKEJAVA.COM欢迎您光临");
message.setFrom(new InternetAddress("发信@dukejava.com"));
InternetAddress address=new InternetAddress(mailto);
message.setRecipient(Message.RecipientType.TO,address);
message.setText(messageText);
Transport.send(message);
}catch(MessagingException exa){int index=1;err=exa.toString();}
if(index==0){
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("<html>");
out.println("<head><title>MailPost</title></head>");
out.println("<body>");
out.println ("<p align=center>信息成功发送");
out.println("\n<p align=center><a href=http://www.dukejava.com>www.dukejava.com</a>提供程序");
out.println("\n<p align=center><a href=javascript:this.close();>关闭窗口</a>");
out.println("</body></html>");
out.close();
}
if(index==1){
response.setContentType("text/html");
PrintWriter out = new PrintWriter (response.getOutputStream());
out.println("<html>");
out.println("<head><title>MailPost</title></head>");
out.println("<body>");
out.println ("<p align=center>信息发送失败");
out.println ("\n<p align=center>错误原因:"+err);
out.println("\n<p align=center><a href=http://www.dukejava.com>www.dukejava.com</a>提供程序");
out.println("\n<p align=center><a href=javascript:this.close();>关闭窗口</a>");
out.println("</body></html>");
out.close();
}
}
//Get Servlet information
public String getServletInfo() {
return "javaduke.MailService Information";
}
}