1.打开QQ邮箱的xxx服务,记住授权码
2.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3.application.properties中配置
spring.mail.host=
spring.mail.username=2813573389@
spring.mail.password=xxxxx //这个不是密码,是QQ邮箱授权码
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.port=465
spring.mail.properties.mail.display.sendmail: Javen
spring.mail.properties.mail.display.sendname: ChairC's blog official
spring.mail.properties.mail.smtp.ssl.enable: true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
4.代码
package com.zhaoguo.testlogin.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Random;
@Service
public class MyEMail {
@Value("${spring.mail.username}")
private String from;
@Autowired
private JavaMailSender javaMailSender;
/**
* 发送验证码
*
* @param email
* @param session
*/
public void sendMail(String email, HttpSession session) {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//设置发件人
mimeMessageHelper.setFrom(from);
//设置收件人
mimeMessageHelper.setTo(email);
//设置邮件主题
mimeMessageHelper.setSubject("来不及许愿的星雨测试用户邮箱注册激活");
//生成随机数
String random = randomInteger();
//将随机数放置到session中
session.setAttribute("code",random);
System.out.println(random);
//设置验证码的样式
mimeMessageHelper.setText("激活验证码为:" + random);
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void sendMail1(String email, HttpSession session){
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setTo(email);
//生成随机数
String random = randomInteger();
// 将验证信息存入session
session.setAttribute("code",random);
// 自动信息发送
String mailSubject = "来不及许愿的星雨测试用户邮箱注册激活";
String mailContent = "激活验证码为:" + random;
simpleMailMessage.setSubject(mailSubject);
simpleMailMessage.setText(mailContent);
javaMailSender.send(simpleMailMessage);
}
/**
* 生成随机验证码
*
* @return
*/
private String randomInteger() {
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
//生成6位的随机数
for (int i = 0;i<6;i++){
int i1 = random.nextInt(10);
stringBuffer.append(i1);
}
return stringBuffer.toString();
}
}
5.注意:如果一个类中有自动注入的内容,那么在另一个类中是不可以实例化第一个类的,只能注入第一个类。