简要说明
已封装成工具类,使用时只需要修改发送邮箱和接收邮箱,并进行邮箱相应的配置,导入相关的依赖包,便可以直接引用。
使用方式:类名点方法 ,返回值为发送的验证码,类型为字符串
工具类MailUtil.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Random;
@Component
public class MailUtil {
@Autowired(required = false)
private JavaMailSenderImpl mailSender;
private static MailUtil mailUtil;
@PostConstruct
public void init(){
mailUtil = this;
mailUtil.mailSender = this.mailSender;
}
public static String mail1() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
Random random = new Random();
StringBuffer str = new StringBuffer();
for(int i = 0; i < 6; i++){
str.append(random.nextInt(10));
}
String s = str.toString();
System.out.println("邮箱验证码:"+s);
mailMessage.setSubject("验证码");
mailMessage.setText("您的验证码为:"+s+",如非本人操作,请忽略!请勿回复此邮箱");
// 收件人
// mailMessage.setTo("li17718541773@163.com");
mailMessage.setTo("1303205856@qq.com");
// 发件人
mailMessage.setFrom("1303205856@qq.com");
mailUtil.mailSender.send(mailMessage);
System.out.println("发送成功");
return s;
}
相关配置
#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=发送验证码的邮箱
spring.mail.password=POP3/SMTP服务
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
相关依赖
<!--邮件发送核心包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>