J2EE实现发送邮件功能

   以前做过一个项目,需要有这样的功能,即用户申请帐号后,需要得到系统管理员的批准,管理在批准以后会自动加载邮件内容并自动发送邮件给用户注册邮箱。现在很多的网站或系统都有这样的内容,比如注册淘宝,facebook,校内,csdn,注册成功后都会有一封邮件发送给用户,我做的这个很简单,没有确认链接什么的,只是将一个自动加载的内容发送至用户邮箱。

    在使用该程序时,可以将发送邮箱服务器,用户名,密码等放到constant或国际化文件等(便于以后维护)文件中。

    在使用该程序时,可以将发送邮箱服务器,用户名,密码等放到constant或国际化文件等(便于以后维护)文件中。
 
 /**
     * 管理员 实现邮件发送功能 * 若成功,进入了发送邮件成功页面 如果有错误,跳转到错误提醒界面
     */
 
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        MessageResources messages = getResources(request);
        HttpSession httpSession = request.getSession();
        EmailForm emailForm = (EmailForm) actionForm;
        if (httpSession == null) {
            logger.warn(StringUtil.getLogString("管理员""超时,需要重新登录。"));
            return mapping.findForward("timeout");
        }
 
        // 必须是管理员才允许操作,否则说明是非法登录
        
 
        // 发送方信息
        final String fromEmail = messages.getMessage("FromEmail");
        final String fromEmailName =  messages.getMessage("FromEmailName");
        final String fromEmailPwd =  messages.getMessage("FromEmailPwd");
        final String smtpHost =  messages.getMessage("SmtpHost");
 
        // 接收方信息
        String subjects = emailForm.getSubject().trim();
        String texts = emailForm.getText().trim();
        String email_to =emailForm.getEmail().trim();
 
        try {
 
            Properties props = new Properties();
 
            Transport transport;
            // 设置SMTP服务器
            props.put("mail.smtp.host", smtpHost);
            // 指定是否需要SMTP验证
            props.put("mail.smtp.auth""true");
            props.put("mail.smtp.starttls.enable""true");
            /* 获取邮件会话对象 */
 
            // 将邮件的props属性和Authenticator属性(密码验证)放在session中。
            Session session = Session.getInstance(props, new Authenticator() {
 
               public PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(fromEmailName,
                          fromEmailPwd);
               }
            });
            Message newMessage = null;
            try {// 创建mime邮件对象
               newMessage = new MimeMessage(session);
            catch (RuntimeException e) {
 
               e.printStackTrace();
               response.setContentType("text/html;charset=GBK");//设置发送到客户端的响应的内容类型
               PrintWriter out = response.getWriter();
               String alertmsg = messages
                      .getMessage("发送失败");//发送失败
               out.println("<script>alert('" + alertmsg + "')</script>");
               out.println(("<script> window.close();</script>"));//关闭窗口
               out.println("<script>window.location='teamAdmin.do'</script>");//重新回到某页面
               out.println("<script>location.reload()</script>");//强迫浏览器刷新当前页面
               out.flush();
               return null;
 
            }
 
            newMessage.setFrom(new InternetAddress(fromEmail));
 
            String[] email_team = null;
            email_team = email_to.split(";");
            /* 如果接收邮箱是多个,那么就循环发送 */
            for (int i = 0; i < email_team.length; i++) {
               String email = null;
               email = email_team[i];
               // 设置邮件收件人,主题,内容,正文
               newMessage.setRecipient(Message.RecipientType.TO,
                      new InternetAddress(email));
               newMessage.setSubject(subjects);//文件标题
 
               newMessage.setSentDate(new Date());//发送时间
 
               newMessage.setText(texts);
               // 创建smtp邮件协议发送对象
               transport = session.getTransport("smtp");
               // transport.send()方法中实现取得与邮件服务器的连接,和通过邮件服务器发送邮件。
 
              
               transport.send(newMessage);
            }
 
        }
        catch (AuthenticationFailedException e)
        {
            response.setContentType("text/html;charset=GBK");
            PrintWriter out = response.getWriter();
            String alertmsg = messages.getMessage("密码有误,发送失败");
            out.println("<script>alert('" + alertmsg + "')</script>");
            out.println("<script>window.location='teamAdmin.do'</script>");
            out.flush();
            return null;
        }
        catch (MessagingException e)
        {
            response.setContentType("text/html;charset=GBK");
            PrintWriter out = response.getWriter();
            String alertmsg = messages.getMessage("网络链接有误,发送失败");
            out.println("<script>alert('" + alertmsg + "')</script>");
            out.println("<script>window.location='teamAdmin.do'</script>");
            out.flush();
            return null;
        }
        catch (Exception e)
        {
            response.setContentType("text/html;charset=GBK");
            PrintWriter out = response.getWriter();
            String alertmsg = messages.getMessage("发送失败");
            out.println("<script>alert('" + alertmsg + "')</script>");
            out.println("<script>window.location='teamAdmin.do'</script>");
            out.flush();
            return null;
        }
        response.setContentType("text/html;charset=GBK");
        PrintWriter out = response.getWriter();
        String alertmsg = "发送邮件成功!";
        out.println("<script>alert('" + alertmsg + "')</script>");
        out.println("<script>window.location='teamAdmin.do'</script>");
        out.flush();
 
        return null;
 
    }
 
    }



     本文转自 gaochaojs 51CTO博客,原文链接:http://blog.51cto.com/jncumter/179158,如需转载请自行联系原作者

上一篇:android 5.0新特性学习--RecyclerView


下一篇:大数据行业2016的变与不变