1、首先需要导入pom依赖
<!-- 引入emil模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、配置application.properties
#邮件定时任务
spring.mail.username=****@sina.com
#密码是邮箱的授权码
spring.mail.password=授权码
#用的那哪类型的邮箱账号,就输入哪种的smtp服务器地址
spring.mail.host=smtp.sina.com
#有些邮箱需要这个,如qq邮箱
#spring.mail.properties.mail.smtp.ssl.enable=true
配置如下图
3、测试代码
@RestController
public class MailController {
@Autowired
JavaMailSender javaMailSender;
@PublicInterface
@RequestMapping("/test/saveMailSender")
public void saveMailSender(){
//发送简单的邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("邮件标题");
message.setText("邮件的具体内容");
//发送给谁,可以发送多个邮箱账号
message.setTo("****@qq.com");
//谁发送的
message.setFrom("****@sina.com");
javaMailSender.send(message);
}
@PublicInterface
@RequestMapping("/test/saveMailSenders")
public void saveMailSenders() throws Exception{
//发送复杂的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
//设置邮箱内容
helper.setSubject("邮件标题");
//true开启html,b标签才会生效
helper.setText("<b style='color:red'>邮件的具体内容</b>",true);
//发送给谁,可以发送多个邮箱账号
helper.setTo("****@qq.com");
//谁发送的
helper.setFrom("****@sina.com");
//上传附件
helper.addAttachment("1.png",new File("C:\\Users\\zhao\\Desktop\\1.png"));
helper.addAttachment("2.png",new File("C:\\Users\\zhao\\Desktop\\2.png"));
javaMailSender.send(mimeMessage);
}
}