SpringBoot 實現發件和接收郵箱功能


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();
    }
}
View Code

 

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);
    }
}
View Code

 

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");
    }
}
View Code

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;
    }
}
View Code

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;
    }
}
View Code

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);
}
View Code

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);
        }
    }
}
View Code

 

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);
    }
}
View Code

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>
View Code

 

接口測試:

 

 

如圖:

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM