java邮件开发--心得6-web email的编写
1. 前面讲了好多客户端的电子邮件,实际情况下实际应用价值比较小的,实际生活中用的最多的是网页上的发送email功能,这里比如一个web应用中带有邮件发送功能。
2.下面介绍一个web email使用comcast自带的JNDI的案例及其分析:
package com.web.servlet; import java.io.IOException; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** *用一个content.xml配置文件来编写一个web email * */ public class SendMailServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Context context = (Context)new InitialContext().lookup("java:comp/env"); Session session = (Session)context.lookup("mail/context"); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("itcast_test@sina.com")); InternetAddress[] to = {new InternetAddress("itcast_test@sina.com")}; msg.setRecipients(Message.RecipientType.TO,to); msg.setSubject("web email"); msg.setText("这是一封 java web写的email"); Transport transport = session.getTransport(); transport.connect("itcast_test","123456"); transport.sendMessage(msg,to); transport.close(); response.getWriter().println("send ok!"); } catch (Exception e) { e.printStackTrace(response.getWriter()); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } The resources defined in these elements may be referenced by the following elements in the web application deployment descriptor (/WEB-INF/web.xml) of your web application;重要的配置文件context.xml,该文件放在WEB-INF下的META-INF下,里面的具体如下: <Context> <Resource name="mail/context" auth="Container" type="javax.mail.Session" mail.smtp.host="smtp.sina.com" mail.smtp.auth="true" mail.transport.protocol="smtp" /> </Context>