基于springboot邮箱发送功能,Swagger测试

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 #端口号465587
    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;

/**
 * @Classname Swagger2Config
 * @Description swagger api文档配置
 * @Date 2019/12/16 9:55
 */
@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;

/**
 * @Date 2019/12/16 9:57
 */
public interface IMailService {
    /**
     * 发送文本邮件
     * @param to 接受方
     * @param subject 邮箱主题
     * @param content 文本内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 发送HTML邮件
     * @param to 接受方
     * @param subject 邮箱主题
     * @param content html内容
     * @throws MessagingException
     */
    void sendHtmlMail(String to, String subject, String content) throws MessagingException;

    /**
     * 发送带附件的邮件
     * @param to 接受方
     * @param subject 邮箱主题
     * @param content 文本内容
     * @param filePath 附件路径
     * @throws MessagingException
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException;

    /**
     * 发送正文中有静态资源的邮件
     * @param to 接受方
     * @param subject 邮箱主题
     * @param content 邮箱内容
     * @param rscPath 资源路径
     * @param rscId 资源id
     * @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;

/**
 * @Date 2019/12/16 9:58
 */
@Component
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.from}")
    private String from;

    /**
     * 发送文本邮件
     * @param to
     * @param subject
     * @param content
     */
    @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);
    }


    /**
     * 发送HTML邮件
     * @param to
     * @param subject
     * @param content
     */
    @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);
    }



    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param filePath 附件路径
     */
    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);
    }

    /**
     * 发送正文中有静态资源的邮件
     * @param to
     * @param subject
     * @param content
     * @param rscPath 资源路径
     * @param rscId 资源id
     */
    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

/**
 * @Classname MailController
 * @Date 2019/12/16 9:23
 */
@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);
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值