1.引入pom.xml依赖
<!-- 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.配置 application.yml
spring:
# 邮箱配置
mail:
host: smtp.qq.com #发送邮件服务器
username: *** #发送方QQ邮箱
password: *** #客户端授权码
protocol: smtp #发送邮件协议
properties.mail.smtp.auth: true
properties.mail.smtp.port: 465 #端口号465或587
properties.mail.display.sendmail: guang #可以任意
properties.mail.display.sendname: guang #可以任意
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
default-encoding: utf-8
from: *** #与上面的username保持一致
3.Swagger配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.guang.message.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("邮箱测试API")
.description("2019.12")
.termsOfServiceUrl("")
.contact(new Contact("测试","",""))
.version("1.0")
.build();
}
}
4.编写接口IMailService
import javax.mail.MessagingException;
public interface IMailService {
void sendSimpleMail(String to, String subject, String content);
void sendHtmlMail(String to, String subject, String content) throws MessagingException;
void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;
void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException;
}
5.编写实现类MailServiceImpl
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Component
public class MailServiceImpl implements IMailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.from}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
@Override
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf( File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
}
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
}
}
5.编写测试类Controller
@Api(tags = "邮箱测试接口")
@RestController
@RequestMapping("/mail")
public class MailController {
Logger logger = LoggerFactory.getLogger(MailController.class);
@Autowired
private IMailService mailService;
@GetMapping("/sendSimpleMail")
@ApiOperation("发送简单文本")
@ApiImplicitParams({
@ApiImplicitParam(name = "mail", value = "接收者邮箱", paramType = "query", required = true, defaultValue = "1761437173@qq.com"),
@ApiImplicitParam(name = "theme", value = "邮箱主题", paramType = "query", required = true, defaultValue = "测试简单文本邮件通讯"),
@ApiImplicitParam(name = "content", value = "简单文本内容", paramType = "query", required = true, defaultValue = "测试内容=>无bug通过")
})
public String sendSimpleMail(@ApiIgnore @RequestParam Map<String, String> params) {
logger.info(String.valueOf(params));
mailService.sendSimpleMail(params.get("mail"), params.get("theme"), params.get("content"));
return "成功";
}
@GetMapping("/sendHtmlMail")
@ApiOperation("发送HTML邮件")
@ApiImplicitParams({
@ApiImplicitParam(name = "mail", value = "接收者邮箱", paramType = "query", required = true, defaultValue = "1761437173@qq.com"),
@ApiImplicitParam(name = "theme", value = "邮箱主题", paramType = "query", required = true, defaultValue = "测试HTML邮件通讯"),
@ApiImplicitParam(name = "html", value = "html内容", paramType = "query", required = true, defaultValue = "测试内容<br/><hr><br/>无bug通过")
})
public String sendHtmlMail(@ApiIgnore @RequestParam Map<String, String> params) {
logger.info(String.valueOf(params));
try {
mailService.sendHtmlMail(params.get("mail"), params.get("theme"), params.get("html"));
} catch (MessagingException e) {
e.printStackTrace();
logger.error("发送HTML邮件--失败");
}
return "成功";
}
@GetMapping("/sendAttachmentsMail")
@ApiOperation("发送带附件的邮件")
@ApiImplicitParams({
@ApiImplicitParam(name = "mail", value = "接收者邮箱", paramType = "query", required = true, defaultValue = "1761437173@qq.com"),
@ApiImplicitParam(name = "theme", value = "邮箱主题", paramType = "query", required = true, defaultValue = "测试带附件的邮件通讯"),
@ApiImplicitParam(name = "content", value = "文本内容", paramType = "query", required = true, defaultValue = "测试内容=>无bug通过"),
@ApiImplicitParam(name = "path", value = "附件路径", paramType = "query", required = true, defaultValue = "C:\\Users\\admin\\Desktop\\1.jpg")
})
public String sendAttachmentsMail(@ApiIgnore @RequestParam Map<String, String> params) {
logger.info(String.valueOf(params));
try {
mailService.sendAttachmentsMail(params.get("mail"), params.get("theme"), params.get("content"), params.get("path"));
} catch (MessagingException e) {
e.printStackTrace();
logger.error("发送带附件的邮件--失败");
}
return "成功";
}
@GetMapping("/sendResourceMail")
@ApiOperation("发送正文中有静态资源的邮件")
@ApiImplicitParams({
@ApiImplicitParam(name = "mail", value = "接收者邮箱", paramType = "query", required = true, defaultValue = "1761437173@qq.com"),
@ApiImplicitParam(name = "theme", value = "邮箱主题", paramType = "query", required = true, defaultValue = "测试正文中有静态资源的邮件通讯"),
@ApiImplicitParam(name = "rscPath", value = "资源路径", paramType = "query", required = true, defaultValue = "C:\\Users\\admin\\Desktop\\1.jpg"),
@ApiImplicitParam(name = "rscId", value = "资源id ", paramType = "query", required = true, defaultValue = "1")
})
public String sendResourceMail(@ApiIgnore @RequestParam Map<String, String> params) {
logger.info(String.valueOf(params));
String content = "<html><body>这有是图片的邮件:<img src='cid:1' ></body></html>";
try {
mailService.sendResourceMail(params.get("mail"), params.get("theme"), content, params.get("rscPath"), params.get("rscId"));
} catch (MessagingException e) {
e.printStackTrace();
logger.error("发送正文中有静态资源的邮件--失败");
}
return "成功";
}
}
6.启动类
@SpringCloudApplication
public class MessageApplication {
public static void main(String[] args) {
SpringApplication.run(MessageApplication.class, args);
}
}