怎样使用JSP发送email?(一)

网络整理 - 07-26
下面我们通过一个简单的例子,来说明在JSP中邮件是如何发送的。该例由两个文件组成。一个是HTML文件,用来建立邮件信息(包括发送人、接收人、主题等)的表单,并将表单内容发送给JSP文件;另外一个是JSP页面,负责邮件的发送。

HTML文件
<HTML>
<BODY>
<FORM action="sendmail.jsp" method="post">
<TABLE align="center">
<TR>
<TD width="50%">
To:<BR><INPUT name="to" size="25">
</TD>
<TD width="50%">
From:<BR><INPUT name="from" size="25">
</TD>
</TR>
<TR>
<TD colspan="2">
Subject:<BR><INPUT name="subject" size="50">
</TD>
</TR>
<TR>
<TD colspan="2">
<P>Message:<BR>
<TEXTAREA name="text" rows=25 cols=85></TEXTAREA>
</P>
</TD>
</TR>
</TABLE>
<INPUT type="submit" name="cb_submit" value=" Send ">
<INPUT type="reset" name="cb_reset" value=" Clear ">
</FORM>
</BODY>
</HTML>


  JSP页面的作用就是获得表单提交过来的数据,并将这些数据赋给Java Mail API中相应的对象,最后完成邮件发送。

sendmail.jsp文件
<%@ page import=" Javax.mail.*, Javax.mail.internet.*, Javax.activation.*,Java.util.*"%>
<html>
<head>
<TITLE>JSP meets JavaMail, what a sweet combo.</TITLE>
</head>
<body>
<%
try{
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;

sendMailSession = Session.getInstance(props, null);
props.put("mail.smtp.host", "smtp.jspinsider.com");
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(request.getParameter("from")));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress ( request.getParameter ("to")));
newMessage.setSubject(request.getParameter("subject"));
newMessage.setSentDate(new Date());
newMessage.setText(request.getParameter("text"));
transport = sendMailSession.getTransport("smtp");
transport.send(newMessage);
%>
<P>Your mail has been sent.</P>
<%
}catch(MessagingException m)
{
out.println(m.toString());
}
%>
</body>
</html>