一、短信
1、容联云短信
(1)官网:https://www.yuntongxun.com/member/main
(2)登录注册,进入控制台首页
(3)开发文档
https://doc.yuntongxun.com/p/5f0299f4a80948a1006e775e
(4)导入依赖
<dependency>
<groupId>com.cloopen</groupId>
<artifactId>java-sms-sdk</artifactId>
<version>1.0.3</version>
</dependency>
(5)调用示例测试
String serverIp = "app.cloopen.com";
String serverPort = "8883";
String accountSId = "你的accountSId";
String accountToken = "你的auth token";
String appId = "你的appId";
CCPRestSmsSDK sdk = new CCPRestSmsSDK();
sdk.init(serverIp, serverPort);
sdk.setAccount(accountSId, accountToken);
sdk.setAppId(appId);
sdk.setBodyType(BodyType.Type_JSON);
String to = "1352*******";
String templateId= "templateId";
String[] datas = {"变量1","变量2","变量3"};
HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
if("000000".equals(result.get("statusCode"))){
HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
Set<String> keySet = data.keySet();
for(String key:keySet){
Object object = data.get(key);
System.out.println(key +" = "+object);
}
}else{
System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
}
(6)正式调用环境
-
application.yml spring:
sms:
serverIp: app.cloopen.com
serverPort: 8883
accountSId: 你的accountSId
accountToken: 你的AUTH TOKEN
appId: 你的AppID
-
SmsTools import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Set;
@Data
@ConfigurationProperties(prefix = "spring.sms")
@Component
public class SmsTools {
private String serverIp;
private String serverPort;
private String accountSId;
private String accountToken;
private String appId;
public Boolean sendSms(String to,String templateId,String[] datas){
CCPRestSmsSDK sdk = new CCPRestSmsSDK();
sdk.init(serverIp, serverPort);
sdk.setAccount(accountSId, accountToken);
sdk.setAppId(appId);
sdk.setBodyType(BodyType.Type_JSON);
HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
if("000000".equals(result.get("statusCode"))){
HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
Set<String> keySet = data.keySet();
for(String key:keySet){
Object object = data.get(key);
System.out.println(key +" = "+object);
}
return true;
}else{
System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
return false;
}
}
}
-
调用测试 @Resource
private SmsTools smsTools;
@Test
void sendSms(){
Boolean sendSms = smsTools.sendSms("18886330640", "1", new String[]{"2345", "5"});
System.out.println(sendSms);
}
-
随机生成4位数验证码代码 public static int getRandomCode(){
int max=9999;
int min=1111;
Random random = new Random();
return random.nextInt(max)%(max-min+1) + min;
}
?
2、阿里云
参考这个链接:https://www.yuque.com/zhangshuaiyin/guli-mall/ktswm9
二、邮箱
QQ邮箱接入手册 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、MailTools
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "spring.mail")
@Data
public class MailTools {
@Resource
private JavaMailSenderImpl mailSender;
@Resource
private FreeMarkerConfigurer freeMarkerConfigurer;
private String subject;
private String from;
public void sendSimpleEmail(String mailContent,String...to){
this.sendSimpleEmail(subject,mailContent,to);
}
public void sendSimpleEmail(String subject,String mailContent,String...to){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setSubject(subject);
mailMessage.setTo(to);
mailMessage.setFrom(from);
mailMessage.setText(mailContent);
mailSender.send(mailMessage);
}
public void sendMimeMail(String subject,String mailContent,String...to) throws MessagingException {
this.sendMimeMail(subject,mailContent,null,to);
}
public void sendMimeMail(String mailContent,String...to) throws MessagingException {
this.sendMimeMail(this.subject,mailContent,null,to);
}
public void sendMimeMail(String subject, String mailContent, File[] files, String...to) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(mailContent,true);
if(files!=null && files.length>0){
for (File file:files){
if(file!=null){
String filename = file.getName();
helper.addAttachment(filename,file);
}
}
}
mailSender.send(mimeMessage);
}
public void sendTemplateMail(String subject, Map<String,Object> model, String templatePath, String...to) throws IOException, TemplateException, MessagingException {
Template mailTemplate = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath);
String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(mailTemplate,model);
this.sendMimeMail(subject,templateHtml,to);
}
}
3、application.yml
spring:
mail:
protocol: smtp
host: smtp.qq.com
port: 587
username: 40594@qq.com
password: 你的密码
from: 40594@qq.com
freemarker:
template-loader-path: classpath:/templates/mail/
suffix: .ftl
cache: false
charset: UTF-8
4、邮件模板account_active.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
.content{
text-indent: 2em;
color: green;
font-size: 20px;
}
.footer{
text-align: right;
}
</style>
</head>
<body>
<div id="content_box">
<h2>尊敬的${name},您好!</h2>
<p class="content">
欢迎成为XXX家族成员的一份子,您此次账户注册的激活码为:${code},该激活码用于注册用户激活账户使用,请妥善保管!
请于30分钟内输入激活!
</p>
<div class="footer">
<span>XXX</span></br>
<span>${datetime}</span>
</div>
</div>
</body>
</html>
5、测试调用
@Resource
private MailTools mailTools;
@Test
void sendMail() throws TemplateException, IOException, MessagingException {
String templateName = "account_active.ftl";
Map<String,Object> model = new HashMap<>();
Date date = new Date();
String strDateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
String datetime = sdf.format(date);
model.put("name","昵称");
model.put("code","6270");
model.put("datetime",datetime);
mailTools.sendTemplateMail("邮箱注册主题",model,templateName,"9605940@qq.com");
}
6、pom.xml
<build>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
</build>
三、第三方请求方式工具HttpUtils
HttpUtils.java地址:https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
pom.xml地址:https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.3.7.v20160115</version>
</dependency>
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
|