mailservlet.java

来自「java的一系列产品中包括jsme,jmse,j2ee,本文件提供j2ee实现的」· Java 代码 · 共 61 行

JAVA
61
字号
package javamail;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.util.*; 
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.util.Properties;

public class MailServlet extends HttpServlet 
{
  
  public void doPost(HttpServletRequest req, HttpServletResponse res)
       throws ServletException, IOException
  {
    res.setContentType("text/html");    
    //Get the response's PrintWriter to return text to the client.
    PrintWriter toClient = res.getWriter();
    try {
    	String toText = req.getParameter("to");
    	String fromText = req.getParameter("from");
    	String subjectText = req.getParameter("subject");
    	String contentText = req.getParameter("content");
    	SendMessage.send(toText, fromText, subjectText, contentText);    

    	// Respond to client with a confirmation
    	toClient.println("<html>");
    	toClient.println("<title>Send mail</title>");
    	toClient.println("<body bgcolor=#ffffff><p>
                       "Your message has been sent</body>");
      toClient.println("</html>");
    } catch(Exception e) {
      e.printStackTrace();
      toClient.println("A problem occured while sending Mail " + e);
    }      
  }
  
  public static void send(String to, String from, String subject, String content) throws Exception {
  	Properties props = new Properties();
  	InitialContext ic = new InitialContext();
  	
  	Session session = (Session)ic.lookup("MailSession");
  	
  	Message msg = new MimeMessage(session);
  	msg.setFrom(new InternetAddress(from));
  	
  	msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
  	msg.setSubject(subject);
  	
  	msg.setSentDate(new Date());
  	msg.setContent(content, "text/plain");

  	Transport.send(msg);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?