1. 邮箱发送
2. 准备工作
3. 整合SpringBoot
3.1 配置
依赖引入
<!-- 邮件服务--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
application.yml
spring:mail:host: smtp.qq.comport: 587username: QQ邮箱password: 授权码default-encoding: UTF-8properties:mail:debug: truesmtp:sockFactory:class: javax.net.ssl.SSLSocketFactory
其他
邮件对象
package com.ruoyi.common.vo;import lombok.Data;/*** 邮件对象*/
@Data
public class MailMessage {//发送者private String from;//接受者private String to;//抄送人private String cc;//主题private String subject;//内容private String text;
}
3.2 发送简单邮件
创建邮箱组件
package com.ruoyi.common.component;import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.vo.MailMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;import javax.annotation.Resource;/*** qq邮箱*/
@Component
public class MailService {@Value("${spring.mail.username}")private String mailFrom;@Resourceprivate JavaMailSender javaMailSender;/*** 发送邮件** @param from 发送者* @param to 收件人* @param cc 抄送人* @param subject 主题* @param content 内容*/public void sendSimpleMail(String from, String to, String cc, String subject, String content) {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setFrom(mailFrom);mailMessage.setTo(to);mailMessage.setCc(cc);mailMessage.setSubject(subject);mailMessage.setText(content);javaMailSender.send(mailMessage);}public void sendSimpleMail(MailMessage message) {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setFrom(mailFrom);String[] tos = StrUtil.splitToArray(message.getTo(), ";");mailMessage.setTo(tos);String[] ccs = StrUtil.splitToArray(message.getCc(), ";");mailMessage.setCc(ccs);mailMessage.setSubject(message.getSubject());mailMessage.setText(message.getText());javaMailSender.send(mailMessage);}
}
测试
控制层
@Resourceprivate MailService mailService;/*** 发送邮件** @param user* @return*/@GetMapping("/mail")public AjaxResult mail(MailMessage mailMessage) {mailService.sendSimpleMail(mailMessage);return AjaxResult.success();}