用springBoot发送邮件
导入发送Mail依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置mail
spring.mail.username=2034281742@qq.com
spring.mail.password=iqmbatnwddzydfgb
#是什么邮箱就 smtp.XX.com
spring.mail.host=smtp.qq.com
#qq需要开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true
编写简单邮件
@Async //告诉spring这是一个异步方法
public void sendMail(){ //简单邮箱
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("这是lzl通过java程序发送的测试邮件");
message.setText("这是正文");
message.setTo("2034281742@qq.com");
message.setFrom("2034281742@qq.com");
senderMail.send(message);
System.out.println("邮件已发送");
}
编写一个复杂邮件
@Async
public void sendMimeMail() throws MessagingException { //发送复杂邮件
MimeMessage mimeMessage = senderMail.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true); //开启multipart,以实现发送附件
messageHelper.setSubject("这是lzl通过java程序发送的测试邮件");
messageHelper.setText("<p style='color:yellow'>这是正文</p>",true);
//附件
messageHelper.addAttachment("图片1",new File("D:\\Instalaltion package\\sunDowm.jpg"));
messageHelper.addAttachment("图片2",new File("D:\\Instalaltion package\\sunDowm.jpg"));
messageHelper.setTo("2034281742@qq.com");
messageHelper.setFrom("2034281742@qq.com");
senderMail.send(mimeMessage);
}
实现
package com.Google.controller;
import com.Google.service.TimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
@RestController
public class mailController {
@Autowired
TimeService timeService;
@RequestMapping("/mail")
public String sendMail() throws InterruptedException, MessagingException {
timeService.sendMimeMail();
timeService.sendMail();
timeService.timeSleep();
return "邮件已发送!请耐心等待";
}
}
启动
package com.Google;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync//开启异步功能
public class SpringBoot07MailTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot07MailTestApplication.class, args);
}
}