SpringBoot 整合Mail实现邮件发送

SprinBoot 系列文章: 

Spring Boot入门之Hello Spring Boot
SpringBoot 配置多个JdbcTemplate
SpringBoot 整合Mybatis
CAS统一登录认证(3): CAS 客户端接入实践
SpringBoot 整合Mail实现邮件发送
数据库连接池优化配置(druid,dbcp,c3p0)
SpringBoot+SpringSecurity+mysql实现认证与授

SpringBoot+Spring Security基于内存用户认证 
SpringBoot+WebSocket在线聊天室、消息推送 
SpringBoot+SpringData JPA操作Mysql数据库 
SpringBoot热部署值devtools配置
Spring Boot 资源文件属性配置 
Spring Boot Server等内容的配置
Spring Boot + FreeMarker模板 
SpringBoot+thymeleaf模板
SpringBoot +JDBC连接Mysql数据库
Zipkin分布式任务追踪 
SpringBoot应用部署到外置Tomcat 
Spring Boot + Swagger2 自动生成api接口文档 

SpringBoot整合Shiro安全框架          
SpringBoot+CAS Client 实现单点登录

SpringBoot 整合MyBatis-Plus  
SpringBoot + validation 接口参数校验
Springboot+Redis 实现API接口防刷限流
          
ShardingSphere-ShardingJdbc 数据分片(分库、分表)
ShardingSphere-ShardingJdbc 读写分离
ShardingSphere-ShardingJdbc 数据脱敏

            
springboot+sms 集成腾讯云短信平台
SpringBoot+RabbitMQ 实现消息队列
快速从零搭建一个SpringBoot Web项目
从零快速搭建一个SpringBoot Web项目
            
SpringBoot+ElasticSearch 实现全文检索
访问ElasticSearch的几种方式
SpringBoot + Activiti 工作流引擎(一、基本概念与环境搭建)
SpringBoot + Activiti 工作流引擎(二、流程&任务操作)
SpringBoot 定时任务 实现方式
            
SpringBoot + EhCache实现本地缓存
SpringBoot + Redis 实现分布式缓存 

一、简介

       邮件发送是网络应用中最常用的扩展功能之一,用户注册、忘记密码、动态验证码登录、发送运营情况等等都要使用到邮件的发送。在Spring发展的早期就提供了非常好用的 JavaMailSender接口实现邮件发送,而在Spring Boot的Starter模块中也为此提供了自动化配置,更加简化了邮件发送的过程。

二、引入依赖

在Spring Boot的工程中的 pom.xml 中引入 spring-boot-starter-mail 依赖:

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

 三、在 application.properties 中加入mail的配置

#### 1、qq邮箱的配置 ####
# 指定默认MimeMessage的编码,默认为: UTF-8
spring.mail.default-encoding=UTF-8
# 指定SMTP server host.
spring.mail.host=smtp.qq.com
# 指定SMTP server的用户名.
spring.mail.username=1456682842@qq.com
# 指定SMTP server登陆授权码
spring.mail.password=授权码
spring.mail.port=25
# 指定SMTP server使用的协议,默认为: smtp
spring.mail.protocol=smtp
# 指定是否在启动时测试邮件服务器连接,默认为false
spring.mail.test-connection=false

#### 2、163邮箱配置 ####
spring.mail.host=smtp.163.com
spring.mail.username=oy18778454639@163.com
spring.mail.password=密码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8

QQ邮箱授权码可以在邮箱设置-账户中找到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务下的

开启服务 - POP3/SMTP服务 根据提示进行开启和授权码的获取。

163邮箱smtp开启:

四、邮件发送实践

application.properties中添加邮件接收者,方便测试:

# 邮件接收者
spring.mail.to.user = 1456682842@qq.com

编写测试代码,完整代码如下:

package com.oycbest;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
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.test.context.junit4.SpringRunner;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * @author oyc
 * @Title: SpringBootMailTest
 * @ProjectName springboot-mail
 * @Description: 发送邮件单元测试
 * @date 2019/3/10 23:15
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMailTest {

        /**
         * 自动注入的Bean
         */
        @Autowired
        private JavaMailSender mailSender;

        /**
         * 读取配置文件中的邮件发送者
         */
        @Value("${spring.mail.username}")
        private String from;

        /**
         * 读取配置文件中的邮件接收者
         */
        @Value("${spring.mail.to.user}")
        private String toUser;

        @Test
        public void sendSimpleMail() {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(toUser);
            message.setSubject("邮件主题");
            message.setText("邮件详情~~~邮件详情~~~邮件详情~~~");
            mailSender.send(message);
        }

        @Test
        public void sendHtmlMessage() {
            MimeMessage message = null;
            message = mailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("Flyat") + "<" + from + ">");// 创建邮件发送者地址
                helper.setFrom(fromAddress);
                InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText("接收方") + "<" + toUser + ">");// 创建邮件发送者地址
                helper.setTo(toAddress);
                helper.setSubject("邮件标题-HTML");
                StringBuffer sb = new StringBuffer();
                sb.append("<h1>邮件详情</h1>")
                        .append("<p style='color:red;'>HTML字体颜色测试</p>");
                //第二个参数指定发送的是HTML格式
                helper.setText(sb.toString(), true);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            mailSender.send(message);
        }

        @Test
        public void sendAttachmentsMail() {
            MimeMessage message = null;
            try {
                message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("Flyat") + "<" + from + ">");// 创建邮件发送者地址
                helper.setFrom(fromAddress);
                InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText("接收方") + "<" + toUser + ">");// 创建邮件发送者地址
                helper.setTo(toAddress);
                helper.setSubject("带附件的邮件");
                StringBuffer sb = new StringBuffer();
                sb.append("<h1>带附件的邮件内容</h1>")
                        .append("<p style='color:red;'>HTML字体颜色测试</p>");
                //第二个参数指定发送的是HTML格式
                helper.setText(sb.toString(), true);
                //注意项目路径问题,自动补用项目路径
                FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/test.jpg"));
                helper.addAttachment("图片.jpg", file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mailSender.send(message);
        }

        @Test
        public void sendInlineMail() {
            MimeMessage message = null;
            try {
                message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("Flyat") + "<" + from + ">");// 创建邮件发送者地址
                helper.setFrom(fromAddress);
                InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText("接收方") + "<" + toUser + ">");// 创建邮件发送者地址
                helper.setTo(toAddress);
                helper.setSubject("带静态资源的邮件");
                //第二个参数指定发送的是HTML格式
                helper.setText("<html><body>带静态资源的邮件内容 图片:<img src='cid:test' /></body></html>", true);

                FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/test.jpg"));
                helper.addInline("test", file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mailSender.send(message);
        }

    }

将电脑中的test.jpg复制到resources/static/中用于测试附件和带静态文件的发送情况。

在运行各个单元测试即可完成邮件发送,具体发送功能需要根据业务系统进行调整。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值