如何发送邮箱、手机短信以及设置

1.邮件发送

1.1 邮件服务设置

1.1.1 方法一:通过yaml文件配置

pamirs:
  email:
    smtp:
      smtpHost: smtp.exmail.qq.com
      smtpUser: xxx@xxx.com
      smtpPassword: xxxxxx
      smtpPort: 465
      smtpSecurity: SSL
      #邮件模块可后续后台自行添加
      templates:
        - name: 邮箱注册邮件
          title: '${code}是你此次注册的验证码'
          body: '<div>Hi ${realname},</div><div>你正在使用验证码注册。</div>'

1.1.2 方法二:工程启动加入初始化设置方法

/**
     * 初始化邮件模板
     */
    private void initEmailTemplate(){
        EmailSenderSource emailSenderSource = new EmailSenderSource();
        emailSenderSource.setName("邮件发送服务");
        emailSenderSource.setType(MessageEngineTypeEnum.EMAIL_SEND);
        //优先级
        emailSenderSource.setSequence(10);
        //发送账号
        emailSenderSource.setSmtpUser("xxx@xxx.com");
        //发送密码
        emailSenderSource.setSmtpPassword("xxxxxx");
        //发送服务器地址和端口
        emailSenderSource.setSmtpHost("smtp.exmail.qq.com");
        emailSenderSource.setSmtpPort(465);
        //" None: SMTP 对话用明文完成。" +
        //" TLS (STARTTLS): SMTP对话的开始时要求TLS 加密 (建议)" +
        //" SSL/TLS: SMTP对话通过专用端口用 SSL/TLS 加密 (默认是: 465)")
        emailSenderSource.setSmtpSecurity(EmailSendSecurityEnum.SSL);
        emailSenderSource.setActive(true);
        emailSenderSource.createOrUpdate();

        List<EmailTemplate> templates = new ArrayList<>();
        templates.add(new EmailTemplate().setName("重置密码邮件模板").setTitle("请确认你的密码修改请求").setBody("<div>Hi ${realname},</div><div>你正在使用验证码注册。</div>").setModel(PamirsUser.MODEL_MODEL).setEmailSenderSource(emailSenderSource));
        new EmailTemplate().createOrUpdateBatch(templates);
    }

1.2 调用邮件发送组件发送邮件

/**
     * 代码中使用消息组件发送Email
     */
    public void sendEmailByTemplate(){
        try {
            EmailSender emailSender = (EmailSender) MessageEngine.get(MessageEngineTypeEnum.EMAIL_SEND).get(null);;
            EmailTemplate template = new EmailTemplate().setName("邮件模版名称").queryOne();
            //标题:${name}
            //内容:${fieldInt}次数
            String sendTo = "xxx@xxx.com";
            String copyTo = "yyy@yyy.com";

            Map<String, Object> objectData = new HashMap<>();
            objectData.put("name","张三");
            objectData.put("fieldInt",999);
            Boolean aBoolean = emailSender.send(template, objectData, sendTo, copyTo);
            if (null == aBoolean || !aBoolean) {
                log.error("发送邮件失败");
            }
        } catch (Exception e) {
            log.error("发送确认邮件失败:,异常:{}", e);
        }
    }

2.发送短信

2.1 短信通道设置

2.1.1 方法一:通过yaml文件配置

pamirs:
  sms:
    aliyun:
      signatureMethod: HMAC-SHA1
      endpoint: https://dysmsapi.aliyuncs.com
      version: '2017-05-25'
      accessKeyId: xxxxxxxxxxxxx
      signatureVersion: '1.0'
      accessKeySecret: xxxxxxxxxxxx
      regionId: cn-hangzhou
      timeZone: GMT
      signName: xxxxxx

2.1.2 方法二:工程启动加入初始化设置方法

private void initSmsConfig() {
        SmsChannelConfig smsChannelConfig = new SmsChannelConfig();
        SmsChannelConfig smsChannelConfigs = smsChannelConfig.setChannel(SMSChannelEnum.ALIYUN)
                .setAccessKeyId("xxxxxx")
                .setSignName("xxxxxx")
                .queryOne();
        if (null == smsChannelConfigs) {
            smsChannelConfig.setChannel(SMSChannelEnum.ALIYUN);
            smsChannelConfig.setType(MessageEngineTypeEnum.SMS_SEND);
            smsChannelConfig.setSignatureMethod("HMAC-SHA1");
            smsChannelConfig.setEndpoint("https://dysmsapi.aliyuncs.com");
            smsChannelConfig.setVersion("2017-05-25");
            smsChannelConfig.setAccessKeyId("xxxxxx");
            smsChannelConfig.setAccessKeySecret("xxxxxx");
            smsChannelConfig.setSignatureVersion("1.0");
            smsChannelConfig.setRegionId("cn-hangzhou");
            smsChannelConfig.setTimeZone("GMT");
            smsChannelConfig.setSignName("xxxxxx");
            smsChannelConfig.setActive(Boolean.TRUE);
            smsChannelConfig.create();
        } else {
            smsChannelConfigs.updateById();
        }

        //初始化短信模版,需要先到阿里云申请短信模版
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setChannel(SMSChannelEnum.ALIYUN);
        smsTemplate.setTemplateType(SMSTemplateTypeEnum.SIGN_IN);
        smsTemplate.setTemplateCode("SMS_252710149");//阿里云短信模版的Code
        smsTemplate.setTemplateContent("验证码: ${code},您正在登录。10分钟内有效,请注意保密,请勿向他人泄露您的验证码。");//阿里云短信模版

        List<SmsTemplate> smsTemplates = new ArrayList<>();
        smsTemplates.add(smsTemplate);
        new SmsTemplate().createOrUpdateBatch(smsTemplates);
    }

2.2 调用邮件发送组件发送邮件

public void sendSms(){
        try {

            List<String> receivePhoneNumbers = new ArrayList<>();
            receivePhoneNumbers.add("13800000000");
            // 占位符处理
            Map<String, String> vars = new HashMap<>();
            vars.put("code", "123456");

            SmsTemplate smsTemplate = new SmsTemplate().setChannel(SMSChannelEnum.ALIYUN);
            smsTemplate.setTemplateType(SMSTemplateTypeEnum.SIGN_IN);
            smsTemplate.setTemplateCode("SMS_252710149").queryOne();
            SMSSender smsSender = (SMSSender) MessageEngine.get(MessageEngineTypeEnum.SMS_SEND).get(null);
            receivePhoneNumbers.stream().distinct().forEach(it -> {
                try {
                    if (!smsSender.smsSend(smsTemplate, it, vars)) {
                        //todo 错误处理
                    }
                } catch (Exception e) {
                    //todo 错误处理
                }
            });
        } catch (Exception e) {
            //todo 错误处理
        }
    }

Oinone社区 作者:数式-海波原创文章,如若转载,请注明出处:https://doc.oinone.top/backend/4346.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
数式-海波的头像数式-海波数式管理员
上一篇 2023年11月6日 pm4:48
下一篇 2023年11月7日 am11:35

相关推荐

  • 流程设计流程结束通知SPI接口

    1.实现SPI接口 import pro.shushi.pamirs.meta.common.spi.SPI; import pro.shushi.pamirs.meta.common.spi.factory.SpringServiceLoaderFactory; import pro.shushi.pamirs.workflow.app.api.entity.WorkflowContext; import pro.shushi.pamirs.workflow.app.api.model.WorkflowInstance; @SPI(factory = SpringServiceLoaderFactory.class) public interface WorkflowEndNoticeApi { void execute(WorkflowContext context, WorkflowInstance instance); } 自定义通知逻辑 /** * 自定义扩展流程结束时扩展点 */ @Order(999) @Component @SPI.Service public class MyWorkflowEndNoticeApi implements WorkflowEndNoticeApi { @Override public void execute(WorkflowContext context, WorkflowInstance instance) { Long dataBizId = instance.getDataBizId(); //todo自定义逻辑 } }

    2023年12月26日
    80800
  • RocketMQ消费者出现类似RemotingTimeoutException: invokeSync call timeout错误处理办法

    RocketMQ消费者在macOS中出现类似RemotingTimeoutException: invokeSync call timeout错误处理办法: 命令行中执行脚本 scutil –set HostName $(scutil –get LocalHostName)  重启应用

    2024年6月12日
    88800
  • Oinone连接外部数据源方案

    场景描述 在实际业务场景中,有是有这样的需求:链接外部数据进行数据的获取;通常的做法:1、【推荐】通过集成平台的数据连接器,链接外部数据源进行数据操作;2、项目代码中链接数据源,即通过程序代码操作外部数据源的数据; 本篇文章只介绍通过程序代码操作外部数据源的方式. 整体方案 Oinone管理外部数据源,即yml中配置外部数据源; 后端通过Mapper的方式进行数据操作(增/删/查/改); 调用Mapper接口的时候,指定到外部数据源; 详细步骤 1、数据源配置(application.yml), 与正常的数据源配置一样 out_ds_name(外部数据源别名): driverClassName: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # local环境配置调整 url: jdbc:mysql://ip(host):端口/数据库Schema?useSSL=false&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&autoReconnect=true&allowMultiQueries=true username: 用户名 password: 命名 initialSize: 5 maxActive: 200 minIdle: 5 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true asyncInit: true 2、外部数据源其他配置外部数据源限制创建表结构的执行,可以通过配置指定【不创建DB,不创建数据表】 persistence: global: auto-create-database: true auto-create-table: true ds: out_ds_name(外部数据源别名): # 不创建DB auto-create-database: false # 不创建数据表 auto-create-table: false 3、后端写Mapper SQL Mapper跟使用原生mybaits/mybaits-plus写法一样,无特殊限制; Mapper和SQL写到一起,或者分开两个文件都可以 4、Mapper被Service或者Action调用1)启动的Application中@MapperScan需要扫描到对应的包。2)调用是与普通bean一样(即调用方式跟传统的方式样),唯一的区别就是加上DsHintApi,即指定Mapper所使用的数据源。 @Autowired private ScheduleItemMapper scheduleItemMapper; public saveData(Object data) { ScheduleQuery scheduleQuery = new ScheduleQuery(); //scheduleQuery.setActionName(); try (DsHintApi dsHint = DsHintApi.use(“外部数据源名称”)) { List<ScheduleItem> scheduleItems = scheduleItemMapper.selectListForSerial(scheduleQuery); // 具体业务逻辑 } } 其他参考:如何自定义sql语句:https://doc.oinone.top/backend/4759.html

    2024年5月17日
    1.2K00
  • 如何把平台功能菜单加到项目中?

    概述 在使用Oinone低代码平台进行项目开发的过程中,会存在把平台默认提供的菜单加到自己的项目中。这篇文章介绍实现方式,以角色管理为例。 1. 低代码情况 即项目是通过后端代码初始化菜单的方式。 通常在 XXXMenu.java类通过@UxMenu注解的方式,代码片段如下: 此种情况与添加项目本地的菜单无区别,具体代码: @UxMenu(value = "账号管理", icon = "icon-yonghuguanli") class AccountManage { @UxMenu("用户管理") @UxRoute(value = CustomerCompanyUserProxy.MODEL_MODEL, title = "用户管理") class CompanyUserManage { } @UxMenu("角色管理") @UxRoute(value = AuthRole.MODEL_MODEL, module = AdminModule.MODULE_MODULE, title = "角色管理") class RoleManage { } @UxMenu("操作日志") @UxRoute(value = OperationLog.MODEL_MODEL, module = AdminModule.MODULE_MODULE/***菜单所挂载的模块**/) class OperateLog { } } 2. 无代码情况 在界面设计器中,新建菜单–>选择绑定已有页面,进行发布即可。

    2024年4月19日
    1.4K00
  • Oinone请求路由源码分析

    通过源码分析,从页面发起请求,如果通过graphQL传输到具体action的链路,并且在这之间做了哪些隐式处理分析源码版本5.1.x 请求流程大致如下: 拦截所有指定的请求 组装成graphQL请求信息 调用graphQL执行 通过hook拦截先执行 RsqlDecodeHook:rsql解密 UserHook: 获取用户信息, 通过cookies获取用户ID,再查表获取用户信息,放到本地Local线程里 RoleHook: 角色Hook FunctionPermissionHook: 函数权限Hook ,跳过权限拦截的实现放在这一层,对应的配置 pamirs: auth: fun-filter: – namespace: user.PamirsUserTransient fun: login #登录 – namespace: top.PetShop fun: action DataPermissionHook: 数据权限hook PlaceHolderHook:占位符转化替换hook RsqlParseHook: 解释Rsql hook SingletonModelUpdateHookBefore 执行post具体内容 通过hook拦截后执行 QueryPageHook4TreeAfter: 树形Parent查询优化 FieldPermissionHook: 字段权限Hook UserQueryPageHookAfter UserQueryOneHookAfter 封装执行结果信息返回 时序图 核心源码解析 拦截所有指定的请求 /pamirs/模块名RequestController @RequestMapping( value = "/pamirs/{moduleName:^[a-zA-Z][a-zA-Z0-9_]+[a-zA-Z0-9]$}", method = RequestMethod.POST ) public String pamirsPost(@PathVariable("moduleName") String moduleName, @RequestBody PamirsClientRequestParam gql, HttpServletRequest request, HttpServletResponse response) { } DefaultRequestExecutor 构建graph请求信息,并调用graph请求 () -> execute(GraphQL::execute, param), param private <T> T execute(BiFunction<GraphQL, ExecutionInput, T> executor, PamirsRequestParam param) { // 获取GraphQL请求信息,包含grapsh schema GraphQL graphQL = buildGraphQL(param); … ExecutionInput executionInput = ExecutionInput.newExecutionInput() .query(param.getQuery()) .variables(param.getVariables().getVariables()) .dataLoaderRegistry(Spider.getDefaultExtension(DataLoaderRegistryApi.class).dataLoader()) .build(); … // 调用 GraphQL的方法execute 执行 T result = executor.apply(graphQL, executionInput); … return result; } QueryAndMutationBinder 绑定graphQL读取写入操作 public static DataFetcher<?> dataFetcher(Function function, ModelConfig modelConfig) { if (isAsync()) { if (FunctionTypeEnum.QUERY.in(function.getType())) { return AsyncDataFetcher.async(dataFetchingEnvironment -> dataFetcherAction(function, modelConfig, dataFetchingEnvironment), ExecutorServiceApi.getExecutorService()); } else { return dataFetchingEnvironment -> dataFetcherAction(function, modelConfig, dataFetchingEnvironment); } } else { return dataFetchingEnvironment -> dataFetcherAction(function, modelConfig, dataFetchingEnvironment); } } private static Object dataFetcherAction(Function function, ModelConfig modelConfig, DataFetchingEnvironment environment) { try { SessionExtendUtils.tagMainRequest(); // 使用共享的请求和响应对象 return Spider.getDefaultExtension(ActionBinderApi.class) .action(modelConfig,…

    2024年8月21日
    4.0K02

Leave a Reply

登录后才能评论