首先我先去qq邮箱或者网易邮箱开通POP3/IMAP/SMTP/Exchange/CardDAV 服务
它在左上角的设置——账户——往下滑就可以找到——然后点击开通
开通后就会得到一串授权码。如下图
接下来直接编写代码
首先我没导入依赖
<!-- 这个是邮箱验证-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>3.1.0</version>
</dependency>
整体项目结构如下
controller层
@Component
public class EmailController {@Autowiredprivate JavaMailSenderImpl mailSender;public void send(EmailInfo emailInfo) {try {SimpleMailMessage mailMessage = new SimpleMailMessage();//主题mailMessage.setSubject("邮件主题");//生成随机数String code = randomCode();//内容mailMessage.setText("邮件内容" );System.out.println("您收到的验证码是:" + code);//发给谁mailMessage.setTo(emailInfo.getToEmail());//你自己的邮箱(可以去配置文件中获取) 也可以直接写上去mailMessage.setFrom("发邮件的人");//发送mailSender.send(mailMessage);} catch (Exception e) {e.printStackTrace();}}/*** 随机生成6位数的虚拟银行卡* @return String code*/public String randomCode(){StringBuilder str = new StringBuilder();Random random = new Random();for (int i = 0; i < 6; i++) {str.append(random.nextInt(10));}return str.toString();}}
pojo层(就是一个实体类)
package com.chd.pojo;/*** @Author 陈厚德* @Version 2.2*/
public class EmailInfo {private String id;/*** 内容*/private String title;/*** 邮箱收件地址*/private String toEmail;public EmailInfo() {}public EmailInfo(String id, String title, String toEmail) {this.id = id;this.title = title;this.toEmail = toEmail;}/*** 获取* @return id*/public String getId() {return id;}/*** 设置* @param id*/public void setId(String id) {this.id = id;}/*** 获取* @return title*/public String getTitle() {return title;}/*** 设置* @param title*/public void setTitle(String title) {this.title = title;}/*** 获取* @return toEmail*/public String getToEmail() {return toEmail;}/*** 设置* @param toEmail*/public void setToEmail(String toEmail) {this.toEmail = toEmail;}public String toString() {return "EmailInfo{id = " + id + ", title = " + title + ", toEmail = " + toEmail + "}";}
}
propertie配置类
server.port=8725
spring.mail.host = smtp.qq.com
spring.mail.username = 发送者
spring.mail.password = 你的密码
spring.mail.properties.mail.smtp.ssl.enable=ture
spring.mail.default-encoding=UTF-8
最后是测试类
package com.chd;import com.chd.controller.EmailController;
import com.chd.pojo.EmailInfo;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;@SpringBootTest
class EmailChdApplicationTests {@AutowiredEmailController controller;// 测试邮箱验证@Testvoid contextLoads() {System.out.println("测试邮箱验证");EmailInfo emailInfo=new EmailInfo("25","邮箱测试","被测试的邮箱号");System.out.println("测试者是"+emailInfo.getToEmail());controller.send(emailInfo);}}
到这里,测试不报错就成功了,希望嫩帮助到各位小伙伴