再想它法了,對,就是 XMLHttpRequest,把功能分離,Excel 只提交 Http 請求,由 JSP 來完成實(shí)際的郵件發(fā)送工作,當(dāng)然也可以實(shí)現(xiàn)為其他的形式。所以也就有兩部分實(shí)現(xiàn)代碼,分別為:
JSP 代碼,使用的是 Apache 的 commons-email 組件,它還需要用到 activation.jar 和 mail.jar,關(guān)于 commons-email 的使用可參考前面的一篇:用 apache commons-email 輕松發(fā)送無亂碼郵件。比如文件存為 sendmail.jsp,通過瀏覽器來訪問時用的 URL 是 http://192.168.1.100:8080/WebUtils/sendmail.jsp:
01.<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
02.<%@ page import="org.apache.commons.mail.*,java.net.*"%>
03.<%
04.
05./*發(fā)送郵件的頁面,只允許以 post 方式提交
06. 參數(shù)說明:
07. to: 郵件接收人
08. subject: 郵件標(biāo)題
09. body: 郵件正文
10.*/
11.
12.String method = request.getMethod();
13.
14.if(method.equalsIgnoreCase("post")){ //只處理 post 請求
15.
16. //把請求的字符集設(shè)為 iso8859-1,然后調(diào)用 toUTF8 來解決亂碼問題
17. request.setCharacterEncoding("iso8859-1");
18. String to = toUTF8(request.getParameter("to"));
19. String subject = toUTF8(request.getParameter("subject"));
20. String body = toUTF8(request.getParameter("body"));
21.
22. // 發(fā)送帶附件及HTML內(nèi)容的郵件
23. HtmlEmail email = new HtmlEmail();
24. email.setHostName("smtp.sina.com");
25.
26. // 需要郵件發(fā)送服務(wù)器驗(yàn)證,用戶名/密碼
27. email.setAuthentication("fantasia", "xxxxxx");
28. email.addTo(to);
29. email.setFrom("fantasia@sina.com", "Unmi");
30.
31. // 設(shè)置主題的字符集為UTF-8
32. email.setCharset("UTF-8");
33. email.setSubject(subject);
34. try{
35. email.setHtmlMsg(body);
36. email.attach(new URL("file:///c|SendMail.java"), "SendMail.java","SendMail.java");
37. email.buildMimeMessage();
38. email.send();
39. out.print("發(fā)送成功");
40. }catch(Exception ex){
41. out.print(ex.getMessage());
42. }
43.}
44.%>
45.<%!
46. private String toUTF8(String src) throws UnsupportedEncodingException{
47. String dst = new String(src.getBytes("ISO8859-1"),"UTF-8");
48. return dst;
49. }
50.%>