在我们工作中,遇到很多系统都有关于注册发送短信或者邮箱验证这一个功能,同样的springboot也集成了这一块,那么我就简单的写一个demo测试一下,实际工作中会有很多权限控制,安全校验等,这个demo只是让我们知道springboot如何处理这一块的逻辑,方便我们入手。首先,看一下我的项目的结构图:
pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.csq.study</groupId>
<artifactId>springBoot-sendMail</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springboot mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- springboot web(MVC) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
</dependency>
<!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
配置文件:
#设置服务端口
server.port=8088
# Email配置属性
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.username=939782637@qq.com
#切记此处需要开启pom3的时候的验证码不是邮箱的密码
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
mail1.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>邮件格式</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p style="color: red;">这是一封测试邮件。</p>
</body>
</html>
mail2.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>测试邮件2</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p>这是一封含有附件的邮件,请查收!</p>
</body>
</html>
controller:
SendMailController
package com.csq.study.springboot.sendmail.controller;
import java.io.File;
import java.util.ArrayList;
import javax.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import com.csq.study.springboot.sendmail.service.SendMailService;
@RestController
public class SendMailController {
@Autowired
private SendMailService sendMailService;
@Autowired
private TemplateEngine templateEngine;
@GetMapping("/sendOne")
public String sendOne() throws MessagingException {
//简单邮件
//测试企业邮箱
sendMailService.sendTxtMail1("****.song@dilatoit.com","简单的文字介绍","我是一封简单的测试邮件");
return "sendOne发送成功";
}
@GetMapping("/sendTwo")
public String sendTwo() throws MessagingException {
//模板邮件
//测试163邮箱
Context ct = new Context();
ct.setVariable("username","我是托尼老师");
sendMailService.sendTxtMail2("m186056****6@163.com","附带标题内容等邮件",templateEngine.process("mail/mail",ct));
return "sendTwo发送成功";
}
@GetMapping("/sendThree")
public String sendThree() throws MessagingException {
//模板邮件,带附件
Context ct = new Context();
ct.setVariable("username","我是托尼老师(附带两首诗歌)");
ArrayList<File> files = new ArrayList<>();
files.add(new File("C:\\Users\\Administrator\\Desktop\\love.txt"));
sendMailService.sendTxtMail3("124346****@qq.com","带有附件的测试邮件",templateEngine.process("mail/mail2",ct),files);
return "sendThree发送成功";
}
}
SendMessageController
package com.csq.study.springboot.sendmail.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.csq.study.springboot.sendmail.util.SendMessageUtil;
/**
* 发送短信验证码
* @Description: TODO
* @ClassName: SendMessageController
* @author chengshengqing
* @see TODO
*/
@RestController
public class SendMessageController {
@GetMapping("/sendMessage")
public String testSendMessage(){
// SendMessageUtil.send("SMS账户","接口秘钥","目标号码","发送内容");
Integer resultCode = SendMessageUtil.send("愤怒的清哥哥","d41d8cd98f00b204****","176006****5","验证码:"+SendMessageUtil.getRandomCode(6));
return SendMessageUtil.getMessage(resultCode);
}
}
service接口以及实现类
package com.csq.study.springboot.sendmail.service;
import java.io.File;
import java.util.List;
import javax.mail.MessagingException;
/**
*
* @Description: TODO
* @ClassName: SendService
* @author chengshengqing
* @see TODO
*/
public interface SendMailService {
/**
* 简单的邮件发送
* @Title: sendTxtMail1
* @Description: TODO
* @param accept
* @param topic
* @param content
* @author chengshengqing
*/
public void sendTxtMail1(String accept, String topic, String content) ;
/**
* 附带标题等内容的邮件
* @Title: sendTxtMail2
* @Description: TODO
* @param accept
* @param topic
* @param content
* @throws MessagingException
* @author chengshengqing
*/
public void sendTxtMail2(String accept, String topic, String content) throws MessagingException;
/**
* 附带附件的邮件
* @Title: sendTxtMail3
* @Description: TODO
* @param accept
* @param topic
* @param content
* @param files
* @throws MessagingException
*/
public void sendTxtMail3(String accept, String topic, String content, List<File> files) throws MessagingException;
}
实现类
package com.csq.study.springboot.sendmail.service;
import java.io.File;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
/**
* 邮件的发送方
*/
@Value("${spring.mail.username}")
private String sendFrom;
/**
* 发送一个简单测试
*
* @param accept 接收方
* @param topic 邮件主题
* @param content 邮件内容
*/
@Override
public void sendTxtMail1(String accept, String topic, String content) {
// TODO Auto-generated method stub
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendFrom);
message.setTo(accept);
message.setSubject(topic);
message.setText(content);
javaMailSender.send(message);
}
/**
* 发送含有标题内容等的邮件
*
* @param accept 接收方
* @param topic 邮件主题
* @param content 邮件内容
* @throws MessagingException
*/
@Override
public void sendTxtMail2(String accept, String topic, String content) throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = javaMailSender.createMimeMessage();
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sendFrom);
helper.setTo(accept);
helper.setSubject(topic);
helper.setText(content, true);
javaMailSender.send(message);
}
/**
* 发送含有标题内容且可以带附件等的邮件
*
* @param accept 接收方
* @param topic 邮件主题
* @param content 邮件内容
* @param files 附带文件(可以多个文件)
* @throws MessagingException
*/
@Override
public void sendTxtMail3(String accept, String topic, String content, List<File> files)
throws MessagingException {
// TODO Auto-generated method stub
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper mh = new MimeMessageHelper(message, true);
mh.setFrom(sendFrom);
mh.setTo(accept);
mh.setSubject(topic);
mh.setText(content, true);
//添加附件
for(File file : files){
mh.addAttachment(file.getName(), new FileSystemResource(file));
}
javaMailSender.send(message);
}
}
工具类:
package com.csq.study.springboot.sendmail.util;
import java.util.Random;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class SendMessageUtil {
private static final String SMS_Url = "http://sms.webchinese.cn/web_api/";
/**
* @param Uid SMS用户id :愤怒的清哥哥
* @param Key 接口秘钥:SMS登录可查(非登录密码)
* @param sendPhoneNum 短信发送目标号码
* @param desc 短信内容
* @return Integer(1:成功码,其他失败,具体参见注释)
*/
public static Integer send(String Uid,String Key,String sendPhoneNum,String desc){
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(SMS_Url);
post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
//设置参数
NameValuePair[] data = {
new NameValuePair("Uid", Uid),
new NameValuePair("Key", Key),//秘钥
new NameValuePair("smsMob", sendPhoneNum),
new NameValuePair("smsText", desc)
};
post.setRequestBody(data);
try {
client.executeMethod(post);
} catch (Exception e) { e.printStackTrace(); }
Header[] headers = post.getResponseHeaders();
int statusCode = post.getStatusCode();
System.out.println("statusCode:" + statusCode);
for (Header h : headers) {
System.out.println(h.toString());
}
String result ="";
try {
result = new String(post.getResponseBodyAsString().getBytes("gbk"));
} catch (Exception e) { e.printStackTrace(); }
post.releaseConnection();
return Integer.parseInt(result);
}
/**
* -1 没有该用户账户
-2 接口密钥不正确 [查看密钥]不是账户登陆密码
-21 MD5接口密钥加密不正确
-3 短信数量不足
-11 该用户被禁用
-14 短信内容出现非法字符
-4 手机号格式不正确
-41 手机号码为空
-42 短信内容为空
-51 短信签名格式不正确接口签名格式为:【签名内容】
-6 IP限制
大于0 短信发送数量
以上作为补充
*/
public static String getMessage(Integer code){
String message;
if(code > 0 ) {
message = "SMS-f发送成功!短信量还有" + code + "条";
}else if(code == -1){
message = "SMS-没有该用户账户";
}else if(code == -2){
message = "SMS-接口密钥不正确";
}else if(code == -21){
message = "SMS-MD5接口密钥加密不正确";
}else if(code == -3){
message = "SMS-短信数量不足";
}else if(code == -11){
message = "SMS-该用户被禁用";
}else if(code == -14){
message = "SMS-短信内容出现非法字符";
}else if(code == -4){
message = "SMS-手机号格式不正确";
}else if(code == -41){
message = "SMS-手机号码为空";
}else if(code == -42){
message = "SMS-短信内容为空";
}else if(code == -51){
message = "SMS-短信签名格式不正确接口签名格式为:【签名内容】";
}else if(code == -6){
message = "SMS-IP限制";
}else{
message = "其他错误";
}
return message;
}
/**
* 随机生成6位验证码
* @return
*/
public static String getRandomCode(Integer code){
Random random = new Random();
StringBuffer result= new StringBuffer();
for (int i=0;i<code;i++){
result.append(random.nextInt(10));
}
return result.toString();
}
}
启动类
package com.csq.study.springboot.sendmail;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SendMailApplication {
public static void main(String[] args) {
SpringApplication.run(SendMailApplication.class, args);
}
}
启动项目,分别访问:http://localhost:8088/sendMessage 、http://localhost:8088/sendOne 、http://localhost:8088/sendTwo、http://localhost:8088/sendThree
有如下截图:
发送短信验证码成功截图:
发送企业邮箱成功截图
发送qq邮箱成功截图:
发送163邮箱成功截图:
说明:
发送短信我用的是 百度SMS短信通 我们可以进入官网:http://sms.webchinese.cn/ 然后出注册、申请账号 ,做这一步就是为了那免费的五条短信啊(免费的都好用
) ,获取到自己对应账号名称和密钥,后面需要用,然后就可以尝试发送短信了。本demo测试全部经过本人实际测试.有其它问题欢迎互相沟通。