天天看點

javax.mail開發注冊郵箱驗證

一、導入maven依賴

<dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>
           

二、建立郵件工具類

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class EmailUtils {

    private static String host = "smtp.163.com";
    private static String username = "*****@163.com";
    private static String password = "*****";
    private static String protocol = "smtp";
    private static boolean debug = true;

    private EmailUtils(){}

    public static void sendEmail(String to, String code) throws MessagingException, UnsupportedEncodingException {
        //連接配接郵件伺服器的參數設定
        Properties properties = new Properties();
        //設定伺服器位址
        properties.setProperty("mail.smtp.host",host);
        //設定使用者認證方式
        properties.setProperty("mail.smtp.auth","true");
        //設定傳輸協定
        properties.setProperty("mail.transport.protocol", protocol);
        //建立連接配接對象,連接配接到郵箱伺服器
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        session.setDebug(debug);
        //建立郵件對象
        Message message = new MimeMessage(session);
        //設定發件人
        message.setFrom(new InternetAddress(username));
        //設定收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        message.setRecipient(Message.RecipientType.CC, new InternetAddress(username));
        //設定郵件主題
        message.setSubject("來自稀有無緣的激活郵件");
        //設定圖檔節點
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent("請注意您的資訊","text/html;charset=UTF-8");
        DataHandler dataHandler = new DataHandler(new FileDataSource("G:\\360downloads\\310684.jpg"));
        mimeBodyPart.setDataHandler(dataHandler);
        //設定圖檔id以便在html中調用
        mimeBodyPart.setContentID("imgt");
        //設定文位元組點
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<a href='http://webjob.free.ngrok.cc/user/jihuo?code=" + code + "'>點選此連結激活您的賬号</a><img src='cid:imgt'>","text/html;charset=UTF-8");
        //設定附件
        MimeBodyPart fujian = new MimeBodyPart();
        DataHandler f = new DataHandler(new FileDataSource("G:\\360downloads\\303167.jpg"));
        fujian.setDataHandler(f);
        fujian.setFileName(MimeUtility.encodeText(f.getName()));
        MimeMultipart mimeMultipart = new MimeMultipart();
        //加入所有節點
        mimeMultipart.addBodyPart(mimeBodyPart);
        mimeMultipart.addBodyPart(text);
        mimeMultipart.addBodyPart(fujian);
        mimeMultipart.setSubType("mixed");
        message.setContent(mimeMultipart);
        //設定郵件正文
        //message.setContent("<p style='font-size: 34px'>請查收您的激活碼資訊</p>","text/html;charset=UTF-8");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        //發送郵件
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
    }
           

三、建立使用者表

CREATE TABLE `user`(
	`id` INT(12) PRIMARY KEY,
	`username` VARCHAR(12),
	`password` VARCHAR(32),
	`email` VARCHAR(32),
	`code` VARCHAR(64)
);
           

四、建立使用者類

import java.io.Serializable;

public class User implements Serializable {

    public static final long serialVersionUID = 1L;

    private Integer id;
    private String username;
    private String password;
    private String email;
    private String code;

    public User(){}

    public User(String username, String password, String email) {
        this.username = username;
        this.password = password;
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
           

四、建立userDao

public interface UserDao {

    void insert(User user);

    User queryByCode(String code);

    void update(User user);

}
           

五、建立mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.liuxing.dao.UserDao">
    <select id="queryByCode" resultType="com.liuxing.entity.User">
        select id, username,
        password, email, code
        from user
        where code = #{code}
    </select>

    <insert id="insert" useGeneratedKeys="true"
            keyColumn="id"  parameterType="com.liuxing.entity.User">
        insert into
        user(id,username,password,email,code)
        values
        (#{id},#{username},#{password},#{email},#{code})
    </insert>
    <update id="update" parameterType="com.liuxing.entity.User">
        update user
        <set>
            <if test="code!=null"> code=null</if>
        </set>
        where code=#{code}
    </update>

</mapper>
           

六、controller

@PostMapping(value = "/register")
    public @ResponseBody
    String register(User user) throws UnsupportedEncodingException, MessagingException {
        user.setId((int)System.currentTimeMillis());
        String code = UUID.randomUUID().toString().replace("-","");
        user.setCode(code);
        userDao.insert(user);
        EmailUtils.sendEmail(user.getEmail(), code);
        return "郵件發送成功";
    }
    @GetMapping(value = "/jihuo")
    public String jihuo(String code){
        User user = userDao.queryByCode(code);
        if (user != null){
            userDao.update(user);
        }
        return "redirect:../th/index";
    }
           

七、前台頁面

<form action="/user/register" method="post">
    <input type="text" name="username"/>
    <input type="password" name="password"/>
    <input type="email" name="email"/>
    <input type="submit" value="注冊"/>
</form>
           

使用者點選注冊進入到register方法中,生成随機code,向資料庫庫添加使用者資訊。

使用者收到郵件後點選郵件中的連結進入到jihuo方法中,根據傳過來的code的值在資料庫中查詢使用者資訊,如果查詢到則将資料庫中該使用者的code設定為null,即代表該使用者已經通過郵箱驗證。如果使用者在點選過程中code被篡改則認證失敗,上述例子隻是簡單實作,實際開發中需要完善。

繼續閱讀