概述
java 发送短信/邮箱
数据库创建
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`username` varchar(50) NOT NULL COMMENT '用户名',
`nickname` varchar(50) NOT NULL COMMENT '昵称',
`password` varchar(50) NOT NULL COMMENT '密码',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
环境依赖
<!--thymeleaf引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mail 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker模版依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--邮箱信息发送结束-->
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql引擎-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Mybatis-Plus启动器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!--mybatis-plus自动代码生成-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--添加 模板引擎 依赖 代码生成器-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--knife4j的版本-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
<!--hutool-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
hutool
使用详情:https://www.hutool.cn/docs/#/
yml
spring:
application:
name: demo
# 数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo?userUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: root
# 格式化时区
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# jackson实体转json时 为NULL不参加序列化的汇总
default-property-inclusion: non_null
thymeleaf:
cache: false #关闭thymeleaf缓存
mail:
host: smtp.qq.com
username: 2138942661@qq.com
password: uxshpqjowejcefdj
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
# 配置端口号
server:
port: 8081
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
# 扫描 Mapper.xml
mapper-locations: classpath*:/mapper/*.xml
# 配置别名
type-aliases-package: com.bdqn.school.entity
# 逻辑删除
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
//逻辑删除
@TableLogic
框架构造
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 创建代码生成器对象
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(scanner("请输入你的项目路径") + "/src/main/java");
gc.setAuthor("cp");
//生成之后是否打开资源管理器
gc.setOpen(false);
//重新生成时是否覆盖文件
gc.setFileOverride(false);
//%s 为占位符
//mp生成service层代码,默认接口名称第一个字母是有I
gc.setServiceName("%sService");
//设置主键生成策略 自动增长
gc.setIdType(IdType.AUTO);
//设置Date的类型 只使用 java.util.date 代替
gc.setDateType(DateType.ONLY_DATE);
//开启实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
//使用mysql数据库
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("请输入模块名"));
pc.setParent("com.bdqn");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setMapper("mapper");
pc.setEntity("entity");
pc.setXml("mapper");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//设置哪些表需要自动生成
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//实体类名称驼峰命名
strategy.setNaming(NamingStrategy.underline_to_camel);
//列名名称驼峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//使用简化getter和setter
strategy.setEntityLombokModel(true);
//设置controller的api风格 使用RestController
strategy.setRestControllerStyle(true);
//驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("");
mpg.setStrategy(strategy);
mpg.execute();
}
}
config配置文件
Knife4jConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
//.title("swagger-bootstrap-ui-demo RESTful APIs")
.description("# swagger-bootstrap-ui-demo RESTful APIs")
.termsOfServiceUrl("http://www.xx.com/")
.contact("xx@qq.com")
.version("1.0")
.build())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.cp.demo.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
}
MyMetaObjectHandler
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
// 起始版本 3.3.0(推荐使用)
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
// 起始版本 3.3.0(推荐使用)
//在执行增加操作的时候,不仅仅要给createTime赋值,而且要给modifiedTime赋值
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
// 起始版本 3.3.0(推荐)
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
/**
* 乐观锁
* @return
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
//新增自动填充
@TableField(fill = FieldFill.INSERT)
//新增修改自动填充
@TableField(fill = FieldFill.INSERT_UPDATE)
//乐观锁
@Version
手机短信发送
搜索短信服务>进入短信控制台>快速学习>查看API Demo
邮箱发送
进入QQ邮箱>设置>帐户>开启服务 POP3/SMTP服务
配置application.yml文件:
spring:
mail:
host: smtp.qq.com
username: 发件的邮箱
password: 发件邮箱的授权码
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
EmailConfig 实体类
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @Description: 配置发送邮件
*/
@Data
@Component
public class EmailConfig {
/**
* 发件人
*/
@Value("${spring.mail.username}")
private String emailFrom;
}
EmailService 业务接口
import java.io.File;
public interface EmailService {
/**
* 发送文本/简单的邮件
* @param receiverName 接收人
* @param title 标题
* @param content 内容
*/
void sendStringEmail(String receiverName, String title, String content);
/**
* 发送大文件/附件的邮件
* @param receiverName
* @param title
* @param content
* @param file 文件
*/
void sendBigEmail(String receiverName, String title, String content, File file);
/**
* 发送模版邮件
* @param receiverName
* @param title
* @param information 模版参数名(html页面)
*/
void sendTemplateEmail(String receiverName, String title, String information);
}
EmailServiceImpl 实现类
import com.cp.demo.config.EmailConfig;
import com.cp.demo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
@Service
public class EmailServiceImpl implements EmailService {
@Autowired
private EmailConfig emailConfig;
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
@Autowired
private FreeMarkerConfigurer markerConfigurer;
//发送文本/简单的邮件
@Override
public void sendStringEmail(String receiverName, String title, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(emailConfig.getEmailFrom());
message.setTo(receiverName);
message.setSubject(title);
message.setText(content);
mailSender.send(message);
}
//发送大文件/附件的邮件
@Override
public void sendBigEmail(String receiverName, String title, String content, File file) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(emailConfig.getEmailFrom());
helper.setTo(receiverName);
helper.setSubject(title);
helper.setText(content);
FileSystemResource resource = new FileSystemResource(file);
helper.addAttachment("附件", resource);
}catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
}
//发送模版邮件
@Override
public void sendTemplateEmail(String receiverName, String title, String information) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(emailConfig.getEmailFrom());
helper.setTo(receiverName);
helper.setSubject(title);
//封装模版使用的数据
Map<String,Object> map = new HashMap<>();
map.put("username","明世隐");
//1.FreeMarker
//1-1 获取FreeMarker模版
//Template markertemplate = markerConfigurer.getConfiguration().getTemplate(information);
//1-2 将模版内容转为字符串类型并将参数传入
//String markertTtml = FreeMarkerTemplateUtils.processTemplateIntoString(markertemplate, map);
//1-3 将字符串作为邮件内容
//helper.setText(markertTtml,true);
//2.Thymeleaf
//2-1 获取Thymeleaf模版
Context context = new Context();
context.setVariable("username","瑶");
//2-2 将模版内容转为字符串类型并将参数传入
String thymeleafHtml = templateEngine.process("thymeleafTemplate", context);
helper.setText(thymeleafHtml,true);
}catch (Exception e){
e.printStackTrace();
}
mailSender.send(message);
}
}
邮箱发送模块
freemarkerTemplate.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>freemarkerTemplate</title>
</head>
<body>
${username}你好!<br>感谢您的使用,这是你的激活邮件,请点击下面的链接进行激活。<br>
</body>
</html>
thymeleafTemplate.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>thymeleafTemplate</title>
</head>
<body>
<span th:text="${username}"></span>,你好,感谢您的使用,这是你的激活邮件,请点击下面的链接进行激活。<br>
</body>
</html>
EmailController 控制器
import com.basic.hellorabbit.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
/**
* @Description: 邮件
*/
@Controller
public class EmailController {
@Autowired
private EmailService emailService;
@ResponseBody
@RequestMapping(value = "/stringEmaile",method = RequestMethod.GET)
public String sendStringEmail(){
emailService.sendStringEmail("mmmmmm@qq.com","你好","我发的你收到了吗?");
return "发送成功";
}
@ResponseBody
@RequestMapping(value = "/bigEmaile",method = RequestMethod.GET)
public String sendBigEmail(){
File file = new File("src/main/resources/static/zong.jpg");
emailService.sendBigEmail("mmmmmm@qq.com","你好,美图请查收","看我拍的咋样?",file);
return "发送成功";
}
@ResponseBody
@RequestMapping(value = "/templateEmail",method = RequestMethod.GET)
public String sendTemplateEmail(){
//emailService.sendTemplateEmail("mmmmmm@qq.com","激活邮件","freemarkerTemplate.html");
emailService.sendTemplateEmail("mmmmmm@qq.com","激活邮件","thymeleafTemplate.html");
return "发送成功";
}
}
Hutool
对称加密-SymmetricCrypto
String content = "test中文";
//随机生成密钥
byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
//构建
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
//加密
byte[] encrypt = aes.encrypt(content);
//解密
byte[] decrypt = aes.decrypt(encrypt);
//加密为16进制表示
String encryptHex = aes.encryptHex(content);
//解密为字符串
String decryptStr = aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
最后
以上就是优雅皮卡丘为你收集整理的基于SpringBoot 实现 Sms手机&Email邮箱发送java 发送短信/邮箱的全部内容,希望文章能够帮你解决基于SpringBoot 实现 Sms手机&Email邮箱发送java 发送短信/邮箱所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复