需求介绍—发送邮件

首先要进行邮箱设置,要启用客户端SMTP服务。

而且SpringBoot也给了JavaMailSender发送邮件。

代码实现

首先你需要设置好邮箱,步骤百度一大堆,记住要配置一个授权码,是需要在后续进行配置的password

然后就是正式的来写了。

首先引入一个jar

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

  

然后在application.properties进行邮箱的配置

# MailProperties
spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=***
spring.mail.password=***
spring.mail.protocol=smtps
spring.mail.properties.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true

  

那么这个邮箱发送的话我们就建一个工具类MailClient,实现能够复用。

package com.nowcoder.community.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component; import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage; @Component
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class); @Autowired
private JavaMailSender mailSender; @Value("${spring.mail.username}")
private String from; /**
* @param to: 发送目标
* @param subject: 标题
* @param content: 内容
*/
public void sendMail(String to, String subject, String content) {
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
// 允许支持html文件,默认是文本
helper.setText(content, true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败:" + e.getMessage());
}
} }

  

那么我们写一个测试类测试一下MailTests

package com.nowcoder.community;

import com.nowcoder.community.util.MailClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context; @RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class MailTests { @Autowired
private MailClient mailClient; @Autowired
private TemplateEngine templateEngine; @Test
public void testTextMail() {
mailClient.sendMail("***@163.com", "TEST", "Welcome.");
} @Test
public void testHtmlMail() {
Context context = new Context();
context.setVariable("username", "sunday"); String content = templateEngine.process("/mail/demo", context);
System.out.println(content); mailClient.sendMail("***@163.com", "HTML", content);
} }

  

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件实例</title>
</head>
<body>
<p>欢迎你,<span style="color:red;" th:text="${username}"></span>!</p>
</body>
</html>

  

SpringBoot开发六-发送邮件的更多相关文章

  1. SpringBoot开发mockserver及生成swagger接口文档

    通过springboot开发mock server,包含get及post接口,用于练习接口自动化及jmeter很方便 当然,也为后面jenkins持续集成做基础(开发push代码后  → jenkin ...

  2. 基于SpringBoot开发一个Restful服务,实现增删改查功能

    前言 在去年的时候,在各种渠道中略微的了解了SpringBoot,在开发web项目的时候是如何的方便.快捷.但是当时并没有认真的去学习下,毕竟感觉自己在Struts和SpringMVC都用得不太熟练. ...

  3. SpringBoot(六):springboot热部署

    在j2ee项目开发中,热部署插件是JRebel.JRebel的使用为开发人员带来了极大的帮助,且挺高了开发便捷.而在SpringBoot开发生态环境中,SpringBoot热部署常用插件是:sprin ...

  4. SpringBoot开发案例之多任务并行+线程池处理

    前言 前几篇文章着重介绍了后端服务数据库和多线程并行处理优化,并示例了改造前后的伪代码逻辑.当然了,优化是无止境的,前人栽树后人乘凉.作为我们开发者来说,既然站在了巨人的肩膀上,就要写出更加优化的程序 ...

  5. SpringBoot开发案例从0到1构建分布式秒杀系统

    前言 ​最近,被推送了不少秒杀架构的文章,忙里偷闲自己也总结了一下互联网平台秒杀架构设计,当然也借鉴了不少同学的思路.俗话说,脱离案例讲架构都是耍流氓,最终使用SpringBoot模拟实现了部分秒杀场 ...

  6. 记一次SpringBoot 开发中所遇到的坑和解决方法

    记一次SpringBoot 开发中所遇到的坑和解决方法 mybatis返回Integer为0,自动转型出现空指针异常 当我们使用Integer去接受数据库中表的数据,如果返回的数据中为0,那么Inte ...

  7. 记账本微信小程序开发六

    记账本微信小程序开发六 我的界面 主界面

  8. SpringBoot系列四:SpringBoot开发(改变环境属性、读取资源文件、Bean 配置、模版渲染、profile 配置)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念 SpringBoot 开发深入 2.具体内容 在之前已经基本上了解了整个 SpringBoot 运行机制,但是也需要清 ...

  9. SpringBoot开发(改变环境属性、读取资源文件、Bean 配置、模版渲染、profile 配置)

    1.概念 SpringBoot 开发深入 2.具体内容 在之前已经基本上了解了整个 SpringBoot 运行机制,但是也需要清楚的认识到以下的问题,在实际的项目开发之中,尤其是 Java 的 MVC ...

随机推荐

  1. SpringMVC(7)格式化显示

    在SpringMVC(六)数据验证中我们介绍了如何验证提交的数据的正确性,当数据验证通过后就会被我们保存起来.保存的数据会用于以后的展示,这才是保存的价值.那么在展示的时候如何按照要求显示?(比如:小 ...

  2. 判断字符串是否为ip地址----python

    def isIp(ip_str): flag = True if '.' not in ip_str: return False if ip_str.count('.')!=3 : return Fa ...

  3. WPF使用Microsoft.VisualBasic创建单例模式引起的权限降低问题

    在进行WPF开发时,总是在找更加优雅去写单例模式的代码. 很多人都喜欢用Mutex,一个App.cs下很多的Mutex,我也喜欢用. 看完<WPF编程宝典>的第七章Applicaton类后 ...

  4. EL和JSTL核心技术

    一.EL EL表达式简化了jsp表达式方法,可以方便的访问各种数据并输出,依次访问pageContext.request.session和application作用域对象存储的数据,获取请求参数值,b ...

  5. TCP/IP 5层协议簇/协议栈

    TCP/IP 5层协议簇/协议栈 数据/PDU 应用层 PC.防火墙 数据段/段Fragment 传输层 防火墙 报文/包/IP包packet 网络层 路由器 帧Frame 数据链路层 交换机.网卡 ...

  6. 「BZOJ 2956」模积和

    「BZOJ 2956」模积和 令 \(l=\min(n,m)\).这个 \(i\neq j\) 非常不优雅,所以我们考虑分开计算,即: \[\begin{aligned} &\sum_{i=1 ...

  7. python根据正则表达式生成指定规律的网址

    import os def file_name(file_dir): for root, dirs, files in os.walk(file_dir): print(root) #当前目录路径 p ...

  8. SpringBoot总结之Spring Data Jpa

    一.Spring Data Jpa简介 JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate.TopLink等. Spring D ...

  9. 【洛谷 P2388 阶乘之乘】模拟

    分析 求因数5的个数 AC代码 #include<iostream> using namespace std; int main() { long long n,t,ans=0,s=0; ...

  10. UnitTest 用法

    功能 1.能组织多个用例去执行 2.提供丰富的断言方法 3.提供丰富的日志与测试结果 核心要素 1.TestCase 2.TestSuite 3.TextTestRunner 4.Fixture 用法 ...