JavaWeb--发送邮件实现注册

发送邮件

加载包
pom.xml

   <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.7</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1.1</version>
    </dependency>

注册页面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/RegisterServlet.do" method="post">
        <div class="txt txt0">
            <span style="letter-spacing:8px;">用户名:</span>
            <input name="username" type="text" class="txtphone" placeholder="请输入用户名"/>
        </div>
        <div class="txt txt0">
            <span style="letter-spacing:4px;">登录密码:</span>
            <input name="password" type="text" class="txtphone" placeholder="请输入密码"/>
        </div>
        <div class="txt txt0">
            <span style="letter-spacing:4px;">邮箱:</span>
            <input name="email" type="text" class="txtphone" placeholder="请输入邮箱"/>
        </div>
        <div class="txt txt0">
            <input type="submit" value="注册"/>
        </div>
    </form>
</body>
</html>

注册成功跳转页面:info.jsp

<%--
  Created by IntelliJ IDEA.
  User: ASUS
  Date: 2020/8/29
  Time: 22:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${message}
</body>
</html>

用户实体类User.java

package edu.cqupt.pojo;

import java.io.Serializable;
public class User implements Serializable {

    private String username;
    private String password;
    private String email;

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

RegisterServlet.java

package edu.cqupt.servlet;

import edu.cqupt.pojo.User;
import edu.cqupt.utils.SendEmail;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        System.out.println(username);
        System.out.println(password);
        System.out.println(email);
        User user = new User(username, password, email);
        SendEmail send = new SendEmail(user);
        send.start();		// 使用线程,加快邮件发送
        req.setAttribute("message","注册成功,请查收邮件");
        req.getRequestDispatcher("info.jsp").forward(req,resp);

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

SendEmail.java

package edu.cqupt.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import edu.cqupt.pojo.User;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail extends Thread{
    private String from = "发送方@qq.com";
    private String username = "发送方@qq.com";
    private String password = "邮箱授权码";
    private String host = "smtp.qq.com";
    private  User user;

    public SendEmail(User user) {
        this.user = user;
    }

    @Override
    public void run() {
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host", "smtp.qq.com");
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.auth", "true");

            //QQ邮箱,设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.socketFactory", sf);

            // 使用JavaMail发送邮件的5个步骤
            // 1、创建session
            Session session = Session.getInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            // 2. 开启Session的debug模式:true
            session.setDebug(false);
            // 3.通过session得到transport对象
            Transport ts = session.getTransport();
            ts.connect(host, username, password);
            // 4. 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
            message.setSubject("注册邮件");
            String info = "Yours username:" + user.getUsername() + "password:" + user.getPassword();
            message.setContent(info, "text/html;chartset=UTF-8");
            // 5.发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            // 6.关闭连接
            ts.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

注册效果
 
 image.png
    
image.png

posted @ 2020-08-31 08:53  sinlearn  阅读(306)  评论(0编辑  收藏  举报