java mail

JavaMail下载与安装
http://java.sun.com/products/javamail/index.html
核心类与接口
javax.mail.Session
javax.mail.Message
javax.mail.Address
javax.mail.Authenticator
javax.mail.Transport
javax.mail.Store
javax.mail.Folder
-----------------------------------------------------
1 加载javamail的jar包
2 编写处理类
public class SendMail {
 public static void mian(String[] args){
  Properties props=new Properties();
  Session session=Session.getInstance(props,null);
  props.put("mail.host", "127.0.0.1");//接收邮件的地址
  props.put("mail.transport.protocol", "smtp");//传输邮件的协议
  
  Message message=new MimeMessage(session);
  try {
   message.setFrom(new InternetAddress("[email protected]"));//设定发件人
   message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));//设定收件人
   message.setSubject("你好吗?");//设标题
   message.setText("javamail发送邮件测试");//设内容
   Transport.send(message);//发送信息
  } catch (AddressException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (MessagingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}
---------------------------------------------------
Apache Commons Email组件
1 加载javamail的jar包和Apache Commons Email的jar包
2 编写servlet的处理类
public class SendCommMail extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request,response);
 }
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  SimpleEmail email=new SimpleEmail();//生成SimpleEmail对象
  email.setHostName("smtp.sina.com");//生成邮件
  email.setAuthentication("web08", "web2008");//建立用户
  email.setCharset("UTF-8");//邮件内容编码
  try {
   email.setFrom(request.getParameter("from"));//发件人
   email.addTo(request.getParameter("to"));//收件人
   email.setMsg(request.getParameter("context"));//内容
   email.send();//发送邮件
   request.setAttribute("sendmail.message", "邮件发送成功!");
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("sendmail.message", "邮件发送不成功!");
  }
  request.getRequestDispatcher("/sendResult.jsp").forward(request, response);
 }
}
3 配置web.xml文件
4 页面
----------------------------------------------------------------------
带附件的邮件
1 1 加载javamail的jar包,Apache Commons Email的jar包和fileUpLoad
2 2 编写servlet的处理类
public class SendCommMail extends HttpServlet {
 private ServletContext sc;//ServletContext定义了一系列方法用于与相应的servlet容器通信
 private String savePath;
 File file;
 private Map<String,String> parameters=new HashMap<String,String>();//存页面信息

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request,response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("UTF-8");
  file=this.doAtta(request);
  MultiPartEmail email=new MultiPartEmail();//生成SimpleEmail对象
  email.setHostName("smtp.163.com");//生成邮件
  email.setAuthentication("ywj_316", "1234567890");//建立用户
  email.setCharset("UTF-8");//邮件内容编码
  try {
   email.setFrom(parameters.get("from"));//发件人
   email.addTo(parameters.get("to"));//收件人
   email.setMsg(parameters.get("context"));//内容 
   email.setSubject(parameters.get("title"));//主题
   if(file!=null){
    EmailAttachment attachment=new EmailAttachment();//附什对象
    attachment.setPath(file.getParent());//附件路径
    attachment.setDescription(EmailAttachment.ATTACHMENT);//附件类型
    attachment.setName(file.getName());//附件名称
    email.attach(attachment);
   }
   System.out.println("ssssssssssssssssssssssssssssssssssss");
   email.send();//发送邮件
   request.setAttribute("sendmail.message", "邮件发送成功!");
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("sendmail.message", "邮件发送不成功!");
  }
  request.getRequestDispatcher("/sendResult.jsp").forward(request, response);
 }
 
 public File doAtta(HttpServletRequest request)throws ServletException,IOException{
  DiskFileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  try {
   List items = upload.parseRequest(request);
   for (int i = 0; i < items.size(); i++) {
    FileItem item = (FileItem) items.get(i);
    if (item.isFormField()) {
     parameters.put(item.getFieldName(), item.getString("UTF-8"));
     System.out.println(item.getFieldName());
     System.out.println(item.getString("UTF-8"));
    } else {
     if (item.getName() != null && !item.getName().equals("")) {
      File temFile = new File(item.getName());
      file = new File(sc.getRealPath("/") + savePath,
        temFile.getName());
      item.write(file);

      request.setAttribute("upload.message", "上传文件成功!");
     } else {
      request.setAttribute("upload.message", "没有上传文件成功!");
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("upload.message", "没有上传文件成功!");
  }
  return file;
 }
 
 public void init(ServletConfig config) throws ServletException {
  savePath = config.getInitParameter("savePath");//得到初始化信息
  sc = config.getServletContext();//得到ServletContext接口的实例
 }
}
3 配置web.xml文件
 <servlet>
    <servlet-name>SendCommMail</servlet-name>
    <servlet-class>com.webs.SendCommMail</servlet-class>
      <init-param>
    <param-name>savePath</param-name>
    <param-value>uploads</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>SendCommMail</servlet-name>
    <url-pattern>/servlet/sendMail</url-pattern>
  </servlet-mapping>
4 页面
 <body>
    发送邮件的程序<br>
    <form action="servlet/sendMail" name="form1"  enctype="multipart/form-data" method="post">
     收件人:<input type="text" name="to"/><br>
    发件人:<input type="text" name="from"/><br>
    主题:<input type="text" name="title"/><br>
    附件:<input type="file" name="file"/><br>
    内容:<input type="text" name="context"/><br>
    <input type="submit"/>
    </form>
  </body>

你可能感兴趣的:(java,apache,jsp,Web,servlet)