jsp中群发邮件
1、获取需要的jar文件,mail.jar(http://java.sun.com/products/javamail/)和activation.jar(http://java.sun.com/products/javabeans/glasgow/jaf.html),将activation.jar和mail.jar复制到应用程序的\\WEB-INF\\lib中,即可使用。
2、sendmail.jsp文件代码:
<% @page contentType=\"text/html;charset=gb2312\"%>
<%@ page import=\"java.sql.*,java.io.*,java.util.*,java.text.*, javax.mail.*, javax.mail.internet.*\" %>
<jsp:useBean id=\"connBean\" scope=\"session\" class=\"opendb.opendb\"/><html>
<head>
<title>JavaMail 电子邮件发送系统</title>
</head>
<body>
<%
String userName = (String)session.getAttribute(\"userName\");
String figure = (String)session.getAttribute(\"figure\");
String from = \"\";
String to = \"\";
ResultSet rs = null;
String smtphost = \"smtp.yeah.net\"; // 发送邮件服务器
String user = \"zyf0808\"; // 填写自己的邮件服务器登录用户名
String password = \"123456789\"; // 填写你自己的邮件服务器登录密码
String subject = connBean.change(request.getParameter(\"txtSubject\")); // 邮件标题
String body =connBean.change(request.getParameter(\"txtContent\"));// 邮件内容
if(userName!=null && !userName.equals(\"\"))
{
ResultSet rst = connBean.ExecuteQuery(\"SELECT Email FROM Classmates WHERE UserName = ’\"+userName+\"’ \");
if (rst.next())
from = rst.getString(\"Email\"); //发件人地址
else from = \"zyf0808@yeah.net\"; //换成可用的管理员的邮箱地址
}
else
{
//未登录
%>
<SCRIPT language=\"JavaScript\">
alert(\"对不起,您尚未登录,只有登录的管理员同学才能使用该功能!\")
window.location.replace(\"../login.jsp\");
</SCRIPT>
<%
}
//得到除当前登录管理员外的所有用户的邮箱
rs = connBean.ExecuteQuery(\"SELECT Email FROM Classmates WHERE UserName <> ’\"+userName+\"’\");
while (rs.next())
{
to = rs.getString(\"Email\"); // 接受人邮件地址
if (to !=null && !to.equals(\"\") )
{
try
{
Properties props = new Properties();
props.put(\"mail.smtp.host\", smtphost);
props.put(\"mail.smtp.auth\",\"true\");
Session ssn = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(ssn); [Page]
InternetAddress fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
InternetAddress toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
Transport transport = ssn.getTransport(\"smtp\");
transport.connect(