Spring Boot Sample 030之spring-boot-io-email

一、环境

  • Idea 2020.1
  • JDK 1.8
  • maven

二、目的

spring boot 通过整合email

gitHub地址: https://github.com/ouyushan/ouyushan-spring-boot-samples

三、步骤

3.1、点击File -> New Project -> Spring Initializer,点击next

3.2、在对应地方修改自己的项目信息

3.3、选择Web依赖,选中Spring Web、Spring Boot DevTools,Apache Freemarker、Java Mail Sender。可以选择Spring Boot版本,本次默认为2.3.0,点击Next

3.4、项目结构

四、添加文件

pom.xml文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.ouyushan</groupId>
        <artifactId>ouyushan-spring-boot-samples</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>org.ouyushan</groupId>
    <artifactId>spring-boot-io-email</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-io-email</name>
    <description>Email project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties文件

spring.mail.host=smtp.126.com
spring.mail.username=ouyushan@126.com
spring.mail.password=**********

spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

Sender.java

package org.ouyushan.springboot.io.email.service;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 15:27
 */
public interface Sender {
    String sendMail();
}

SimpleSender.java

package org.ouyushan.springboot.io.email.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 14:54
 */

@Service
public class SimpleSender implements Sender {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    public String sendMail() {
        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人邮箱
        message.setFrom(this.mailProperties.getUsername());
        // 收信人邮箱
        message.setTo("511932633@qq.com");
        // 邮件主题
        message.setSubject("简单邮件测试");
        // 邮件内容
        message.setText("简单邮件测试");
        this.javaMailSender.send(message);
        return "success";
    }
}

HtmlSender.java

package org.ouyushan.springboot.io.email.service;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 15:26
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 15:33
 */

@Service
public class HtmlSender implements Sender {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    @Override
    public String sendMail() {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message);

        try {
            messageHelper.setFrom(this.mailProperties.getUsername());
            messageHelper.setTo("503742782@qq.com");
            messageHelper.setSubject("HTML内容邮件测试");
            // 第二个参数表示是否html,设为true
            messageHelper.setText("<h1>HTML内容..</h1>", true);
            this.javaMailSender.send(message);
            return "success";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "false";
    }
}

AttachSender.java

package org.ouyushan.springboot.io.email.service;

import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 15:33
 */

@Service
public class AttachSender implements Sender{

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    @Override
    public String sendMail() {
        try {
            MimeMessage message = this.javaMailSender.createMimeMessage();
            // 第二个参数表示是否开启multipart模式
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);

            messageHelper.setFrom(this.mailProperties.getUsername());
            messageHelper.setTo("503742782@qq.com");
            messageHelper.setSubject("带附件的邮件测试");
            // 第二个参数表示是否html,设为true
            messageHelper.setText("<h1>HTML内容..</h1>", true);
            messageHelper.addAttachment("附件名称",
                    new ClassPathResource("banner.gif"));

            this.javaMailSender.send(message);
            return "success";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "false";
    }
}

InnerAttachSender.java

package org.ouyushan.springboot.io.email.service;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: ouyushan
 * @Email: ouyushan@hotmail.com
 * @Date: 2020/6/9 15:37
 */
@Service
public class InnerAttachSender implements Sender {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Autowired
    private Configuration freemarkerConfiguration;

    @Override
    public String sendMail() {
        try {
            MimeMessage message = this.javaMailSender.createMimeMessage();
            // 第二个参数表示是否开启multipart模式
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(this.mailProperties.getUsername());
            messageHelper.setTo("511932633@qq.com");
            messageHelper.setSubject("基于freemarker模板的邮件测试");

            Map<String, Object> model = new HashMap<>();
            model.put("username", "itmuch");
            model.put("event", "IT牧场大事件");
            String content = null;
            content = FreeMarkerTemplateUtils.processTemplateIntoString(
                    this.freemarkerConfiguration.getTemplate("mail.ftl"), model);
            // 第二个参数表示是否html,设为true
            messageHelper.setText(content, true);
            this.javaMailSender.send(message);
            return "success";

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "false";
    }
}

mail.ftl

<h1>亲爱的${username}, 欢迎关注${event}</h1>

五、测试

SpringBootIoEmailApplicationTests.java

package org.ouyushan.springboot.io.email;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureWebMvc
class SpringBootIoEmailApplicationTests {

    @Test
    public void testSimpleSender(@Autowired MockMvc mockMvc) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/simpleSender")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print());
    }


    @Test
    public void testHtmlSender(@Autowired MockMvc mockMvc) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/htmlSender")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void testAttachSender(@Autowired MockMvc mockMvc) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/attachSender")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void testInnerAttachSender(@Autowired MockMvc mockMvc) throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/innerAttachSender")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print());
    }

}
posted @ 2020-11-15 14:25  欧虞山  阅读(138)  评论(0编辑  收藏  举报