分享

VBA 中发送邮件(三. 使用 XMLHttpRequest 组件)

 dudu1206dudu 2010-07-09

VBA 中发送邮件(三. 使用 XMLHttpRequest 组件)

w3 JMail 组件虽好用,但实际使用过程中还是碰到问题,多数机器上都表现正常,唯独在一台机器上,JMail 的错误信息总是:jmail The message was undeliverable. All servers failed to receive the message。根据经验把病毒软件、防火墙都关了,Telnet 到邮件服务器的 25 端口,或者 Outlook 收发都是正常的,这下有些没辙了,而同事真正又要在那台奇怪的机器上发邮件。

  再想它法了,对,就是 XMLHttpRequest,把功能分离,Excel 只提交 Http 请求,由 JSP 来完成实际的邮件发送工作,当然也可以实现为其他的形式。所以也就有两部分实现代码,分别为:

  JSP 代码,使用的是 Apache 的 commons-email 组件,它还需要用到 activation.jar 和 mail.jar,关于 commons-email 的使用可参考前面的一篇:用 apache commons-email 轻松发送无乱码邮件。比如文件存为 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./*发送邮件的页面,只允许以 post 方式提交
06.  参数说明:
07.  to: 邮件接收人
08.  subject: 邮件标题
09.  body:   邮件正文
10.*/
11. 
12.String method = request.getMethod();
13. 
14.if(method.equalsIgnoreCase("post")){ //只处理 post 请求
15. 
16.     //把请求的字符集设为 iso8859-1,然后调用 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.     // 发送带附件及HTML内容的邮件
23.     HtmlEmail email = new HtmlEmail();
24.     email.setHostName("smtp.sina.com");
25. 
26.     // 需要邮件发送服务器验证,用户名/密码
27.     email.setAuthentication("fantasia", "xxxxxx");
28.     email.addTo(to);
29.     email.setFrom("fantasia@sina.com", "Unmi");
30. 
31.     // 设置主题的字符集为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("发送成功");
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.%>
 
VBA 代码,在它的 Visual Basic 的编辑器中需要引用 Microsoft XML, v6.0 (或者其他相应版本,如 v2.6、v3.0、v4.0、v5.0):VBA 代码,在它的 Visual Basic 的编辑器中需要引用 Microsoft XML, v6.0 (或者其他相应版本,如 v2.6、v3.0、v4.0、v5.0):

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多