⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 javamailservlet.java

📁 SUN的JAVA MAIL API
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        try {
	    Message msg = mud.getFolder().getMessage(msgNum);

	    Multipart mp = (Multipart)msg.getContent();
	    part = mp.getBodyPart(partNum);
	    
	    String sct = part.getContentType();
	    if (sct == null) {
		out.println("invalid part");
		return;
	    }
	    ContentType ct = new ContentType(sct);

	    res.setContentType(ct.getBaseType());
	    InputStream is = part.getInputStream();
	    int i;
	    while ((i = is.read()) != -1)
		out.write(i);
	    out.flush();
	    out.close();
	} catch (MessagingException mex) {
	    out.println(mex.toString());
	}
    }

    /**
     * This is a utility message that pretty-prints the message 
     * headers for message that is being displayed.
     */
    private void displayMessageHeaders(MailUserData mud, Message msg, 
				       ServletOutputStream out) 
	throws IOException {

	try {
	    out.println("<b>Date:</b> " + msg.getSentDate() + "<br>");

            Address[] fr = msg.getFrom();
            if (fr != null) {
                boolean tf = true;
                out.print("<b>From:</b> ");
                for (int i = 0; i < fr.length; i++) {
                    out.print(((tf) ? " " : ", ") + getDisplayAddress(fr[i]));
                    tf = false;
                }
                out.println("<br>");
            }

            Address[] to = msg.getRecipients(Message.RecipientType.TO);
            if (to != null) {
                boolean tf = true;
                out.print("<b>To:</b> ");
                for (int i = 0; i < to.length; i++) {
                    out.print(((tf) ? " " : ", ") + getDisplayAddress(to[i]));
                    tf = false;
                }
                out.println("<br>");
            }

            Address[] cc = msg.getRecipients(Message.RecipientType.CC);
            if (cc != null) {
                boolean cf = true;
                out.print("<b>CC:</b> ");
                for (int i = 0; i < cc.length; i++) {
                    out.print(((cf) ? " " : ", ") + getDisplayAddress(cc[i]));
		    cf = false;
		}
                out.println("<br>");
            }
            
	    out.print("<b>Subject:</b> " + 
		      ((msg.getSubject() !=null) ? msg.getSubject() : "") + 
		      "<br>");

        } catch (MessagingException mex) {
	    out.println(msg.toString());
	}
    }

    /**
     * This method displays the URL's for the available commands and the
     * INBOX headerlist 
     */
    private void displayHeaders(MailUserData mud,
				HttpServletRequest req, 
                                ServletOutputStream out)
	throws IOException {

        SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy");

        out.println("<html>");
        out.println("<HEAD><TITLE>JavaMail Servlet</TITLE></HEAD>");
	out.println("<BODY bgcolor=\"#ccccff\"><hr>");
	out.print("<center><font face=\"Arial,Helvetica\" font size=\"+3\">");
	out.println("<b>Folder " + mud.getStore().getURLName() + 
		    "/INBOX</b></font></center><p>");

	// URL's for the commands that are available
	out.println("<font face=\"Arial,Helvetica\" font size=\"+3\"><b>");
        out.println("<a href=\"" +
		    HttpUtils.getRequestURL(req) +
		    "?logout=true\">Logout</a>");
        out.println("<a href=\"" +
		    HttpUtils.getRequestURL(req) +
		    "?compose=true\" target=\"compose\">Compose</a>");
	out.println("</b></font>");
	out.println("<hr>");

	// List headers in a table
        out.print("<table cellpadding=1 cellspacing=1 "); // table
	out.println("width=\"100%\" border=1>");          // settings

	// sender column header
	out.println("<tr><td width=\"25%\" bgcolor=\"ffffcc\">");
	out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
	out.println("<b>Sender</b></font></td>");
	// date column header
	out.println("<td width=\"15%\" bgcolor=\"ffffcc\">");
	out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
	out.println("<b>Date</b></font></td>");
	// subject column header
	out.println("<td bgcolor=\"ffffcc\">");
	out.println("<font face=\"Arial,Helvetica\" font size=\"+1\">");
	out.println("<b>Subject</b></font></td></tr>");

	try {
	    Folder f = mud.getFolder();
	    int msgCount = f.getMessageCount();
	    Message m = null;
	    // for each message, show its headers
	    for (int i = 1; i <= msgCount; i++) {
                m = f.getMessage(i);
		
		// if message has the DELETED flag set, don't display it
		if (m.isSet(Flags.Flag.DELETED))
		    continue;

		// from 
                out.println("<tr valigh=middle>");
                out.print("<td width=\"25%\" bgcolor=\"ffffff\">");
		out.println("<font face=\"Arial,Helvetica\">" + 
			    ((m.getFrom() != null) ? 
			               m.getFrom()[0].toString() : 
			               "" ) +
			    "</font></td>");

		// date
                out.print("<td nowrap width=\"15%\" bgcolor=\"ffffff\">");
		out.println("<font face=\"Arial,Helvetica\">" + 
                            df.format((m.getSentDate()!=null) ? 
				      m.getSentDate() : m.getReceivedDate()) +
			    "</font></td>");

		// subject & link
                out.print("<td bgcolor=\"ffffff\">");
		out.println("<font face=\"Arial,Helvetica\">" + 
		            "<a href=\"" +
			    HttpUtils.getRequestURL(req) + 
                            "?message=" +
                            i + "\">" +
                            ((m.getSubject() != null) ? 
			           m.getSubject() :
			           "<i>No Subject</i>") +
                            "</a>" +
                            "</font></td>");
                out.println("</tr>");
	    }
	} catch (MessagingException mex) {
	    out.println("<tr><td>" + mex.toString() + "</td></tr>");
	    mex.printStackTrace();
	}

	out.println("</table>");
	out.println("</BODY></html>");
	out.flush();
	out.close();
    }

    /** 
     * This method handles the request when the user hits the
     * <i>Compose</i> link. It send the compose form to the browser.
     */
    private void compose(MailUserData mud, HttpServletResponse res,
			 ServletOutputStream out) 
	throws IOException {
	
	res.setContentType("text/html");
	out.println(composeForm);
	out.close();
    }

    /**
     * This method processes the send request from the compose form
     */
    private void send(HttpServletRequest req, HttpServletResponse res,
		      ServletOutputStream out, HttpSession ssn)
	throws IOException {
	    
        String to = req.getParameter("to");
	String cc = req.getParameter("cc");
	String subj = req.getParameter("subject");
	String text = req.getParameter("text");

	try {
	    MailUserData mud = getMUD(ssn);
	    if (mud == null)
		throw new Exception("trying to send, but not logged in");

	    Message msg = new MimeMessage(mud.getSession());
	    InternetAddress[] toAddrs = null, ccAddrs = null;

	    if (to != null) {
		toAddrs = InternetAddress.parse(to, false);
		msg.setRecipients(Message.RecipientType.TO, toAddrs);
	    } else
		throw new MessagingException("No \"To\" address specified");

	    if (cc != null) {
		ccAddrs = InternetAddress.parse(cc, false);
		msg.setRecipients(Message.RecipientType.CC, ccAddrs);
	    }

	    if (subj != null)
		msg.setSubject(subj);

	    URLName u = mud.getURLName();
	    msg.setFrom(new InternetAddress(u.getUsername() + "@" +
					    u.getHost()));

	    if (text != null)
		msg.setText(text);

	    Transport.send(msg);
	    
	    out.println("<h1>Message sent successfully</h1></body></html>");
	    out.close();
	    
	} catch (Exception mex) {
	    out.println("<h1>Error sending message.</h1>");
	    out.println(mex.toString());
	    out.println("<br></body></html>");
	}
    }


    // utility method; returns a string suitable for msg header display
    private String getDisplayAddress(Address a) {
        String pers = null;
        String addr = null;
        if (a instanceof InternetAddress &&
            ((pers = ((InternetAddress)a).getPersonal()) != null)) {
	    
	    addr = pers + "  "+"&lt;"+((InternetAddress)a).getAddress()+"&gt;";
        } else 
            addr = a.toString();
        
        return addr;
    }

    // utility method; retrieve the MailUserData 
    // from the HttpSession and return it
    private MailUserData getMUD(HttpSession ses) throws IOException {
	MailUserData mud = null;

	if (ses == null) {
	    return null;
	} else {
	    if ((mud = (MailUserData)ses.getValue("javamailservlet")) == null){
		return null;
	    }
	}
	return mud;
    }


    public String getServletInfo() {
        return "A mail reader servlet";
    }

    /**
     * This is the HTML code for the compose form. Another option would
     * have been to use a separate html page.
     */
    private static String composeForm = "<HTML><HEAD><TITLE>JavaMail Compose</TITLE></HEAD><BODY BGCOLOR=\"#CCCCFF\"><FORM ACTION=\"/servlet/JavaMailServlet\" METHOD=\"POST\"><input type=\"hidden\" name=\"send\" value=\"send\"><P ALIGN=\"CENTER\"><B><FONT SIZE=\"4\" FACE=\"Verdana, Arial, Helvetica\">JavaMail Compose Message</FONT></B><P><TABLE BORDER=\"0\" WIDTH=\"100%\"><TR><TD WIDTH=\"16%\" HEIGHT=\"22\">	<P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">To:</FONT></B></TD><TD WIDTH=\"84%\" HEIGHT=\"22\"><INPUT TYPE=\"TEXT\" NAME=\"to\" SIZE=\"30\"> <FONT SIZE=\"1\" FACE=\"Verdana, Arial, Helvetica\"> (separate addresses with commas)</FONT></TD></TR><TR><TD WIDTH=\"16%\"><P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">CC:</FONT></B></TD><TD WIDTH=\"84%\"><INPUT TYPE=\"TEXT\" NAME=\"cc\" SIZE=\"30\"> <FONT SIZE=\"1\" FACE=\"Verdana, Arial, Helvetica\"> (separate addresses with commas)</FONT></TD></TR><TR><TD WIDTH=\"16%\"><P ALIGN=\"RIGHT\"><B><FONT FACE=\"Verdana, Arial, Helvetica\">Subject:</FONT></B></TD><TD WIDTH=\"84%\"><INPUT TYPE=\"TEXT\" NAME=\"subject\" SIZE=\"55\"></TD></TR><TR><TD WIDTH=\"16%\">&nbsp;</TD><TD WIDTH=\"84%\"><TEXTAREA NAME=\"text\" ROWS=\"15\" COLS=\"53\"></TEXTAREA></TD></TR><TR><TD WIDTH=\"16%\" HEIGHT=\"32\">&nbsp;</TD><TD WIDTH=\"84%\" HEIGHT=\"32\"><INPUT TYPE=\"SUBMIT\" NAME=\"Send\" VALUE=\"Send\"><INPUT TYPE=\"RESET\" NAME=\"Reset\" VALUE=\"Reset\"></TD></TR></TABLE></FORM></BODY></HTML>";

}


/**
 * This class is used to store session data for each user's session. It
 * is stored in the HttpSession.
 */
class MailUserData {
    URLName url;
    Session session;
    Store store;
    Folder folder;

    public MailUserData(URLName urlname) {
	url = urlname;
    }

    public URLName getURLName() {
	return url;
    }

    public Session getSession() {
	return session;
    }

    public void setSession(Session s) {
	session = s;
    }

    public Store getStore() {
	return store;
    }

    public void setStore(Store s) {
	store = s;
    }

    public Folder getFolder() {
	return folder;
    }

    public void setFolder(Folder f) {
	folder = f;
    }
}

⌨️ 快捷键说明

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