1. 程式人生 > >javaweb郵箱註冊賬號和啟用

javaweb郵箱註冊賬號和啟用

先設計資料庫表

active代表是否啟用,如果沒有去郵箱點選連結,active為0,點了就更新active欄位為1

需要的jar包依賴

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5<ersion> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4<ersion> </dependency>

前臺程式碼

oup.onclick=function(){
   var username=document.getElementById('username').value;
   var password=document.getElementById('password').value;
   var password1=document.getElementById('password1').value;
    var email=document.getElementById('email').value;
//先對輸入的郵箱格式進行判斷
          if(email == ''){
              alert("請輸入您的郵箱");
              return;
          }else if(email != "") {
              var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
              isok= reg.test(email );
              if (!isok) {
                  alert("郵箱格式不正確,請重新輸入!");
                  return false;
              }
          };
   $.ajax({
      url : "User/user.do",
      type : "post",
      data : {
         "username":username,
         "password":password,
         "password1":password1,
         "email":email
      },
      async : false,
      success : function(data) {
         if(data=='No'){
            alert("註冊失敗");
         }
         else {
            alert("註冊成功");
            window.location.href="login(1).html";
         }
      }
   });

};

後臺程式碼Usercontroller

@RequestMapping(value = "/user.do")  /
@ResponseBody
public String regist(HttpServletRequest request, User user, Model model, ModelAndView modelandview) {

    String password = request.getParameter("password");
    String password1 = request.getParameter("password1");
    String username = request.getParameter("username");
    String email = request.getParameter("email");
    String active = "0";

     User  user1 = userService.login(username, password);


        if (user1 != null || !password.equals(password1)) {//我寫的賬戶是否存在的判斷。 可以自行刪除
            System.out.println("No");
            return "No";
        } else {
            try{
               

                sendEmail a=new sendEmail();
                a.sendHtmlEmail(email);
                userService.regist(username, password, email, active);//賬號存入資料庫,但是active欄位 為0
            }catch (Exception e){

                System.out.println("使用者註冊:" + user.getUsername() + user.getPassword());

                return "Yes";
            }
        }

        //註冊成功後跳轉success.jsp頁面
         return "";

}

sendEmail類(三種郵箱型別),我用的是qq郵箱來啟用,也可以用163等郵箱,道理差不多

package controller;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

import java.io.File;
import java.net.URL;

public class sendEmail {
    /*我們使用普通郵件來測試

    public static void main(String[] args) {
        sendHtmlEmail();//傳送普通郵件
      //  sendHtmlEmail();//傳送html5郵件
      //   sendAttachmentsEmail();//傳送帶附件郵件
    }
  */
    private static void sendSimpleEmail() {
        Email email=new SimpleEmail();
        email.setHostName("smtp.qq.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("XXXXX","XXXXX"));//傳送人的郵箱和授權碼
        email.setSSLOnConnect(true);

        try {
            email.setFrom("XXXXX");//傳送人的郵箱
            email.setSubject("測試主題");//傳送的主題
            email.setMsg("測試內容");//傳送的內容
            email.addTo("XXXXXX");//接受人的郵箱
            email.send();
            System.out.println("傳送simple郵件成功!!!");
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    public static void sendHtmlEmail(String mail)  {
        HtmlEmail email = new HtmlEmail();
        email.setHostName("smtp.qq.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("[email protected]","xxxxxx"));//傳送人的郵箱和授權碼,
        email.setSSLOnConnect(true);
        try {
            email.setFrom("xxxxxx","hwj");
            email.setSubject("HTML5格式郵箱");
            String activeUrl="http://localhost:8080/xuenian/User/activemail.do?mail="+mail;
//傳送一個啟用連結來實現對資料庫的active欄位更新為1,mail就是你前臺註冊的mail。
            email.setHtmlMsg("點選連結啟用賬戶"+activeUrl);
            email.setTextMsg("測試內容");
            email.addTo(mail, "hzk");
            email.send();
            System.out.println("傳送HTML郵件成功!!");
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    private static void sendAttachmentsEmail() {
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName("smtp.qq.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("xxxx","xxxxx"));//傳送人的郵箱和授權碼
        email.setSSLOnConnect(true);
        try {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setURL(new URL("https://www.xys1118.com/images/topbg.jpg"));
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("xys.jpg");
            attachment.setName("xys.jpg");

            email.attach(attachment);
            email.attach(new File("C:/Users/admin/Desktop/測試/1/1.txt"));
            email.setFrom("[email protected]","hqs");
            email.setSubject("HTML5帶有附件郵箱");
            email.setMsg("測試附件郵件內容");
            email.addTo("[email protected]", "hzk");
            email.send();
            System.out.println("傳送HTML郵件成功!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

郵箱授權碼獲取(qq郵箱為例子)

在你的qq郵箱的設定的賬戶裡。

開啟前兩個,會有一個授權碼給你,就是你的授權碼。通過你的郵箱來發出啟用郵件給別人的郵箱。

activemail.do(啟用連結的處理後臺程式碼) 

//驗證郵箱
@RequestMapping(value = "/activemail.do")
public ModelAndView activemail(User user,HttpServletRequest request, Model model) {

    String email = request.getParameter("mail");
    System.out.println(email);
    String active = "1";
    //1.根據啟用碼從資料庫查出使用者資訊
    ModelAndView mv = new ModelAndView("redirect:/success.html");//自己寫一個success頁面代表啟用成功
    ModelAndView mv1 = new ModelAndView("redirect:/fail.html");//自己寫一個success頁面代表啟用失敗

    user = userService.findemail(email);
    //2.如果能查出來那麼我們就將這個使用者的啟用碼狀態變為啟用(active為1)
    if (user != null) {
        userService.updataemail(active, email);
        return mv;

    } else {
        System.out.println("啟用失敗!");
        return mv1;
    }
}

程式碼正確的話會有郵件 ,點選即可啟用