1、导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、配置yaml文件
spring:
mail:
username: QQ邮箱
password: 授权码
host: smtp.qq.com
#qq要开启加密授权验证
properties:
mail:
smtp:
ssl:
enable: true
qq授权码获取
请求邮箱》设置》账户
3、编写MailUtils
@Component
@Async
public class MailUtils {
@Autowired
private JavaMailSenderImpl mailSender;
/**
* 复杂邮件发送
* @param html 是否开启html标签
* @param subject 标题
* @param text 内容
* @param textHtml 是否在文本中开启html标签
* @param fileName 上传后的附件名
* @param pathName 上传附件路径
* @param toMail 发送邮件给谁
* @param fromMail 发送邮件人
* @throws MessagingException
* @Author wu
*/
public void sendMail(Boolean html,String subject,String text,Boolean textHtml,String fileName,String pathName,String toMail,String fromMail) throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, html);
//正文
helper.setSubject(subject);
helper.setText(text,textHtml);
//附件
helper.addAttachment(fileName,new File(pathName));
//发送给谁
helper.setTo(toMail);
//发送者
helper.setFrom(fromMail);
mailSender.send(mimeMessage);
}
/**
* 简单的邮件发送
* @param subject 标题
* @param text 内容
* @param toMail 发送给谁
* @param fromMail 发送者
* @Author wu
*/
public void sendMail(String subject,String text,String toMail,String fromMail)
{
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject(subject);
simpleMailMessage.setText(text);
simpleMailMessage.setTo(toMail);
simpleMailMessage.setFrom(fromMail);
mailSender.send(simpleMailMessage);
}
}
4、controller调用实现
@RestController
public class AsyncController {
@Autowired
MailUtils mailUitls;
@GetMapping("/mail")
public String mail() throws MessagingException {
mailUitls.sendMail(true,"标题一","内容n",true,"1.jpg","D:\\文件数据\\images\\img2.jpg","发送给谁的邮箱","发送者邮箱");
return "ok";
}
}
5、启动
@EnableAsync //开启异步支持
@SpringBootApplication
public class SpringbootMailApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09MailApplication.class, args);
}
}