配置
#邮件发送配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=XXX@qq.com
#邮箱授权码
spring.mail.password=授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.protocol=smtp
service
@Slf4j@Service("mailService")publicclassMailService{@Value("${spring.mail.username}")private String from;@Autowiredprivate JavaMailSender mailSender;publicvoidsendSimpleMail(String to, String title, String content){
SimpleMailMessage message=newSimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
log.info("邮件发送成功");}/**
* 发送带附件的邮件
* @param to
* @param title
* @param cotent
* @param fileList
*/publicvoidsendAttachmentsMail(String to, String title, String cotent, List<File> fileList){
MimeMessage message= mailSender.createMimeMessage();try{
MimeMessageHelper helper=newMimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(title);
helper.setText(cotent);
String fileName= null;for(File file: fileList){
fileName= MimeUtility.encodeText(file.getName(),"GB2312","B");
helper.addAttachment(fileName, file);}}catch(Exception e){
e.printStackTrace();}
mailSender.send(message);
log.info("邮件发送成功");}
controller
@Autowiredprivate MailService mailService;@GetMapping(value="email")public StringgetCheckCode(@RequestParam String memberEmail){
System.out.println("邮箱为"+memberEmail);
String checkCode= String.valueOf(newRandom().nextInt(899999)+100000);
String message="您的注册验证码为:"+checkCode;try{
mailService.sendSimpleMail(memberEmail,"注册验证码", message);}catch(Exception e){return"500";}return checkCode;}