JSP发邮件

用JSP发邮件的示例,注意要将mail.jar和servlet-api.jar放到lib下。否则会抛出下面异常:
Session cannot be resolved to a type
...
MimeMessage cannot be resolved to a type
...
InternetAddress cannot be resolved to a type
...
Message.RecipientType.TO cannot be resolved to a type
...

转帖代码如下:
<%@ page contentType="text/html;charset=gb2312"%>
<% request.setCharacterEncoding("gb2312");%><!--中文处理代码-->
<!--引入要用到的类库-->
<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*"%>
<%@ page import="javax.activation.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>发送成功</title>
</head>
<body>
<%
  try {
    //从html表单中获取邮件信息  
    String tto = "[email protected]";
    String ttitle = "邮件标题";
    String tcontent = "邮件内容";
    String username = "[email protected]";
    String pass = "pwd";
    String from1 = "[email protected]";

    Properties props = new Properties();////获得系统属性对象  
    props.put("mail.smtp.host", "smtp.163.com");//存储发送邮件服务器的信息  
    props.put("mail.smtp.auth", "true");//同时通过验证  
    Session s = Session.getInstance(props);//根据属性新建一个邮件会话  
    s.setDebug(true);

    MimeMessage message = new MimeMessage(s);//由邮件会话新建一个消息对象  

    //设置邮件  
    InternetAddress from = new InternetAddress(from1);
    message.setFrom(from);//设置发件人  
    InternetAddress to = new InternetAddress(tto);
    message.setRecipient(Message.RecipientType.TO, to);//设置收件人,并设置其接收类型为TO  
    message.setSubject(ttitle);//设置主题  
    message.setText(tcontent);//设置信件内容  
    message.setSentDate(new Date());//设置发信时间  

    //发送邮件  
    message.saveChanges();//存储邮件信息  
    Transport transport = s.getTransport("smtp");
    transport.connect("smtp.163.com", username, pass);//以smtp方式登录邮箱  
    transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有  
    //已设好的收件人地址  
    transport.close();
%>
<div align="center">
<p><font color="#FF6600">发送成功!</font></p>
<p><a href="recmail.jsp">去看看我的信箱</a><br>
<br>
<a href="index.htm">再发一封</a></p>
</div>
<%
	} catch (MessagingException e) {
		out.println(e.toString());
	}
%>
</body>
</html>

你可能感兴趣的:(html,jsp,servlet)