前期工作
- 准备一个可以发邮件的邮箱,这里选择的是qq邮箱
- 点击设置
- 点击账户
- 点击开启(我已经是开启了)
- 按照提示步骤,获取授权码,记得保存好授权码
springboot
- pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 配置文件
spring:
mail:
host: smtp.qq.com
port: 587
username: 你的邮箱地址
password: 刚才生成的授权码
default-encoding: utf-8
- service层
package com.example.monitorserver.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.monitorserver.mapper.ProjectMapper;
import com.example.monitorserver.mapper.UserMapper;
import com.example.monitorserver.mapper.UserProjectMapper;
import com.example.monitorserver.po.Project;
import com.example.monitorserver.po.User;
import com.example.monitorserver.po.UserProject;
import com.example.monitorserver.service.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
@Service
@Slf4j
public class SendEmailServiceImpl implements SendEmailService {
@Autowired
private JavaMailSenderImpl mailSender;
@Resource
private UserProjectMapper userProjectMapper;
@Resource
private ProjectMapper projectMapper;
@Resource
private UserMapper userMapper;
//注入发件人地址【这里获取的是全局配置里的username】
@Value("${spring.mail.username}")
private String from;
@Override
public void sendSimpleEmail(String subject, String text,String email) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
//发送的对象
message.setTo(email);
//标题
message.setSubject(subject);
//内容
message.setText(text);
//发送
sendEmail(message);
return true;
}
private void sendEmail(SimpleMailMessage message) {
try {
mailSender.send(message);
log.debug("邮件发送成功");
} catch (MailException e) {
log.debug("邮件发送失败");
e.printStackTrace();
}
}
}
灿哥好强啊