ssm实现qq邮箱发送验证码

ssm实现qq邮箱发送验证码

导入maven依赖

<!--邮箱验证码-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.2</version>
        </dependency>

新建 mail.properties 进行配置

#服务器主机名 smtp.xx.com
mail.smtp.host=smtp.qq.com
mail.smtp.username=qq号@qq.com
#客户端授权码
mail.smtp.password=授权码
#编码字符
mail.smtp.defaultEncoding=utf-8
#是否进行用户名密码校验
mail.smtp.auth=true
#设置超时时间
mail.smtp.timeout=20000

在springMVC配置文件配置

 <!--QQ发送邮箱验证码-->
    <!--读取属性文件-->
    <context:property-placeholder location="classpath:mail.properties" ignore-unresolvable="true"/>

    <!--配置邮件接口-->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.smtp.host}"/>
        <property name="username" value="${mail.smtp.username}"/>
        <property name="password" value="${mail.smtp.password}"/>
        <property name="defaultEncoding" value="${mail.smtp.defaultEncoding}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
            </props>
        </property>
    </bean>

controller 进行配置

    @Autowired
    private JavaMailSender javaMailSender;//import org.springframework.mail.javamail.JavaMailSender;

    @Value("${mail.smtp.username}")
    private String emailFrom;

    /*验证码发送*/
    @PostMapping("/send")
    public Result senMsg(HttpSession httpSession, @RequestParam("userEmail") String userEmail) {
        //生成六位数验证码
        String Captcha = String.valueOf(new Random().nextInt(899999) + 100000);
        httpSession.setAttribute("Captcha", Captcha);//存储验证码
        SimpleMailMessage message = new SimpleMailMessage();
        //发件人的邮箱地址
        message.setFrom(emailFrom);
        //收件人的邮箱地址
        message.setTo(userEmail);
        //邮件主题
        message.setSubject("验证码");
        //邮件内容
        message.setText("验证码:" + Captcha);
        //发送邮件
        javaMailSender.send(message);
        return Result.success(200, "发送成功", null);
    }

推荐博客:https://blog.csdn.net/weixin_42356887/article/details/105638417

posted @ 2021-10-10 18:39  有何和不可  阅读(508)  评论(1)    收藏  举报