SendMailServlet.java
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:3k
源码类别:
Java编程
开发平台:
Java
- package bible.javamail;
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.util.*;
- import javax.activation.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- import javax.naming.*;
- /**
- * Class SendMailServlet
- *
- *
- * @author
- * @version %I%, %G%
- */
- public class SendMailServlet extends HttpServlet {
- private String to = "";
- private String subject = "";
- private String messageText = "";
- private String successMessage = "";
- /**
- * Method doGet
- *
- *
- * @param req
- * @param res
- *
- * @throws IOException
- * @throws ServletException
- *
- */
- public void doGet(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- PrintWriter pw = res.getWriter();
- res.setContentType("text/html");
- pw.println("<HTML><HEAD><TITLE>Send Mail - Simple</TITLE></HEAD>");
- pw.println("<BODY><H1>Send Mail - Simple</H1>");
- pw.println("<FORM ACTION='sendmail' METHOD=post><TABLE>");
- pw.println("<TR><TD>To:</TD><TD><INPUT NAME=to size=60></TD></TR>");
- pw.println("<TR><TD>Subject:</TD><TD><INPUT NAME=subject size=60>"
- + "</TD></TR>");
- pw.println("<TR><TD VALIGN>Message:</TD>");
- pw.println("<TD><TEXTAREA NAME=messageText rows=10 cols=60>"
- + "</TEXTAREA></TD></TR>");
- pw.println("<TR><TD><INPUT TYPE=SUBMIT NAME=Submit VALUE=Submit>"
- + "</TD></TR>");
- pw.println("</TABLE></FORM>");
- pw.println("<STRONG>" + successMessage + "</STRONG>");
- pw.println("</BODY></HTML>");
- }
- /**
- * Method doPost
- *
- *
- * @param req
- * @param res
- *
- * @throws IOException
- * @throws ServletException
- *
- */
- public void doPost(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- to = req.getParameter("to");
- subject = req.getParameter("subject");
- messageText = req.getParameter("messageText");
- sendMessage();
- doGet(req, res);
- }
- /**
- * Method sendMessage
- *
- *
- */
- public void sendMessage() {
- try {
- // lookup mail session in JNDI
- InitialContext context = new InitialContext();
- Session session = (Session) context.lookup("BibleMailSession");
- // set message with to, subject, and message text
- Message msg = new MimeMessage(session);
- // set message with to, subject, and message text
- msg.setFrom();
- msg.setRecipients(Message.RecipientType.TO,
- InternetAddress.parse(to, false));
- msg.setSubject(subject);
- msg.setSentDate(new Date());
- msg.setText(messageText);
- // send message
- Transport.send(msg);
- successMessage = "Message sucessfully sent.";
- session = null;
- } catch (Exception e) {
- successMessage = e.getMessage();
- }
- }
- }
- /*--- Formatted in Bible Style on Thu, Sep 6, '01 ---*/
- /*------ Formatted by Jindent 3.24 Gold 1.02 --- http://www.jindent.de ------*/