栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot阿里、腾讯短信和邮件发送service封装

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot阿里、腾讯短信和邮件发送service封装

Springboot阿里、腾讯短信和邮件发送service封装
    • 依赖
    • 配置
    • 读取配置
    • 根据启用情况注入
    • 发送接口封装
    • 腾讯发送短信实现
    • 阿里云短信发送实现
    • 实际消息发送service
    • 测试短信发送
    • 测试 邮件发送
    • 完整代码下载

依赖

        
            com.aliyun
            aliyun-java-sdk-core
            4.0.3
        
        
        
            com.aliyun.oss
            aliyun-sdk-oss
            2.5.0
            
                
                    commons-lang
                    commons-lang
                
            
        
        
        
            com.aliyun
            aliyun-java-sdk-dysmsapi
            2.1.0
        

        
        
            com.github.qcloudsms
            qcloudsms
            1.0.5
        

        
        
            com.qcloud
            cos_api
            5.6.24
            
                
                    slf4j-log4j12
                    org.slf4j
                
            
        
        
        
            com.qiniu
            qiniu-java-sdk
            7.2.29
        

        
        
            org.springframework.boot
            spring-boot-starter-mail
            2.1.9.RELEASE
        
           
        
            cn.hutool
            hutool-all
            5.7.21
        
        
            org.projectlombok
            lombok
            true
        
配置
  #通知相关配置
notify:
  mail:
    # 邮件通知配置,邮箱一般用于接收业务通知例如收到新的订单,sendto 定义邮件接收者,通常为 管理 人员
    enable: false
    host: smtp.qq.com
    username: 121665820
    password: xxxxxxxxx
    sendfrom: 121665820@qq.com
    sendto: 121665820@qq.com
    port: 465
  # 短消息模版通知配置
  # 短信息用于通知 ,例如 短信通知,注意配置格式;template-name,template-templateId 请参考 NotifyType 枚举值
  sms:
    enable: false
    # 如果是腾讯云短信,则设置active的值tencent
    # 如果是阿里云短信,则设置active的值aliyun
    active: aliyun
    sign: zbwd
    template:
      - name: refund
        templateId: 159447
    aliyun:
      regionId: xxx
      accessKeyId: xxx
      accessKeySecret: xxx
    tencent:
      appid: 111111111
      appkey: xxxxxxxxxxxxxx
读取配置
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Data
@ConfigurationProperties(prefix = "notify")
public class NotifyProperties {

    private Sms sms;

    private Mail mail;

    @Data
    public static class Mail {
        private boolean enable;
        private String host;
        private String username;
        private String password;
        private String sendfrom;
        private String sendto;
        private Integer port;
    }

    @Data
    public static class Sms {
        private boolean enable;
        private String active;
        private String sign;
        private Aliyun aliyun;
        private Tencent tencent;
        private List> template = new ArrayList<>();

        @Data
        public static class Tencent {
            private int appid;
            private String appkey;

        }

        @Data
        public static class Aliyun {
            private String regionId;
            private String accessKeyId;
            private String accessKeySecret;


        }
    }

}
根据启用情况注入
import com.github.qcloudsms.SmsSingleSender;
import com.zbwd.plan.notify.AliyunSmsSender;
import com.zbwd.plan.notify.NotifyService;
import com.zbwd.plan.notify.TencentSmsSender;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;


@Configuration
@EnableConfigurationProperties(NotifyProperties.class)
public class NotifyAutoConfiguration {

    private final NotifyProperties properties;

    public NotifyAutoConfiguration(NotifyProperties properties) {
        this.properties = properties;
    }

    @Bean
    public NotifyService notifyService() {
        NotifyService notifyService = new NotifyService();

        NotifyProperties.Mail mailConfig = properties.getMail();
        if (mailConfig.isEnable()) {
            notifyService.setMailSender(mailSender());
            notifyService.setSendFrom(mailConfig.getSendfrom());
            notifyService.setSendTo(mailConfig.getSendto());
        }

        NotifyProperties.Sms smsConfig = properties.getSms();
        if (smsConfig.isEnable()) {
            if ("aliyun".equalsIgnoreCase(smsConfig.getActive())) {
                notifyService.setSmsSender(aliyunSmsSender());
            }
            if ("tencent".equalsIgnoreCase(smsConfig.getActive())) {
                notifyService.setSmsSender(tencentSmsSender());
            }
            notifyService.setSmsTemplate(smsConfig.getTemplate());
        }

        return notifyService;
    }

    public JavaMailSender mailSender() {
        NotifyProperties.Mail mailConfig = properties.getMail();
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(mailConfig.getHost());
        mailSender.setUsername(mailConfig.getUsername());
        mailSender.setPassword(mailConfig.getPassword());
        mailSender.setPort(mailConfig.getPort());
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", true);
        properties.put("mail.smtp.timeout", 5000);
        properties.put("mail.smtp.starttls.enable", true);
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //阿里云 必须加入配置 outlook配置又不需要 视情况而定.发送不成功多数是这里的配置问题
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.port", mailConfig.getPort());
        properties.put("debug", true);
        mailSender.setJavaMailProperties(properties);
        return mailSender;
    }

    
    public TencentSmsSender tencentSmsSender() {
        NotifyProperties.Sms smsConfig = properties.getSms();
        TencentSmsSender smsSender = new TencentSmsSender();
        NotifyProperties.Sms.Tencent tencent = smsConfig.getTencent();
        smsSender.setSender(new SmsSingleSender(tencent.getAppid(), tencent.getAppkey()));
        smsSender.setSign(smsConfig.getSign());
        return smsSender;
    }

    
    public AliyunSmsSender aliyunSmsSender() {
        NotifyProperties.Sms smsConfig = properties.getSms();
        AliyunSmsSender smsSender = new AliyunSmsSender();
        NotifyProperties.Sms.Aliyun aliyun = smsConfig.getAliyun();
        smsSender.setSign(smsConfig.getSign());
        smsSender.setRegionId(aliyun.getRegionId());
        smsSender.setAccessKeyId(aliyun.getAccessKeyId());
        smsSender.setAccessKeySecret(aliyun.getAccessKeySecret());
        return smsSender;
    }
}

发送接口封装

public interface SmsSender {

    
    @Deprecated
    SmsResult send(String phone, String content);


    
    SmsResult sendWithTemplate(String phoneNumbers, String templateId, String[] params);
}

腾讯发送短信实现
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.Data;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;


@Data
public class TencentSmsSender implements SmsSender {
    private final Log logger = LogFactory.getLog(TencentSmsSender.class);

    private SmsSingleSender sender;
    private String sign;


    @Override
    public SmsResult send(String phone, String content) {
        try {
            SmsSingleSenderResult result = sender.send(0, "86", phone, content, "", "");
            logger.debug(result);

            SmsResult smsResult = new SmsResult();
            smsResult.setSuccessful(true);
            smsResult.setResult(result);
            return smsResult;
        } catch (HTTPException | IOException e) {
            logger.error(e.getMessage(), e);
        }

        SmsResult smsResult = new SmsResult();
        smsResult.setSuccessful(false);
        return smsResult;
    }

    
    @Override
    public SmsResult sendWithTemplate(String phone, String templateId, String[] params) {
        try {
            SmsSingleSenderResult result = sender.sendWithParam("86", phone, Integer.parseInt(templateId), params, this.sign, "", "");
            logger.debug(result);

            SmsResult smsResult = new SmsResult();
            smsResult.setSuccessful(true);
            smsResult.setResult(result);
            return smsResult;
        } catch (HTTPException | IOException e) {
            logger.error(e.getMessage(), e);
        }

        SmsResult smsResult = new SmsResult();
        smsResult.setSuccessful(false);
        return smsResult;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }
}
阿里云短信发送实现
import cn.hutool.json.JSONUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.Data;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


@Data
public class AliyunSmsSender implements SmsSender {
    private final Log logger = LogFactory.getLog(AliyunSmsSender.class);

    private String regionId;
    private String accessKeyId;
    private String accessKeySecret;
    private String sign;

    private final String okCode = "OK";

    private static String DOMAIN = "dysmsapi.aliyuncs.com";

    private static String VERSION = "2017-05-25";

    private static String SEND_SMS_ACTION = "SendSms";

    private static String REGIN_ID_NAME = "RegionId";

    private static String PHONE_NUMBERS = "PhoneNumbers";

    private static String SIGN_NAME = "SignName";

    private static String TEMPLATE_CODE = "TemplateCode";

    private static String TEMPLATE_PARAM = "TemplateParam";


    @Override
    public SmsResult send(String phone, String content) {
        SmsResult smsResult = new SmsResult();
        smsResult.setSuccessful(false);
        return smsResult;
    }

    
    @Override
    public SmsResult sendWithTemplate(String phoneNumbers, String templateId, String[] params) {
        DefaultProfile profile = DefaultProfile.getProfile(this.regionId, this.accessKeyId, this.accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(DOMAIN);
        request.setVersion(VERSION);
        request.setAction(SEND_SMS_ACTION);
        request.putQueryParameter(REGIN_ID_NAME, this.regionId);
        request.putQueryParameter(PHONE_NUMBERS, phoneNumbers);
        request.putQueryParameter(SIGN_NAME, this.sign);
        request.putQueryParameter(TEMPLATE_CODE, templateId);
        String templateParam = params[0];
        request.putQueryParameter(TEMPLATE_PARAM, templateParam);


        SmsResult smsResult = new SmsResult();
        smsResult.setSuccessful(false);
        try {
            CommonResponse response = client.getCommonResponse(request);
            smsResult.setResult(response);
            String code = String.valueOf(JSONUtil.parseObj(response.getData()).get("Code"));
            if (response.getHttpResponse().isSuccess() && okCode.equals(code)) {
                smsResult.setSuccessful(true);
            } else {
                logger.error("短信发送失败:" + response.getData());
            }
        } catch (Exception e) {
            logger.error("短信发送失败:", e);
        }
        return smsResult;
    }


}
实际消息发送service
import lombok.Data;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.scheduling.annotation.Async;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Data
public class NotifyService {

    
    private String sendFrom;

    
    private String sendTo;

    
    private MailSender mailSender;

    
    private SmsSender smsSender;

    
    private List> smsTemplate = new ArrayList<>();

    
    public boolean isSmsEnable() {
        return smsSender != null;
    }

    
    public boolean isMailEnable() {
        return mailSender != null;
    }


    
    @Async
    public void notifySms(String phoneNumber, String message) {
        if (smsSender == null) {
            return;
        }

        smsSender.send(phoneNumber, message);
    }

    
    @Async
    public void notifySmsTemplate(String phoneNumbers, NotifyType notifyType, String[] params) {
        if (smsSender == null) {
            return;
        }

        String templateIdStr = getTemplateId(notifyType, smsTemplate);
        if (templateIdStr == null) {
            return;
        }

        smsSender.sendWithTemplate(phoneNumbers, templateIdStr, params);
    }

    
    public SmsResult notifySmsTemplateSync(String phoneNumbers, NotifyType notifyType, String[] params) {
        if (smsSender == null) {
            return null;
        }
        return smsSender.sendWithTemplate(phoneNumbers, getTemplateId(notifyType, smsTemplate), params);
    }


    
    @Async
    public void notifyMail(String subject, String content) {
        if (mailSender == null) {
            return;
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);
        message.setTo(sendTo);
        message.setSubject(subject);
        message.setText(content);
        mailSender.send(message);
    }

    
    private String getTemplateId(NotifyType notifyType, List> values) {
        for (Map item : values) {
            String notifyTypeStr = notifyType.getType();

            if (item.get("name").equalsIgnoreCase(notifyTypeStr)) {
                return item.get("templateId");
            }
        }
        return null;
    }


}
测试短信发送
import com.zbwd.plan.PlanApplication;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.concurrent.Executor;


@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class SmsTest {

    @Autowired
    private NotifyService notifyService;

    @Test
    public void testCaptcha() {
        String phone = "xxxxxxxxxxx";
        String[] params = new String[]{"123456"};

        notifyService.notifySmsTemplate(phone, NotifyType.REFUND, params);
    }

    @Test
    public void testPaySucceed() {
        String phone = "xxxxxxxxxxx";
        String[] params = new String[]{"123456"};

        notifyService.notifySmsTemplate(phone, NotifyType.REFUND, params);
    }

    @Test
    public void testShip() {
        String phone = "xxxxxxxxxxx";
        String[] params = new String[]{"123456"};

        notifyService.notifySmsTemplate(phone, NotifyType.REFUND, params);
    }

    @Test
    public void testRefund() {
        String phone = "xxxxxxxxxxx";
        String[] params = new String[]{"123456"};

        notifyService.notifySmsTemplate(phone, NotifyType.REFUND, params);
    }

    @Configuration
    @Import(PlanApplication.class)
    static class ContextConfiguration {
        @Bean
        @Primary
        public Executor executor() {
            return new SyncTaskExecutor();
        }
    }
}
测试 邮件发送
import com.zbwd.plan.PlanApplication;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.SyncTaskExecutor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.concurrent.Executor;


@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {

    @Autowired
    private NotifyService notifyService;

    @Test
    public void testMail() {
        notifyService.notifyMail("订单信息", "订单1111111已付款,请发货");
    }

    @Configuration
    @Import(PlanApplication.class)
    static class ContextConfiguration {
        @Bean
        @Primary
        public Executor executor() {
            return new SyncTaskExecutor();
        }
    }


}
完整代码下载

https://download.csdn.net/download/qq_35385687/85466642

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号