Spring中提供了JavaMailSender接口实现邮件发送功能,在SpringBoot2.X中也封装了发送邮件相关的Starter并且提供了自动化配置。

本文目录

一、添加对应的Starter二、添加发送邮件相关的配置三、实现发送邮件功能四、实现过程中踩过的坑1.中文附件乱码问题2.无法注入JavaMailSender问题

一、添加对应的Starter

pom.xml中添加下面依赖

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

二、添加发送邮件相关的配置

application.properties中添加邮件配置

spring.mail.host = smtp.163.com
spring.mail.port = 465
spring.mail.username = xxx@163.com
spring.mail.password = xxx
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.timeout = 25000
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.starttls.enable = true
spring.mail.properties.mail.smtp.starttls.required = true

三、实现发送邮件功能

本例中封装了一个MailServiceImpl,里面注入javaMailSender即可,具体代码如下

MailServiceImpl.java部分代码:

    /**
     * 发送邮件
     *
     * @Author: java碎碎念
     */
    public void sendMail(Email email) {
        long start = System.currentTimeMillis();
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(mailUserName);
            helper.setTo(email.getToAddress().toArray(new String[email.getToAddress().size()]));
            helper.setSubject(email.getSubject());
            helper.setText(email.getContent(), true);             if (null != email.getAttachments() && email.getAttachments().size() > 0) {
                for (File curFile : email.getAttachments()) {
                    FileSystemResource file = new FileSystemResource(curFile);
                    helper.addAttachment(MimeUtility.encodeWord(file.getFilename(), "utf-8", "B"), file);
                }
            }
            log.info("邮件开始发送");
            javaMailSender.send(mimeMessage);
            long sendMillTimes = System.currentTimeMillis() - start;
            log.info("邮件发送成功,sendTimes=" + sendMillTimes);
        } catch (Exception e) {
            log.error("发送html邮件时发生异常!", e);
        }
    }

MailController.java部分代码:

@RequestMapping(value = "/sendMail")
    public String sendEmail() {
        Email email_email = new Email();
        List<String> addressList = new ArrayList<String>();
        addressList.add("xxx@qq.com");
        email_email.setToAddress(addressList);
        email_email.setSubject("java碎碎念-主题测试");// 主题
        email_email.setContent("你好!<br><br> 测试邮件发送成功!");
        // 发送邮件
        mailService.sendMail(email_email);         return "ok";
    }

项目启动成功后访问http://localhost:8080/sendMail即可成功发送邮件,收到邮件截图如下:


收到邮件截图

到此发送邮件功能全部实现,有问题欢迎留言沟通哦!
完整源码地址: https://github.com/suisui2019/springboot-study

四、实现过程中踩过的坑

1.中文附件乱码问题

java mail发邮件是附件名过长默认会被截断显示乱码,在程序启动时设置主动设置为false可正常显示,具体设置代码如下

public static void main(String[] args) {
        //java mail发邮件时附件名过长默认会被截断,附件名显示【tcmime.29121.29517.50430.bin】,主动设为false可正常显示附件名
        System.setProperty("mail.mime.splitlongparameters", "false");
        SpringApplication.run(SendMailApplication.class, args);
    }

2.无法注入JavaMailSender问题

在application.properties中配置spring.mail.host即可。

推荐阅读

1.Spring Boot入门-快速搭建web项目
2.Spring Boot 2.X 整合Redis
3.Spring Boot 2.X 如何优雅的解决跨域问题?
4.Spring Boot 2.X 如何添加拦截器?
5.Spring Boot 2.X 集成spring session实现session共享
6.Redis Cluster搭建高可用Redis服务器集群
7.为什么单线程的Redis这么快?
8.一篇文章搞定SpringMVC参数绑定
9.SpringMVC+Mybatis 如何配置多个数据源并切换?
10.Spring条件注解@Conditional


限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

Java碎碎念公众号

SpringBoot 2.X从0到1实现邮件发送功能的更多相关文章

  1. Spring Boot 2.0 图文教程 | 集成邮件发送功能

    文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...

  2. 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...

  3. springboot下实现邮件发送功能

    springboot给我们封装好了邮件功能,非常简单,只需要稍微配置下就ok. 引入jar <dependency> <groupId>org.springframework. ...

  4. 用ASP.NET Core 1.0中实现邮件发送功能-阿里云邮件推送篇

    在上篇中用MailKit实现了Asp.net core 邮件发送功能,但一直未解决阿里云邮件推送问题,提交工单一开始的回复不尽如人意,比如您的网络问题,您的用户名密码不正确等,但继续沟通下阿里云客户还 ...

  5. SpringBoot邮件发送功能

    快速入门 在Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依赖: <dependency> <groupId>org.sp ...

  6. springboot做邮件发送功能时报错No qualifying bean of type 'org.springframework.mail.javamail.JavaMailSender' available:的问题解决方案

    1.检查application.yml中的配置是否正确 spring.mail.host=smtp.xxx.comspring.mail.username=xxx@xxx.comspring.mail ...

  7. springboot添加邮件发送及压缩功能

    springboot添加邮件发送及文件压缩功能 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/9190233.html 先来一段诗 ``` 就这样吧 忍受折磨 ...

  8. SpringBoot | 第二十六章:邮件发送

    前言 讲解了日志相关的知识点后.今天来点相对简单的,一般上,我们在开发一些注册功能.发送验证码或者订单服务时,都会通过短信或者邮件的方式通知消费者,注册或者订单的相关信息.而且基本上邮件的内容都是模版 ...

  9. SpringBoot集成邮件发送

    一:简述 在日常中的工作中难免会遇到程序集成邮件发送功能.接收功能:此篇文章我将使用SpringBoot集成邮件发送功能和接收功能:若对邮件一些基本协议和发送流程不懂的请务必参考我之前写的博客或者浏览 ...

随机推荐

  1. 记录自己的一次pjax性能优化

    什么是pjax? pjax = ajax + pushState 通过ajax让页面进行局部刷新,然后通过pushstate让url发生改变,再让pushState,让页面产生一个回退的记录,从而让页 ...

  2. 使用ping网络工具编写Shell脚本程序实现网络连接故障初步排查

    在学习ping命令的时候,突发奇想:为何不使用ping命令对网络连接故障进行排查? 具体思路: 1. ping  127.0.0.1 (虚拟网卡地址)以检查主机的TCP/IP协议栈是否正常. 2. p ...

  3. mySql中Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre的问题

    报错信息 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'a.id' ...

  4. jenkins构建,拉取不到最新版本代码,报clock of the subversion server appears to be out of sync

    一.问题描述 今天遇到个问题,我这边提交了代码后,一般会马上去jenkins上点一下,构建到开发环境上. 但是发现修改没生效,后来发现,提交的版本假设是3250,但是jenkins构建使用的版本为32 ...

  5. Vue中jsx的最简单用法

    最终页面显示效果为 <div class="open-service" style="color: #0199f0; cursor: pointer;"& ...

  6. ArcGIS Server 10.4切片图的制作与发布

    场景:有一张遥感卫星图,需要以切片图的形式发布 需要的资料:tif的格式遥感图像 发布步骤: 1.选择Service Editor-->Parameters-->Anti-Aliasing ...

  7. MySQL基础之常用函数

    数学函数的使用 常用数学函数 函数 作用 函数 作用 ceil() 进一取整 abs() 取绝对值 floor() 舍掉小数部分 power() 幂运算 round() 四舍五入 pi() 圆周率 t ...

  8. cgo在mac上编译

    用了cgo mac上编译不过的可以试试下面的方法 ../../pkg/mod/github.com/mattn/go-sqlite3@v1.:: fatal error: 'stdlib.h' fil ...

  9. Linux:Apache服务器的搭建

    下载安装并启动apache服务 安装apache服务 yum install -y httpd 启动apache服务 systemctl start httpd.service apache服务器的目 ...

  10. GetPrivateProfileInt 使用方法

    GetPrivateProfileInt =>从ini文件取得数值 <参数> lpApplicationName String,指定在其中查找条目的小节.注意这个字串是不区分大小写的 ...