SSM实现邮箱验证功能

编程入门 行业动态 更新时间:2024-10-23 21:27:16

(一)项目目录

(二)添加依赖pom.xml

(三)生成唯一激活码

public class CodeUtil {
    //生成唯一的激活码
    public String generateUniqueCode(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

(四)邮箱和授权吗

(五)发送邮件工具类

import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件工具类
 * @Author:
 * @Date:
 */
//@Component 将工具类注入spring容器中
@Component
public class SendEmailUtil {

     /*
      *发送邮件
      * @param toEmail 目的地
      * @param code 唯一激活码
      * @return
      */
    public int send_email(String toEmail,String code) throws IOException, AddressException, MessagingException{

        String to = toEmail;
        String subject = "邮箱验证";
        String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/RegisterDemo/ActiveServlet?code="
                + code + "'>http://localhost:8080/RegisterDemo/ActiveServlet?code=" + code
                + "</href></h3></body></html>";

        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.qq");
        properties.put("mail.smtp.port", "25");
        properties.put("mail.smtp.auth", "true");

        //发送者的邮箱和授权码
        Authenticator authenticator = new Email_Authenticator("****@qq", "pchfwcnialuudjab");
        Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);
        MimeMessage mailMessage = new MimeMessage(sendMailSession);
        //邮箱的发送者
        try {
            mailMessage.setFrom(new InternetAddress("2464171268@qq"));
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        //邮箱接收
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        //发送邮件的标题
        mailMessage.setSubject(subject, "UTF-8");
        //发送邮件的日期
        mailMessage.setSentDate(new Date());

        //MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();

        //创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        //设置邮件的内容的格式和字节码
        html.setContent(content.trim(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return 1;
    }
}

控制逻辑部分代码:UserService.java

实现类UserServiceImpl.java:

单元测试代码:

收件箱:

更多推荐

SSM实现邮箱验证功能

本文发布于:2023-06-14 08:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:邮箱   功能   SSM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!