Java技术:SpringBoot实现邮件发送功能

简介: 邮件发送功能基本是每个完整业务系统要集成的功能之一,今天小编给大家介绍一下SpringBoot实现邮件发送功能,希望对大家能有所帮助!

d0543ce9e311620ce89e2ac606383ea2.png

目录

1、创建一个基本的SpringBoot项目,pom文件导入发送邮件的依赖

2、application.yml 文件配置配置邮件发送信息

3、创建IEmailService 接口文件,定义邮件发送的接口

4、创建IEmailService接口的实现类EmailService.java 文件

5、新建邮件发送模板 email.html

6、新建测试类,主要代码如下

7、效果截图

邮件发送功能基本是每个完整业务系统要集成的功能之一,今天小编给大家介绍一下SpringBoot实现邮件发送功能,希望对大家能有所帮助!

今天主要给大家分享简单邮件发送、HTML邮件发送、包含附件的邮件发送三个例子,具体源码链接在文章末尾,有需要的朋友可以自己下载学习一下。

1、创建一个基本的SpringBoot项目,pom文件导入发送邮件的依赖

<!--邮件发送依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker制作Html邮件模板依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、application.yml 文件配置配置邮件发送信息

spring:
mail:
host: smtp.qq.com
username: xxx@qq.com  #发件人邮箱
password: xxxxx  #授权码
protocol: smtp
properties.mail.smtp.auth:true
properties.mail.smtp.port:465#发件邮箱端口
properties.mail.display.sendmail: xiaoMing
properties.mail.display.sendname: xiaoming
properties.mail.smtp.starttls.enable:true
properties.mail.smtp.starttls.required:true
properties.mail.smtp.ssl.enable:true#是否启用ssl
default-encoding: utf-8#编码格式    
freemarker:
cache:false
settings:
classic_compatible:true
suffix: .html
charset: UTF-8
template-loader-path: classpath:/templates/

3、创建IEmailService 接口文件,定义邮件发送的接口

package com.springboot.email.email.service;


import javax.mail.MessagingException;
import java.util.List;


public interface IEmailService {
    /**
     * 发送简单文本邮件
     */
    void sendSimpleMail(String receiveEmail, String subject, String content);
    /**
     * 发送HTML格式的邮件
     */
    void sendHtmlMail(String receiveEmail, String subject, String emailContent) throws MessagingException;
    /**
     * 发送包含附件的邮件
     */
    void sendAttachmentsMail(String receiveEmail, String subject, String emailContent, List<String> filePathList) throws MessagingException;
}

4、创建IEmailService接口的实现类EmailService.java 文件

package com.springboot.email.email.service.impl;


import com.springboot.email.email.service.IEmailService;
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 javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
@Service
public class EmailServiceImpl implements IEmailService {
    @Resource
    private JavaMailSender mailSender;


    @Value("${spring.mail.username}")
    private String fromEmail;


    /**
     * 发送简单文本邮件
     */
    public void sendSimpleMail(String receiveEmail, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(receiveEmail);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }
    /**
     * 发送Html格式的邮件
     */
    public  void sendHtmlMail(String receiveEmail,String subject,String emailContent) throws MessagingException
    {
        init(receiveEmail, subject, emailContent, mailSender, fromEmail);
    }


    public static void init(String receiveEmail, String subject, String emailContent, JavaMailSender mailSender, String fromEmail) throws MessagingException {
        MimeMessage message= mailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(message,true);
        helper.setFrom(fromEmail);
        helper.setTo(receiveEmail);
        helper.setSubject(subject);
        helper.setText(emailContent,true);
        mailSender.send(message);
    }


    /**
     * 发送包含附件的邮件
     */
    public void sendAttachmentsMail(String receiveEmail, String subject, String emailContent, List<String> filePathList) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        //带附件第二个参数true
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(fromEmail);
        helper.setTo(receiveEmail);
        helper.setSubject(subject);
        helper.setText(emailContent, true);
        //添加附件资源
        for (String item : filePathList) {
            FileSystemResource file = new FileSystemResource(new File(item));
            String fileName = item.substring(item.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
        }
        //发送邮件
        mailSender.send(message);
    }
}

5、新建邮件发送模板 email.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
    <style>
        td {
            border: black 1px solid;
        }
    </style>
</head>
<body>
<h1>工资条</h1>
<table style="border: black 1px solid;width: 750px">
    <thead>
    <td>序号</td>
    <td>姓名</td>
    <td>基本工资</td>
    <td>在职天数</td>
    <td>奖金</td>
    <td>社保</td>
    <td>个税</td>
    <td>实际工资</td>
    </thead>
    <tbody>
    <tr>
        <td>${salary.index}</td>
        <td>${salary.name}</td>
        <td>${salary.baseSalary}</td>
        <td>${salary.inDays}</td>
        <td>${salary.reward}</td>
        <td>${salary.socialSecurity}</td>
        <td>${salary.tax}</td>
        <td>${salary.actSalary}</td>
    </tr>
    </tbody>
</table>
</body>
</html>

6、新建测试类,主要代码如下

/**
 * 测试简单文本文件
 */
@Test
public void EmailTest() {
    emailService.sendSimpleMail("hgmyz@outlook.com", "测试邮件", "springboot 邮件测试");
}


@Test
public void HtmlEmailTest() throws MessagingException {
    String receiveEmail = "hgmyz@outlook.com";
    String subject = "Spring Boot 发送Html邮件测试";
    String emailContent = "<h2>您好!</h2><p>这里是一封Spring Boot 发送的邮件,祝您天天开心!<img " + "src='https://p3.toutiaoimg.com/origin/tos-cn-i-qvj2lq49k0/a43f0608912a4ecfa182084e397e4b81?from=pc' width='500' height='300' /></p>" + "<a href='https://programmerblog.xyz' title='IT技术分享设社区' targer='_blank'>IT技术分享设社区</a>";
    emailService.sendHtmlMail(receiveEmail, subject, emailContent);
}




@Test
public void templateEmailTest() throws IOException, TemplateException, MessagingException {
    String receiveEmail = "hgmyz@outlook.com";
    String subject = "Spring Boot 发送Templete邮件测试";
    //添加动态数据,替换模板里面的占位符
    SalaryVO salaryVO = new SalaryVO(1, "小明", 2, 9000.00, 350.06, 280.05, 350.00, 7806.00);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email.html");
    //将模板文件及数据渲染完成之后,转换为html字符串
    Map<String, Object> model = new HashMap<>();
    model.put("salary", salaryVO);
    String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    emailService.sendHtmlMail(receiveEmail, subject, templateHtml);
}


@Test
public void emailContailAttachmentTest() throws IOException, TemplateException, MessagingException {
    String receiveEmail = "hgmyz@outlook.com";
    String subject = "Spring Boot 发送包含附件的邮件测试";
    //添加动态数据,替换模板里面的占位符
    SalaryVO salaryVO = new SalaryVO(1, "小王", 2, 9000.00, 350.06, 280.05, 350.00, 7806.00);
    Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email.html");
    //将模板文件及数据渲染完成之后,转换为html字符串
    Map<String, Object> model = new HashMap<>();
    model.put("salary", salaryVO);
    String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    List<String> fileList = new ArrayList<>();
    fileList.add("F:\\邮件测试.docx");
    fileList.add("F:\\5.png");
    fileList.add("F:\\db.jpg");
    emailService.sendAttachmentsMail(receiveEmail, subject, templateHtml, fileList);
}

7、效果截图

简单文版邮件

67b287e79e92ae7f6b6e155ca16c6ae8.png

html文件

899417287aa1967d3cb1b8b2f73f7220.png

包含附件的邮件

687a355957514ac1cfbe4ea65371b6af.png

Gitee地址:https://gitee.com/hgm1989/springboot-email.git

相关文章
|
20天前
|
NoSQL Java 数据库连接
深入探索 Java 后台开发的核心技术
【4月更文挑战第5天】本文探讨了Java后台开发的关键技术,包括Spring框架与Spring Boot的使用,MyBatis和Hibernate的ORM选择,关系型与NoSQL数据库的适用场景,线程池与异步处理在并发中的作用,微服务架构及RESTful API设计。这些核心技术有助于开发者打造稳定、高性能的Java后台系统,适应不断发展的云计算和人工智能需求。
|
22天前
|
缓存 前端开发 Java
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
【Java】仓库管理系统 SpringBoot+LayUI+DTree(源码)【独一无二】
|
26天前
|
缓存 Java C#
【JVM故障问题排查心得】「Java技术体系方向」Java虚拟机内存优化之虚拟机参数调优原理介绍(一)
【JVM故障问题排查心得】「Java技术体系方向」Java虚拟机内存优化之虚拟机参数调优原理介绍
73 0
|
6天前
|
人工智能 前端开发 Java
Java语言开发的AI智慧导诊系统源码springboot+redis 3D互联网智导诊系统源码
智慧导诊解决盲目就诊问题,减轻分诊工作压力。降低挂错号比例,优化就诊流程,有效提高线上线下医疗机构接诊效率。可通过人体画像选择症状部位,了解对应病症信息和推荐就医科室。
101 10
|
6天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
7天前
|
存储 数据可视化 安全
Java全套智慧校园系统源码springboot+elmentui +Quartz可视化校园管理平台系统源码 建设智慧校园的5大关键技术
智慧校园指的是以物联网为基础的智慧化的校园工作、学习和生活一体化环境,这个一体化环境以各种应用服务系统为载体,将教学、科研、管理和校园生活进行充分融合。无处不在的网络学习、融合创新的网络科研、透明高效的校务治理、丰富多彩的校园文化、方便周到的校园生活。简而言之,“要做一个安全、稳定、环保、节能的校园。
33 6
|
8天前
|
监控 前端开发 算法
Java技术体系
Java技术体系(韩顺平老师整理)
9 0
|
19天前
|
存储 安全 Java
Java中实现高效的字符串拼接技术
【4月更文挑战第6天】在Java编程中,字符串拼接是一个常见的操作。然而,由于字符串的不可变性,频繁的拼接操作可能会导致性能问题。本文将探讨Java中实现高效字符串拼接的技术,包括使用StringBuilder类、StringBuffer类以及Java 8中的StringJoiner类。通过对比这些技术的优缺点,我们将为您提供在不同场景下选择合适的字符串拼接方法的建议。
|
21天前
|
JavaScript Java 关系型数据库
基于 java + Springboot + vue +mysql 大学生实习管理系统(含源码)
本文档介绍了基于Springboot的实习管理系统的设计与实现。系统采用B/S架构,旨在解决实习管理中的人工管理问题,提高效率。系统特点包括对用户输入的验证和数据安全性保障。功能涵盖首页、个人中心、班级管理、学生管理、教师管理、实习单位管理、实习作业管理、教师评分管理、单位成绩管理和系统管理等。用户分为管理员、教师和学生,各自有不同的操作权限。
|
26天前
|
Java Maven Spring
SpringBoot运行出现 Lookup method resolution failed; nested exception is java.lang.IllegalStateException
SpringBoot运行出现 Lookup method resolution failed; nested exception is java.lang.IllegalStateException
34 0