Springboot整合mail实现邮箱注册验证

发布于 2021-06-20  144 次阅读


1.邮件发送流程:

image-20210201221451321

发件方:a@qq.com(简写,为了马赛克)

收件方:b@163.com(简写,为了马赛克)

2.配置pom.xml

    <!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.4.0</version>
        </dependency>

3.登录QQ邮箱,开启pop3和smtp服务

发送短信后,点击【我已发送】会生成一串密码,将此密码填入application.yml中的

spring:
  mail:
    password: wlcfnoewxzuebabc
image-20210620214123996
image-20210201221357635

4.配置application.yml

 #配置邮箱验证
spring:
  mail:
    default-encoding: UTF-8
    host: smtp.qq.com
    username: a@qq.com
    password: wlcfnoewxzuebabc
#指定端口,QQ邮箱默认
    port: 465

5.编写测试方法

package com.shiyun.common;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * Classname:MailTest
 * @description:测试右键的发送
 * @author: 陌意随影
 * @Date: 2021-02-01 22:20
 * @Version: 1.0
 **/
@SpringBootTest
public class MailTest {
        //在使用的时候JavaMailSenderImpl需要用springboot的ioc容器注入。
        @Autowired
        JavaMailSenderImpl mailSender;

        @Test
        public void contextLoads() {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("今晚开会");
            message.setText("大家,好!\n今晚7:30在教学楼201开班委会,请各位班委准时参加! \n谢谢!");
            message.setTo("b@163.com");
            message.setFrom("a@qq.com");
            mailSender.send(message);
        }

        @Test
        public void test2() throws Exception{
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject("今晚开会");
            helper.setText("大家,好!<br> &nbsp;&nbsp;<b style='color:red'>今晚7:30在教学楼201开班委会,请各位班委准时参加!</b> <br>谢谢!",true);
            helper.setTo("b@163.com");
            helper.setFrom("a@qq.com");

            //添加附件
            helper.addAttachment("会议说明.txt",new File("C:\\Users\\Dylan\\Pictures\\会议说明.txt"));
            helper.addAttachment("会议图片.jpg",new File("C:\\Users\\Dylan\\Pictures\\会议图片.jpg"));

            mailSender.send(mimeMessage);
        }

}

6.运行测试方法

image-20210620214425137

可见邮件能够正常发送。


繁华落尽,雪花漫天飞舞。