jsp+javamail 发送邮件全工略

配置WEB-INF
下载jaf-1_1-fr.zip,javamail-1_4.zip解压出来activation.jar,mail.jar
放入E:\WEB-INF\lib下面
最好在E:\j2sdk\lib下面也加入这2个包,让后配置CLASSPATH 加入包路径也就是
%JAVA_HOME%\lib\activation.jar;%JAVA_HOME%\lib\mail.jar;

 

1.email.htm
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>撰写邮件</title>
</head>

<body>
<form name="form1" method="post" action="send.jsp">
<table width="75" border="0" align="center" cellspacing="1" bgcolor="#006600" class="black">
<tr bgcolor="#FFFFFF">
<td width="24%">收信人地址:</td>
<td width="76%">
<input name="to" type="text" id="to"></td>
</tr>
<tr bgcolor="#FFFFFF">
<td>主题:</td>
<td>
<input name="title" type="text" id="title"></td>
</tr>
<tr>
<td height="107" colspan="2" bgcolor="#FFFFFF">
<textarea name="content" cols="50" rows="5" id="content"></textarea></td>
</tr>
<tr align="center">
<td colspan="2" bgcolor="#FFFFFF">
<input type="submit" name="Submit" value="发送">
<input type="reset" name="Submit2" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>


2.send.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%request.setCharacterEncoding("gb2312");%>
<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>发送成功</title>
</head>

<body>
<%
try{
String tto=request.getParameter("to");
String ttitle=request.getParameter("title");
String tcontent=request.getParameter("content");

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("[email protected]");  //发邮件的出发地(发件人的信箱)
message.setFrom(from);
InternetAddress to=new InternetAddress(tto);//发邮件的目的地(收件人信箱)
message.setRecipient(Message.RecipientType.TO,to);
message.setSubject(ttitle);
message.setSentDate(new Date());


//给消息对象设置内容
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
mdp.setContent(tcontent,"text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
Multipart mm=new MimeMultipart();//新建一个MimeMultipart对象用来存放BodyPart对
//象(事实上可以存放多个)
mm.addBodyPart(mdp);//将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
message.setContent(mm);//把mm作为消息对象的内容

message.saveChanges();
Transport transport=s.getTransport("smtp");
transport.connect("smtp.163.com","username","password");//发邮件人帐户密码
transport.sendMessage(message,message.getAllRecipients());
transport.close();
%>
<div align="center">
<p><font color="#FF6600">发送成功!</font></p>
</div>
<%
}catch(MessagingException e){
out.println(e.toString());
}
%>
</body>
</html>

你可能感兴趣的:(jsp+javamail 发送邮件全工略)