这段时间编写一个小程序发送邮件,邮件是把正文和附件合成一个eml文件再发送出去的。加载附件,需要输入流,也就需要知道文件绝对路径了。但是在jsp的环境下,都是以服务器为前提的,在后端编写获取的文件地址是服务器所在的路径。怎么获取客户端这边的绝对路径呢!上网找了很多资料,解决是能解决,不过要不同的浏览器以不同的编码来处理,真的很麻烦啊!
var path = document.getElementById("att").value;
alert(path);
这段代码显示出的地址 X:\fakepath\xxx.xx。为了安全性,现在的浏览器都做了处理。没办法,只好把附件放在服务器里面再发送邮件了。网页上的那些邮箱上传附件都显示进度条,可见也是上传到服务器上再做处理的。后期代码完善也就多编写一个上传文件的功能就行了。
jsp这边的代码为:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'sendmail.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function validate_form(form1){
var path = document.getElementById("att").value;
alert(path);
if(form1.subject.value.length==0){
alert("确认无主题?");
return true;
}else if(form1.content.value.length==0){
alert("确认无内容?");
return true;
}else{
return true;
}
}
</script>
</head>
<body>
<form action="<%=request.getContextPath()%>/SendMail" method="post" οnsubmit="return validate_form(this);" name="form1">
收件人:<input type="text" name="to" />(多地址请用英文逗号隔开) <br>
主 题:<input type="text" name="subject" /><br>
附 件:<input type="file" name="att" id="att"/>(附件必须放在tomcat服务器该项目的根目录下)<br>
内容:<br>
<textarea rows="20" cols="45" name="content"></textarea><br>
<input type="hidden" id="filePath" name="filePath" />
<input type="submit" value="发送"/>
<input type="reset" value="重置"/><br>
</form>
</body>
</html>
本来就是想在前端用javascript处理后通过隐藏域传递过去这个绝对路径了,看来现在行不通了。
servlet这边的代码为:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("unused")
public class SendMail extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -3314519831125334628L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response) ;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
boolean flag = false ; //true为有附件,false为无附件
String att = null ;
String path = null ;
final String from = (String) request.getSession().getAttribute("from") ;
final String password = (String) request.getSession().getAttribute("password") ;
String to = request.getParameter("to").trim() ; //获取收件人地址并去掉前后空格
if(request.getParameter("att") != null && !request.getParameter("att").equals("")){ //如果有附件,获取附件路径
att = new String(request.getParameter("att").getBytes("ISO-8859-1"),"utf-8") ;
path = request.getSession().getServletContext().getRealPath(att);
flag = true ;
}
String subject = new String(request.getParameter("subject").getBytes("ISO-8859-1"),"utf-8") ; //乱码处理
String content = new String(request.getParameter("content").getBytes("ISO-8859-1"),"utf-8") ; //乱码处理
Properties props = new Properties() ;
props.setProperty("mail.smtp.auth", "true") ; //授权校验
props.setProperty("mail.transport.protocol", "smtp") ; //设置发送邮件协议
props.setProperty("mail.host", "smtp.163.com") ; //设置发送邮件服务器
Session session = Session.getInstance(props, //创建一个session对象
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(from, password) ;
}
}
) ;
session.setDebug(true) ; //打印日志
Message msg = new MimeMessage(session) ;
try {
msg.setSubject(subject) ; //设置主题
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)) ; //设置收件人
msg.setFrom(new InternetAddress(from)) ; //设置发件人
MimeMultipart msgMultipart = new MimeMultipart("mixed") ; //混合模式的邮件格式
msg.setContent(msgMultipart) ;
MimeBodyPart content1 = new MimeBodyPart() ; //邮件正文
msgMultipart.addBodyPart(content1) ;
if(flag){ //true为有附件
MimeBodyPart attch1 = new MimeBodyPart() ; //邮件附件
msgMultipart.addBodyPart(attch1) ; //给邮件加载附件
DataSource ds1 = new FileDataSource(path) ;
DataHandler dh1 = new DataHandler(ds1) ;
attch1.setDataHandler(dh1) ;
attch1.setFileName(MimeUtility.encodeText(att)) ; //给上传的附件命名并处理中文乱码
}
MimeMultipart bodyMultipart = new MimeMultipart("related") ; //邮件正文设置混合模式,可以同时显示文字和图片等
content1.setContent(bodyMultipart) ;
MimeBodyPart htmlPart = new MimeBodyPart() ; //正文加载html格式的文字
//MimeBodyPart gifPart = new MimeBodyPart() ; //正文加载显示图片
bodyMultipart.addBodyPart(htmlPart) ;
//bodyMultipart.addBodyPart(gifPart) ;
//DataSource gifds = new FileDataSource("C:\\Users\\lhx\\Pictures\\fgh.jpg") ;
//DataHandler gifdh = new DataHandler(gifds) ;
//gifPart.setDataHandler(gifdh) ;
//gifPart.setHeader("Content-Location", "http://www.sina.com") ;
htmlPart.setContent("<html><head><title>lhx</title></head><body><center>" +
"<h2><font color='BLUE'>韩</h2>" + content +
"<h3><a href='http://www.sina.com'>新浪网</h3> " +
"</center></body></html>", "text/html;charset=gbk") ;
msg.saveChanges() ; //生成eml邮件
Transport.send(msg) ; //发送邮件
response.sendRedirect(request.getContextPath() + "/success.jsp") ; //邮件发送成功跳转的页面
} catch (MessagingException e) {
response.sendRedirect(request.getContextPath() + "/fail.jsp") ; //邮件发送失败跳转的页面
e.printStackTrace();
}
}
}
用request.getSession().getServletContext().getRealPath(att)来获取表单这边提交过来的路径,不过这个路径一定是服务器项目名称跟目录下后面带附件名称这样的地址,根目录下的子目录都不能存放附件,否则上传都会出错误。比如附件一定要是:C:\tomcat7.0\webapps\javamail_web\xxx.xx
后期完善的话就是上传附件,马上知道这个附件放在服务器项目目录哪个地方了,把这个相对路径记住再做处理就行了。