jsp实现email发送

来源:互联网 发布:云计算试点城市 编辑:程序博客网 时间:2024/06/09 13:47

先说一下前提,首先不是光有jsp代码和jar包就能成事的,因为整个email传输需要服务器提供服务,所以务必先架设好邮件服务器,如果你本地没有邮件服务器,起码也要能够连接到一个可以利用的邮件服务器,我这里先用了hmailserver开源软件假设邮件服务器,假设国产不赘述,参考如下链接:

 

http://allanfan.blog.51cto.com/520839/385003/

 

用以上链接做好了以后,先用自己的客户端软件(如foxmail,网易闪电邮)测试一下,如果能够使用,则说明服务器假设成功。

 

然后再开始写Jsp代码(或者java代码,都一样),当然由于jdk当前版本还没有加入邮件方面的api,所以要引用一个额外的包叫做javamail api的,可以到google搜索,官方下载,挺小的,下载后解压,把lib文件夹下的所有Jar包拷贝到当前项目的classpath下面,然后写jsp测试页面如下:

<html>
<head>
<title>JSP JavaMail Example </title>
</head>
<body>
<%@ page import="java.util.*" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>
<%
String host = "localhost";
String to = "10210240124@fudan.edu.cn";
String from = "hexie0@fengchang.cn";
String subject = "bitchtest";
String messageText = "loveyou";
boolean sessionDebug = false;
// Create some properties and get the default Session.
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
 
// Set debug on the Session
// Passing false will not echo debug info, and passing True will.
 
mailSession.setDebug(sessionDebug);
 
// Instantiate a new MimeMessage and fill it with the
// required information.
 
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
 
// Hand the message to the default transport service
// for delivery.
 
Transport.send(msg);
out.println("Mail was sent to " + to);
out.println(" from " + from);
out.println(" using host " + host + ".");
%>
</body>
</html>

 

搞掂。

原创粉丝点击