热门文章 | 热门软件| 热门源码 | 热门电影 | 知识库 | 联系我们
软件 源码 教程 影视 健康 招聘
  HTML | JavaScript | ASP | PHP | JSP | NET | VB | VC | VF | Windows | Linux | Mysql | Mssql | Oracle | Struts 
当前位置: 创世纪计算机资源网 -> 文章频道 ->jsp 
站内搜索:
jsp之发送附件的邮件(2)
作者:小红帽 来源:创世纪计算机资源网 整理日期:2007-3-17

jsp文件:

<%@ 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{
String tto=request.getParameter("to");
String tto=request.getParameter("from");
String ttitle=request.getParameter("title");

String tcontent=request.getParameter("content");

String tfj=request.getParameter("fj");


Properties props=new Properties();
props.put("mail.smtp.host","smtp.126.com");
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);

MimeMessage message=new MimeMessage(s);

//给消息对象设置发件人/收件人/主题/发信时间
InternetAddress from=new InternetAddress("jspmail123@126.com");
message.setFrom(from);
InternetAddress to=new InternetAddress(tto);
message.setRecipient(Message.RecipientType.TO,to);
message.setSubject(ttitle);
message.setSentDate(new Date());

Multipart test=new MimeMultipart();//新建一个MimeMultipart对象用来存放多个BodyPart对象

//设置信件文本内容
BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
mdp.setContent(tcontent,emailtype+";charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
test.addBodyPart(mdp);//将含有信件内容的BodyPart加入到MimeMultipart对象中

 

//设置信件的附件
mdp=new MimeBodyPart();
FileDataSource fds=new FileDataSource(tfj);
dh=new DataHandler(fds);
int ddd=tfj.lastIndexOf("\\");
String fname=tfj.substring(test.txt);//提取文件名
mdp.setFileName(test.txt);//可以和原文件名不一致,但最好一样
mdp.setDataHandler(dh);
test.addBodyPart(mdp);


message.setContent(test);//把mm作为消息对象的内容

message.saveChanges();
Transport transport=s.getTransport("smtp");
transport.connect("smtp.126.com","jspmail123","123456");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
%>
<div align="center">
<p><font color="#FF6600">发送成功!</font></p>

<br>

</div>
<%
}catch(MessagingException e){
out.println(e.toString());
}
%>
</body>
</html>

[1]  [2]  
相关文章