javaweb收发邮件 servler+jsp实现(一)

(一)邮箱登录校验

javaweb收发邮件 servler+jsp实现(一)_第1张图片

 准备:

        申请smtp授权码(自行百度、google)

        

        activation.jar、javax.mail-1.6.0.jar

项目结构 

javaweb收发邮件 servler+jsp实现(一)_第2张图片

welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


  
    My JSP 'welcome.jsp' starting page
  
  
  

邮箱登录

用户名:
授权码:

Login.class (servlet)

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

		response.setContentType("text/html");
		String user = request.getParameter("user");
		String pswd = request.getParameter("pswd");
		String host = "pop3.163.com";
		//登录验证
		if(EmailUtils.getFolder(host, user, pswd)!=null){
			request.getSession().setAttribute("user", user);
			request.getSession().setAttribute("pswd", pswd);
			response.sendRedirect("main.jsp");
		}else{
			response.sendRedirect("error.jsp");	
		}
		
	}

EmailUtils.class

/**
	 * 登录校验、收取邮件获取folder
	 * 
	 * @param host
	 * @param username
	 * @param password
	 * @return
	 */
	public static Folder getFolder(String host, String user, String pswd) {
		Properties prop = new Properties();
		prop.setProperty("mail.store.protocol", "pop3");
		prop.setProperty("mail.pop3.host", host);

		// javax.mail.Session mailSession = Session.getDefaultInstance(prop,
		// null);
		Session mailSession = Session.getInstance(prop, null);
		mailSession.setDebug(false);
		try {
			Store store = mailSession.getStore("pop3");
			store.connect(host, user, pswd);

			Folder folder = store.getFolder("inbox");
			folder.open(Folder.READ_WRITE);
			return folder;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

登录校验之后

main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


     
    My JSP 'main.jsp' starting page
  
  
  	

欢迎${sessionScope.user}


发邮件
收邮件

error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>


      
    My JSP 'error.jsp' starting page   
   
  
    

Error!

javaweb收发邮件 servler+jsp实现(一)_第3张图片

因为某tx邮箱太难伺候,干脆改成163邮箱了,想登录其他邮箱自己改地址

 

你可能感兴趣的:(java)