SpringBoot 实现发件和接收邮箱功能,这里,先以QQ和163邮箱为例。
项目
SwaggerConfiguration

package com.springbootemaildemo.config; 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 SwaggerConfiguration { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("com.springboot")) .paths(PathSelectors.any()) .build(); // return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build(); } /** * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个 * * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() /** * 页面标题 */ .title("Spring Boot Swagger2 RESTful API") /** * 创建人 */ .contact(new Contact("W001", "https://www.cnblogs.com/", "")) /** * 版本号 */ .version("1.0") /** * 描述 */ .description("API 描述") .build(); } }
MailApplication
注意:如果在这MailApplication类上加@EnableSwagger2 注解,就不用SwaggerConfiguration这个配置类了。

package com.springbootemaildemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * \引入了一个注解@EnableSwagger2来启动swagger注解。 * (启动该注解使得用在controller中的swagger注解生效, * 覆盖的范围由@ComponentScan的配置来指定, * 这里默认指定为根路径”com.springboot”下的所有controller) * 也可以单独写衣swaggerConfigura */ @EnableSwagger2 //启动swagger注解 @SpringBootApplication public class MailApplication { public static void main(String[] args) { SpringApplication.run(MailApplication.class, args); } }
MailController

package com.springbootemaildemo.controller; import com.springbootemaildemo.dto.MailSendDto; import com.springbootemaildemo.entity.ResponseEntity; import com.springbootemaildemo.service.MailService; import com.springbootemaildemo.service.impl.MailServiceImpl; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/mail") @Api(value = "邮件系统") public class MailController { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); @Autowired MailService mailServiceImpl; @ApiOperation(value = "发送邮件", notes = "发送邮件") @PostMapping(value = "/send") public ResponseEntity send(@RequestBody MailSendDto dto) { mailServiceImpl.sendSimpleMailMessge(dto); logger.info("MailController send success............."); return new ResponseEntity("200", null, "success"); } }
MailSendDto

package com.springbootemaildemo.dto; import io.swagger.annotations.ApiModel; @ApiModel(value = "DTO") public class MailSendDto { private String to; private String subject; private String content; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
ResponseEntity

package com.springbootemaildemo.entity; import lombok.Data; import java.io.Serializable; public class ResponseEntity implements Serializable { private String code; private String msg; private Object data; public ResponseEntity() { } public ResponseEntity(String code, String msg) { this.code = code; this.msg = msg; } public ResponseEntity(String code, Object data, String msg) { this.code = code; this.msg = msg; this.data = data; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
MailService

package com.springbootemaildemo.service; import com.springbootemaildemo.dto.MailSendDto; import java.util.Map; public interface MailService { /** * 发送普通邮件 * * @param dto */ void sendSimpleMailMessge(MailSendDto dto); /** * 发送普通邮件 * * @param to * @param subject * @param content */ void sendSimpleMailMessge(String to, String subject, String content); /** * 发送 HTML 邮件 * * @param to 收件人 * @param subject 主题 * @param content 内容 */ void sendMimeMessge(String to, String subject, String content); /** * 发送带附件的邮件 * * @param to 收件人 * @param subject 主题 * @param content 内容 * @param filePath 附件路径 */ void sendMimeMessge(String to, String subject, String content, String filePath); /** * 发送带静态文件的邮件 * * @param to 收件人 * @param subject 主题 * @param content 内容 * @param rscIdMap 需要替换的静态文件 */ void sendMimeMessge(String to, String subject, String content, Map<String, String> rscIdMap); }
MailServiceImpl

package com.springbootemaildemo.service.impl; import com.springbootemaildemo.dto.MailSendDto; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.Service; import com.springbootemaildemo.service.MailService; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.util.Map; @Service public class MailServiceImpl implements MailService { private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class); @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String sender; @Override public void sendSimpleMailMessge(MailSendDto dto) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(sender); message.setTo(dto.getTo()); message.setSubject(dto.getSubject()); message.setText(dto.getContent()); try { mailSender.send(message); logger.info("send success................."); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } @Override public void sendSimpleMailMessge(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(sender); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("send success................."); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } @Override public void sendMimeMessge(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(sender); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("send success................."); } catch (MessagingException e) { logger.error("发送MimeMessge时发生异常!", e); } } @Override public void sendMimeMessge(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(sender); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("send success................."); } catch (MessagingException e) { logger.error("发送带附件的MimeMessge时发生异常!", e); } } @Override public void sendMimeMessge(String to, String subject, String content, Map<String, String> rscIdMap) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(sender); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); for (Map.Entry<String, String> entry : rscIdMap.entrySet()) { FileSystemResource file = new FileSystemResource(new File(entry.getValue())); helper.addInline(entry.getKey(), file); } mailSender.send(message); logger.info("send success................."); } catch (MessagingException e) { logger.error("发送带静态文件的MimeMessge时发生异常!", e); } } }
application.yml
server: port: 8080 spring: mail: # 邮件服务地址 host: smtp.163.com # 端口 port: 25 # 编码格式 default-encoding: utf-8 # 用户名 username: xxxxx@163.com # 授权码 password: STMDCLUJRRVQQSAY # 其它参数 properties: mail: smtp: # 如果是用 SSL 方式,需要配置如下属性 starttls: enable: true required: true application: name: SPRING-BOOT-RMAIL
自测MailApplicationTests

package com.springbootemaildemo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.ResourceUtils; import com.springbootemaildemo.service.MailService; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; @RunWith(SpringRunner.class) @SpringBootTest public class MailApplicationTests { @Autowired private MailService mailServiceImpl; private static final String TO = "xxxx@qq.com"; private static final String SUBJECT = "主题 - 邮件"; private static final String CONTENT = "HAAPY"; /** * 测试发送普通邮件 */ @Test public void sendSimpleMailMessage() { mailServiceImpl.sendSimpleMailMessge(TO, SUBJECT, CONTENT); } /** * 测试发送html邮件 */ @Test public void sendHtmlMessage() { String htmlStr = "<h1>Test</h1>"; mailServiceImpl.sendMimeMessge(TO, SUBJECT, htmlStr); } /** * 测试发送带附件的邮件 * * @throws FileNotFoundException */ @Test public void sendAttachmentMessage() throws FileNotFoundException { File file = ResourceUtils.getFile("classpath:testFile.txt"); String filePath = file.getAbsolutePath(); mailServiceImpl.sendMimeMessge(TO, SUBJECT, CONTENT, filePath); } /** * 测试发送带附件的邮件 * * @throws FileNotFoundException */ @Test public void sendPicMessage() throws FileNotFoundException { String htmlStr = "<html><body>测试:图片1 <br> <img src=\'cid:pic1\'/> <br>图片2 <br> <img src=\'cid:pic2\'/></body></html>"; Map<String, String> rscIdMap = new HashMap<>(2); rscIdMap.put("pic1", ResourceUtils.getFile("classpath:pic01.jpg").getAbsolutePath()); rscIdMap.put("pic2", ResourceUtils.getFile("classpath:pic02.jpg").getAbsolutePath()); mailServiceImpl.sendMimeMessge(TO, SUBJECT, htmlStr, rscIdMap); } }
POM文件

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springbootemaildemo</groupId> <artifactId>springboot-email-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-email-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> </dependency> <!-- swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
接口测试:
如图: