配置
大约 1 分钟
配置
mail:
# 邮件服务器地址
host: smtp.qq.com
# 你的邮箱地址
username: 管理员的QQ邮箱,例如:xxxxxx@qq.com
# 授权码
password: xtgfgfqieqfycddh
# 编码格式
default-encoding: utf-8
# 协议
protocol: smtp
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
邮箱地址改成管理员的QQ邮箱
授权码如何获取呢?
获取授权码步骤
①、登录qq邮箱网站:https://wx.mail.qq.com/?cancel_login=true&from=get_ticket_fail
示例代码
/**
* 异步服务实现类
*/
@Slf4j
@Async("asyncExecutor")
@Service
@RequiredArgsConstructor
public class AsyncServiceImpl implements IAsyncService {
private final NoticeMapper noticeMapper;
private final SmartMapper smartMapper;
/**
* 邮件发送者
*/
@Value("${spring.mail.username}")
private String username;
private static final String MACHINE_TITLE = "机器故障通知";
private static final String TEMPLATE = "尊敬的管理员:部分机器发生了故障,请尽快处理!编号:";
/**
* 注入QQ发送邮件的bean
*/
@Autowired
private JavaMailSender javaMailSender;
/**
* 机器故障发送文本邮件
*
* @param content
*/
@Override
public void sendMachineMail(String content) {
try {
log.info("邮箱准备发送:故障机器为:{}",content);
SimpleMailMessage mailMessage= new SimpleMailMessage();
//发送者
mailMessage.setFrom(this.username);
//接收者
mailMessage.setTo(this.username);
//邮件标题
mailMessage.setSubject(MACHINE_TITLE);
//邮件内容
mailMessage.setText(TEMPLATE + content);
Notice notice = new Notice();
notice.setTitle(MACHINE_TITLE);
notice.setContent(TEMPLATE + content);
noticeMapper.insert(notice);
//发送邮箱
javaMailSender.send(mailMessage);
log.info("邮箱发送成功:故障机器为:{}",content);
} catch (Exception e) {
log.info("邮箱发送失败:故障机器为:{}",content);
}
}
}