文章目录

  • 1.引入依赖
  • 2.邮箱信息配置类
  • 3.发送邮件的工具类
  • 4.main函数测试发送邮件
  • 5.集成js插件ueditor编写带样式的邮件正文
  • 5.1.页面集成插件
  • 5.2.编写后台接口接收数据并发送邮件
  • 6.项目配套代码


1.引入依赖

<!--发送邮件需要的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2.邮箱信息配置类

@Component
@Configuration
@ConfigurationProperties(prefix = "mail")
public class EmailConfig {

    /**
     * 邮箱服务的地址
     * qq邮箱=smtp.qq.com   腾讯企业邮箱=smtp.exmail.qq.com
     */
    private String  host;

    /**
     * 邮箱服务使用的端口
     * qq邮箱=25  腾讯企业邮箱=465
     */
    private Integer  port;

    /**
     * 设置ssl访问
     * qq邮箱=false  腾讯企业邮箱=true
     */
    private boolean ssl;

    /**
     * 发件人
     */
    private String  username;

    /**
     * 客户端授权码
     */
    private String  password;

    /**
     * 发件人的昵称
     */
    private String  formName;

    /**
     * 收件人的邮箱账号
     */
    @Value("#{'${mail.to}'.split(',')}")
    private String[] to;
    //省略get,set方法
}

配置文件

server:
  port: 8027
spring:
  servlet:
    multipart:
      # 设置上传文件的大小
      max-file-size: 50MB
      #设置 整个请求的大小
      max-request-size: 70MB
mail:
  host: smtp.qq.com
  port: 25
  username: xxx@qq.com
  password: xxxx
  formName: 皓亮君
  to: xxxx1@qq.com,xxxx2@qq.com

3.发送邮件的工具类

下面工具类对外提供服务的sendEmailByParam()方法,处理发送邮件的逻辑在send()方法里

  • 支持发送带网页样式的邮件内容
  • 支持附件使用File本地文件和MultipartFile网页文件
public class EmailUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);

    private EmailUtil() {
    }

    private static class FileInfo {

        public FileInfo(String name, InputStream inputStream) {
            this.name = name;
            this.inputStream = inputStream;
        }

        private String name;

        private InputStream inputStream;

        public String getName() {
            return name;
        }

        public InputStream getInputStream() {
            return inputStream;
        }

    }


    public static boolean sendEmailByParam(EmailConfig emailConfig, List<File> fileList, String subject, String content) {
        try {
            List<FileInfo> fileInfoList = new ArrayList<>();
            if (fileList != null) {
                for (File file : fileList) {
                    fileInfoList.add(new FileInfo(file.getName(), new FileInputStream(file)));
                }
            }
            send(emailConfig, fileInfoList, subject, content);
            return true;
        } catch (Exception e) {
            LOGGER.error("邮件发送失败: errorMsg={}", e.getMessage());
            return false;
        }
    }

    public static boolean sendEmailByParam(EmailConfig emailConfig, MultipartFile[] fileList, String subject, String content) {
        try {
            List<FileInfo> fileInfoList = new ArrayList<>();
            if (fileList != null) {
                for (MultipartFile file : fileList) {
                    fileInfoList.add(new FileInfo(file.getName(), file.getInputStream()));
                }
            }
            send(emailConfig, fileInfoList, subject, content);
            return true;
        } catch (Exception e) {
            LOGGER.error("邮件发送失败: errorMsg={}", e.getMessage());
            return false;
        }
    }


    /**
     * 发送邮件的主要代码
     */
    private static void send(EmailConfig emailConfig, List<FileInfo> fileList, String subject, String text) throws Exception {
        JavaMailSenderImpl jms = new JavaMailSenderImpl();
        MimeMessage mimeMessage = jms.createMimeMessage();
        //是否包含附件
        boolean multipart = fileList.size() > 0;
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart, "utf-8");
        //设置邮箱服务的地址
        jms.setHost(emailConfig.getHost());
        //设置邮箱服务的端口
        jms.setPort(emailConfig.getPort());
        //设置发邮件的账号
        jms.setUsername(emailConfig.getUsername());
        //设置发邮件的账号的客户端授权码
        jms.setPassword(emailConfig.getPassword());
        //设置邮件内容的编码格式
        Properties p = new Properties();
        p.setProperty("mail.smtp.auth", "true");
        if (emailConfig.isSsl()) {
            //设置ssl认证信息
            p.setProperty("mail.transport.protocol", "smtp");
            p.put("mail.smtp.ssl.enable", "true");
            //开启安全协议
            MailSSLSocketFactory sf = null;
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.socketFactory", sf);
        }
        jms.setJavaMailProperties(p);
        //设置发送人心
        helper.setFrom(emailConfig.getUsername(), emailConfig.getFormName());
        //设置收集人的账号信息       也可以把集合转换成字符串数组   String to[] = new String[List.size]; List.toArray(to);
        helper.setTo(emailConfig.getTo());
        //设置邮件主题
        helper.setSubject(subject);
        //设置邮件内容为网页格式
        helper.setText(text, true);
        //纯文本格式
        //helper.setText(text);
        //设置邮件的附件信息
        for (FileInfo fileInfo : fileList) {
            ByteArrayDataSource attachment = new ByteArrayDataSource(fileInfo.getInputStream(), "application/octet-stream");
            helper.addAttachment(fileInfo.getName(), attachment);
        }
        jms.send(mimeMessage);
        LOGGER.info("发送成功!");
    }
}

4.main函数测试发送邮件

public static void main(String[] args) {
        EmailConfig emailConfig = new EmailConfig();
        //qq邮箱=smtp.qq.com   腾讯企业邮箱=smtp.exmail.qq.com
        emailConfig.setHost("smtp.qq.com");
        //qq邮箱=25  腾讯企业邮箱=465
        emailConfig.setPort(25);
        //qq邮箱=false  腾讯企业邮箱=true
        emailConfig.setSsl(false);
        //发件人邮箱地址
        emailConfig.setUsername("xxx@qq.com");
        //客户端授权码 填写你的邮箱客户端授权码
        emailConfig.setPassword("xxx");
        //发送人昵称
        emailConfig.setFormName("皓亮君");
        //接受邮件人的邮箱账号
        emailConfig.setTo(new String[]{"xxx@qq.com"});
        List<File> fileList = Arrays.asList(new File("C:\\Users\\Administrator\\Desktop\\test\\1.txt"), new File("C:\\Users\\Administrator\\Desktop\\test\\2.txt"));
        sendEmailByParam(emailConfig, fileList, "邮件主题", "邮件的内容");
    }

运行完成了打印发送成功,则邮件成功发送了到收件人手中

springboot office365邮件_发送邮件


springboot office365邮件_List_02

5.集成js插件ueditor编写带样式的邮件正文

5.1.页面集成插件

springboot office365邮件_发送邮件_03

依赖的文件比较多,就不贴代码,需要的可以重文章下方的github地址中自行下载项目源代码,页面上集成ueditor插件代码如下

<!DOCTYPE HTML>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <title>邮件内容编辑</title>
</head>
<body>
<form id="sendEmailForm" action="/sendEmail" method="post" ENCTYPE="multipart/form-data">
    <div>
        邮件标题 <input type="text" class="input-text" name="subject">
    </div>
    <div>
        邮件正文:
        <script id="editor" name="text" type="text/plain"></script>
    </div>
    <div>
        附件一:
    <input type="file" name="file">
    </div>
    <div>
        附件二:
        <input type="file" name="file">
    </div>
    <button class="btn btn-primary radius" type="submit" id="save"> 保存</button>
</form>
<script type="text/javascript" charset="utf-8" src="/js/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/js/ueditor/ueditor.all.js"></script>
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="/js/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>
    var ue = UE.getEditor('editor', {
        autoHeightEnabled: true,
        autoFloatEnabled: true,
        initialFrameHeight: 170
    });
</script>
</body>
</html>

5.2.编写后台接口接收数据并发送邮件

@RestController
public class EmailController {

    @Autowired
    private EmailConfig emailConfig;

    @PostMapping("/sendEmail")
    public String sendEmail(@RequestParam String subject, @RequestParam String text, @RequestParam("file") MultipartFile[] multipartFileList) {
        boolean flag=EmailUtil.sendEmailByParam(emailConfig, multipartFileList, subject, text);
        return flag?"发送成功!":"发送失败!";
    }

}

运行项目后在页面上方访问http://localhost:8027/
然后根据插件功能自行调整样式和排版格式,选择是否需要上传文件,然后在点保存提交请求。

springboot office365邮件_List_04

看到下面的信息则表示邮件已成功发送。

springboot office365邮件_List_05

springboot office365邮件_发送邮件_06