前言
最近一个项目全是各种消息要推送,其中涉及到短信、邮箱、微信公众号和企业微信-微信群,整理一下各个方式通过java的接入方式
短信
使用的是腾讯云短信服务(用的腾讯云的sdk,其他平台肯定不能用这个)
依赖(pom)
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
<!-- 请到https://search.maven.org/search?q=tencentcloud-sdk-java查询所有版本,最新版本如下 -->
<version>3.1.980</version>
</dependency>
初始化
输出参数是腾讯云的secretId和secretKey
public static void init(String tencentSecretId,String tencentSecretKey) {
cred = new Credential(tencentSecretId, tencentSecretKey);
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
// 从3.0.96版本开始, 单独设置 HTTP 代理
// httpProfile.setProxyHost("真实代理ip");
// httpProfile.setProxyPort(真实代理端口);
httpProfile.setReqMethod("POST"); // get请求(默认为post请求)
httpProfile.setConnTimeout(60); // 请求连接超时时间,单位为秒(默认60秒)
httpProfile.setWriteTimeout(60); // 设置写入超时时间,单位为秒(默认0秒)
httpProfile.setReadTimeout(60);// 设置读取超时时间,单位为秒(默认0秒)
httpProfile.setEndpoint("sms.tencentcloudapi.com");
clientProfile = new ClientProfile();
clientProfile.setSignMethod("HmacSHA256"); // 指定签名算法(默认为TC3-HMAC-SHA256)
// 自3.1.80版本开始,SDK 支持打印日志。
clientProfile.setHttpProfile(httpProfile);
clientProfile.setDebug(true);
// 从3.1.16版本开始,支持设置公共参数 Language, 默认不传,选择(ZH_CN or EN_US)
clientProfile.setLanguage(Language.EN_US);
LOGGER.info("短信发送功能初始化完成");
}
发送消息
public static void sendWarnInfo(String phoneNumber,String[] templateParamSet) throws TencentCloudSDKException {
SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
* 您可以直接查询SDK源码确定接口有哪些属性可以设置
* 属性可能是基本类型,也可能引用了另一个数据结构
* 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
SendSmsRequest req = new SendSmsRequest();
/* 填充请求参数,这里request对象的成员变量即对应接口的入参
* 您可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
* 基本类型的设置:
* 帮助链接:
* 短信控制台: https://console.cloud.tencent.com/smsv2
* 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
/* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
// 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
String sdkAppId = "********";
req.setSmsSdkAppId(sdkAppId);
/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
// 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
String signName = "********"";
req.setSignName(signName);
/* 模板 ID: 必须填写已审核通过的模板 ID */
// 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
String templateId = "********"";
req.setTemplateId(templateId);
/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
req.setTemplateParamSet(templateParamSet);
/* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
* 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */
String[] phoneNumberSet = {phoneNumber};
req.setPhoneNumberSet(phoneNumberSet);
/* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
SendSmsResponse res = client.SendSms(req);
JSONObject resultObject=JSONObject.parseObject(SendSmsResponse.toJsonString(res));
resultObject=resultObject.getJSONArray("SendStatusSet").getJSONObject(0);
String code=resultObject.getString("Code");
if (!"Ok".equals(code)){
throw new TencentCloudSDKException(resultObject.getString("Message"));
}
}
输入参数是收件人的手机号和模版参数列表,其中代码中的sdkappId,signName和templateId也需要初始化。
邮箱
spring boot接入
依赖(pom)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
配置文件
spring:
mail:
host: ${MAIL_HOST}
username: ${MAIL_USERNAME}
password: ${MAIL_PASSWORD}
port: ${MAIL_PORT}
protocol: smtp
properties:
mail:
smtp:
ssl:
enable: true
starttls:
enable: true
default-encoding: UTF-8
调用类
直接@Autowired注入一个JavaMailSender对象就可以发送了
@Slf4j
@RequiredArgsConstructor
@Component
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String senderMail;
public void sendSimpleMail(String to, String subject, String text) {
Assert.hasText(to, "收件人邮箱不能为空");
Assert.hasText(subject, "邮件主题不能为空");
Assert.hasText(text, "邮件内容不能为空");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(senderMail); //邮件发送人
message.setTo(to); //邮件接收人
message.setSubject(subject); //邮件主题
message.setText(text); //邮件内容
mailSender.send(message);
log.info("The mail has been sent, to: {}, subject: {}, text: {}", to, subject, text);
}
}
普通Java接入
依赖(pom)
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
实现类
注意props.put(“mail.smtp.ssl.protocols”, “TLSv1.2”);这个先不加,如果遇到端口连不上的情况再加
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class MailUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(MailUtils.class);
private static String host;
private static String port;
private static String name;
private static String pwd;
private static Properties props;
public static void init(String hostToInit,String portToInit,String nameToInit,String pwdToInit){
host=hostToInit;
port=portToInit;
name=nameToInit;
pwd=pwdToInit;
// 连接邮件服务器的参数配置
props = new Properties();
// 设置用户的认证方式
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.ssl.protocols", "TLSv1.2");
props.put("mail.smtp.ssl.enable", "true");//
// 创建定义整个应用程序所需的环境信息的 Session 对象
LOGGER.info("邮箱功能初始化完成");
}
public static void send(String to,String subject,String text) throws Exception {
Session session = Session.getInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(name, pwd);
}
});
// 创建消息对象
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(name)); // 发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
message.setSubject(subject);
message.setText(text);
// 发送邮件
Transport.send(message);
LOGGER.info("邮件发送完成{}",message);
}
}
微信公众号和企业微信-微信群都有对应的API文档,直接进行API调用即可
企业微信-微信群:https://developer.work.weixin.qq.com/document/path/91039
公众号推送:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html