如何实现servlet中的发信功能?

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";
}
}


  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值