<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*"%>
<%@ page import="javax.activation.*"%><!--要发送附件必须引入该库-->
<%@ page import="java.net.*"%><!--要用到URL类-->
<%!
public String codeToString(String str)
{//处理中文字符串的函数
String s=str;
try
{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>发送邮件结果</title>
</head>
<body>
<%
try{
String to_mail=codeToString(request.getParameter("to"));
String to_title=codeToString(request.getParameter("title"));
String to_content=codeToString(request.getParameter("content"));
Properties props=new Properties();
props.put("mail.smtp.host","smtp.sina.com");
props.put("mail.smtp.auth","true");
Session s=Session.getInstance(props);
s.setDebug(true);
MimeMessage message=new MimeMessage(s);
//--给消息对象设置发件人、收件人、主题、发信时间--
InternetAddress from=new InternetAddress("lwvc@sina.com");
message.setFrom(from);
InternetAddress to=new InternetAddress(to_mail);
message.setRecipient(Message.RecipientType.TO,to);
message.setSubject(to_title);
message.setSentDate(new Date());
//新建一个MimeMultipart对象用来存放多个BodyPart对象
Multipart mm=new MimeMultipart();
//------设置信件文本内容------
//新建一个存放信件内容的BodyPart对象
BodyPart mdp=new MimeBodyPart();
//给BodyPart对象设置内容和格式/编码方式
mdp.setContent(to_content,"text/html;charset=gb2312");
//将含有信件内容的BodyPart加入到MimeMultipart对象中
mm.addBodyPart(mdp);
//--设置信件的附件1(自定义附件:直接将所设文本内容加到自定义文件中作为附件发送)
//新建一个存放附件的BodyPart
mdp=new MimeBodyPart();
//新建一个DataHandler对象,并设置其内容和格式/编码方式
DataHandler dh=new DataHandler("大赛邀请函","text/plain; charset= gb2312");
//加上这句将作为附件发送,否则将作为信件的文本内容
mdp.setFileName("yaoqing.txt");
//给BodyPart对象设置内容为dh
mdp.setDataHandler(dh);
//将含有附件的BodyPart加入到MimeMultipart对象中
mm.addBodyPart(mdp);
//设置信件的附件2(用本地机上的文件作为附件)
mdp=new MimeBodyPart();
FileDataSource fds=new FileDataSource("D:/yaoqing.jpg");
dh=new DataHandler(fds);
mdp.setFileName("YaoQingHan.jpg");//可以和原文件名不一致
mdp.setDataHandler(dh);
mm.addBodyPart(mdp);
message.setContent(mm);//把mm作为消息对象的内容
message.saveChanges();
Transport transport=s.getTransport("smtp");
//以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址;第二个参数为用户;第三个参数为密码
transport.connect("smtp.sina.com","lwvc","lwzyjsxyjd");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
%>
<div align="center">
<p><font color="#FF6600">发送带附件的邮件到<%=to_mail%>成功!</font></p>
</div>
<%
}catch(MessagingException e){
out.println(e.toString());
}
%>
</body>
</html>