소스 검색

发送短信和邮箱

彭宇 2 년 전
부모
커밋
c7446fac73

+ 38 - 1
ruoyi-admin/pom.xml

@@ -79,7 +79,44 @@
             <artifactId>java-sdk-oauth</artifactId>
             <version>1.0.9</version>
         </dependency>
-
+        <!--极光-->
+        <dependency>
+            <groupId>cn.jpush.api</groupId>
+            <artifactId>jpush-client</artifactId>
+            <version>3.2.17</version>
+        </dependency>
+        <!--极光推送-->
+        <dependency>
+            <groupId>cn.jpush.api</groupId>
+            <artifactId>jiguang-common</artifactId>
+            <version>1.0.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-websocket</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>javax.websocket</groupId>
+            <artifactId>javax.websocket-api</artifactId>
+            <version>1.1</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+            <version>5.8.2</version>
+        </dependency>
+        <!--邮件-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
+        </dependency>
+        <!--word-->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-scratchpad</artifactId>
+            <version>3.17</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 127 - 0
ruoyi-admin/src/main/java/com/ruoyi/sendSMS/controller/MailTools.java

@@ -0,0 +1,127 @@
+package com.ruoyi.sendSMS.controller;
+
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import java.util.Date;
+import java.util.Properties;
+
+public class MailTools {
+
+    // 发件人的 邮箱 和 密码(替换为自己的邮箱和密码)
+    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性,给 SMTP 客户端设置了独立密码(有的邮箱称为“授权码”),
+    //     对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码(授权码)。
+    public static String myEmailAccount = "sys5923812@163.com";
+    public static String myEmailPassword = "sys200888";
+
+    public static String fromuser = "二道应急局";
+
+    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
+    // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
+    public static String myEmailSMTPHost = "smtp.163.com";
+
+//    // 收件人邮箱(替换为自己知道的有效邮箱)
+//    public static String receiveMailAccount = "sys5923812@126.com";
+
+    public static void main(String[] args) {
+        try {
+        String mail = "huapyluo@126.com";
+        String title = "隐患限期整改告知书";
+        String count = ("测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容测试附件内容");
+            sendMain(mail, title, count);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    public static void sendMain(String tomail, String title, String content) throws Exception {
+        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
+        Properties props = new Properties();                    // 参数配置
+        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议(JavaMail规范要求)
+        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
+        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
+
+        // PS: 某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性, 邮箱支持SSL连接, 也可以自己开启),
+        //     如果无法连接邮件服务器, 仔细查看控制台打印的 log, 如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误,
+        //     打开下面 /* ... */ 之间的注释代码, 开启 SSL 安全连接。
+        /*
+        // SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25, 可以不添加, 如果开启了 SSL 连接,
+        //                  需要改为对应邮箱的 SMTP 服务器的端口, 具体可查看对应邮箱服务的帮助,
+        //                  QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)
+        final String smtpPort = "465";
+        props.setProperty("mail.smtp.port", smtpPort);
+        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
+        props.setProperty("mail.smtp.socketFactory.fallback", "false");
+        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
+        */
+
+        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
+        Session session = Session.getDefaultInstance(props);
+        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log
+
+        // 3. 创建一封邮件
+        MimeMessage message = createMimeMessage(session, myEmailAccount, tomail, title, content);
+
+        // 4. 根据 Session 获取邮件传输对象
+        Transport transport = session.getTransport();
+
+        // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
+        //
+        //    PS_01: 成败的判断关键在此一句, 如果连接服务器失败, 都会在控制台输出相应失败原因的 log,
+        //           仔细查看失败原因, 有些邮箱服务器会返回错误码或查看错误类型的链接, 根据给出的错误
+        //           类型到对应邮件服务器的帮助网站上查看具体失败原因。
+        //
+        //    PS_02: 连接失败的原因通常为以下几点, 仔细检查代码:
+        //           (1) 邮箱没有开启 SMTP 服务;
+        //           (2) 邮箱密码错误, 例如某些邮箱开启了独立密码;
+        //           (3) 邮箱服务器要求必须要使用 SSL 安全连接;
+        //           (4) 请求过于频繁或其他原因, 被邮件服务器拒绝服务;
+        //           (5) 如果以上几点都确定无误, 到邮件服务器网站查找帮助。
+        //
+        //    PS_03: 仔细看log, 认真看log, 看懂log, 错误原因都在log已说明。
+        transport.connect(myEmailAccount, myEmailPassword);
+
+        // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
+        transport.sendMessage(message, message.getAllRecipients());
+
+        // 7. 关闭连接
+        transport.close();
+    }
+
+    /**
+     * 创建一封只包含文本的简单邮件
+     *
+     * @param session     和服务器交互的会话
+     * @param sendMail    发件人邮箱
+     * @param receiveMail 收件人邮箱
+     * @return
+     * @throws Exception
+     */
+    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String title, String content) throws Exception {
+        // 1. 创建一封邮件
+        MimeMessage message = new MimeMessage(session);
+
+        // 2. From: 发件人
+        message.setFrom(new InternetAddress(sendMail, fromuser, "UTF-8"));
+
+        // 3. To: 收件人(可以增加多个收件人、抄送、密送)
+        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));
+
+        // 4. Subject: 邮件主题
+        message.setSubject(title, "UTF-8");
+
+        // 5. Content: 邮件正文(可以使用html标签)
+        message.setContent(content, "text/html;charset=UTF-8");
+
+        // 6. 设置发件时间
+        message.setSentDate(new Date());
+
+        // 7. 保存设置
+        message.saveChanges();
+
+        return message;
+    }
+
+}

+ 35 - 0
ruoyi-admin/src/main/java/com/ruoyi/sendSMS/controller/SendMessageController.java

@@ -0,0 +1,35 @@
+package com.ruoyi.sendSMS.controller;
+
+import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.common.core.domain.R;
+import com.ruoyi.sendSMS.service.SendMessageService;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+
+@RestController
+@RequestMapping("/sendMessageController")
+public class SendMessageController {
+
+    @Resource
+    SendMessageService sendMessageService;
+
+    @GetMapping("/sendMessage")
+    public String sendMessage(@RequestParam(value = "phone") String phone, @RequestParam(value = "str") String str, @RequestParam(value = "SMSsignature") String SMSsignature) {
+        return sendMessageService.sendMessage(phone, str, SMSsignature);
+    }
+
+    @GetMapping("/sendEmail")
+    public AjaxResult sendEmail(@RequestParam(value = "mail") String mail, @RequestParam(value = "title") String title, @RequestParam(value = "count") String count) {
+        try {
+            MailTools.sendMain(mail, title, count);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return AjaxResult.success("操作成功!");
+    }
+}

+ 238 - 0
ruoyi-admin/src/main/java/com/ruoyi/sendSMS/controller/SendSms.java

@@ -0,0 +1,238 @@
+package com.ruoyi.sendSMS.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import javax.net.ssl.*;
+import java.io.*;
+import java.net.URL;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+// If the JDK version is earlier than 1.8, use the third-party library to provide the Base64 class.
+public class SendSms {
+    /**
+     * 设置不验证主机
+     */
+    private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
+        @Override
+        public boolean verify(String hostname, SSLSession session) {
+            return true;
+        }
+    };
+
+    public static void main(String[] args) throws Exception {
+        sendMessage("17612476018", "1231231321", "数字梨树");
+    }
+
+    public static Map<String, Object> buildRequestBody(String msisdn, String smsTemplateId,
+                                                       Map<String, String> paramValues, String accout, String passward, String SMSsignature) {
+        if (null == msisdn || null == smsTemplateId || null == accout || null == passward) {
+            System.out.println(
+                    "buildRequestBody(): mobiles, templateId or templateParas or account or password is null.");
+            return null;
+        }
+
+        Map<String, Object> map = new HashMap<String, Object>();
+        List<MtSmsMessage> requestLists = new ArrayList<MtSmsMessage>();
+        MtSmsMessage mtSmsMessage = new MtSmsMessage();
+        List<String> mobiles = new ArrayList<String>();
+        mobiles.add(msisdn);
+        mtSmsMessage.setMobiles(mobiles);
+        mtSmsMessage.setTemplateId(smsTemplateId);
+        mtSmsMessage.setTemplateParas(paramValues);
+        mtSmsMessage.setSignature("【"+SMSsignature+"】");
+        requestLists.add(mtSmsMessage);
+        map.put("account", accout);
+        map.put("password", passward);
+        map.put("requestLists", requestLists);
+        return map;
+    }
+
+    public static class MtSmsMessage {
+        List<String> mobiles;
+        String templateId;
+        Map<String, String> templateParas;
+        String signature;
+        String messageId;
+        String extCode;
+        List<NamedPatameter> extendInfos;
+
+        public List<String> getMobiles() {
+            return mobiles;
+        }
+
+        public void setMobiles(List<String> mobiles) {
+            this.mobiles = mobiles;
+        }
+
+        public String getTemplateId() {
+            return templateId;
+        }
+
+        public void setTemplateId(String templateId) {
+            this.templateId = templateId;
+        }
+
+        public Map<String, String> getTemplateParas() {
+            return templateParas;
+        }
+
+        public void setTemplateParas(Map<String, String> templateParas) {
+            this.templateParas = templateParas;
+        }
+
+        public String getSignature() {
+            return signature;
+        }
+
+        public void setSignature(String signature) {
+            this.signature = signature;
+        }
+
+        public String getMessageId() {
+            return messageId;
+        }
+
+        public void setMessageId(String messageId) {
+            this.messageId = messageId;
+        }
+
+        public String getExtCode() {
+            return extCode;
+        }
+
+        public void setExtCode(String extCode) {
+            this.extCode = extCode;
+        }
+
+        public List<NamedPatameter> getExtendInfos() {
+            return extendInfos;
+        }
+
+        public void setExtendInfos(List<NamedPatameter> extendInfos) {
+            this.extendInfos = extendInfos;
+        }
+    }
+
+    public class NamedPatameter {
+        String key;
+        String value;
+
+        public String getKey() {
+            return key;
+        }
+
+        public void setKey(String key) {
+            this.key = key;
+        }
+
+        public String getValue() {
+            return value;
+        }
+
+        public void setValue(String value) {
+            this.value = value;
+        }
+    }
+
+    static void trustAllHttpsCertificates() throws Exception {
+        TrustManager[] trustAllCerts = new TrustManager[]{
+                new X509TrustManager() {
+                    @Override
+                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+                        return;
+                    }
+
+
+                    @Override
+                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
+                        return;
+                    }
+
+
+                    @Override
+                    public X509Certificate[] getAcceptedIssuers() {
+                        return null;
+                    }
+                }
+        };
+        SSLContext sc = SSLContext.getInstance("SSL");
+        sc.init(null, trustAllCerts, null);
+        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+    }
+
+    public static String sendMessage(String phone, String message, String SMSsignature) {
+
+        String url = "https://139.9.32.119:18312/common/sms/sendTemplateMessage";
+
+        //【数字梨树】
+//        String smsTemplateId = "SMS_21010400002";
+        //【四平市林业局】
+        String smsTemplateId = "SMS_21030400002";
+        Map<String, String> templateParas = new HashMap<String, String>();
+        templateParas.put("dxnr", message);
+        String accout = "760395"; //实际账号
+        String passward = "Mds*e&sd2D"; //实际密码
+        // If the request body does not contain the signature name, set signature to null.
+        Map<String, Object> body = buildRequestBody(phone, smsTemplateId, templateParas, accout, passward,SMSsignature);
+        if (null == body || body.isEmpty()) {
+            System.out.println("body is null.");
+            return "body is null";
+        }
+        HttpsURLConnection connection = null;
+        InputStream is = null;
+        BufferedReader br = null;
+        try {
+            trustAllHttpsCertificates();
+            URL realUrl = new URL(url);
+            connection = (HttpsURLConnection) realUrl.openConnection();
+            connection.setHostnameVerifier(DO_NOT_VERIFY);
+            connection.setDoInput(true); // 设置可输入
+            connection.setDoOutput(true); // 设置该连接是可以输出的
+            connection.setRequestMethod("POST"); // 设置请求方式
+            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+            // connection.connect();
+            ObjectMapper objectMapper = new ObjectMapper();
+            PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
+            pw.write(objectMapper.writeValueAsString(body));
+            pw.flush();
+            pw.close();
+
+            br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
+            int status = connection.getResponseCode();
+            if (200 == status) { // 200
+                is = connection.getInputStream();
+            } else { // 400/401
+                is = connection.getErrorStream();
+            }
+            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
+            String line = null;
+            StringBuilder result = new StringBuilder();
+            while ((line = br.readLine()) != null) { // 读取数据
+                result.append(line + "\n");
+            }
+            connection.disconnect();
+            System.out.println(result.toString());
+            return result.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (null != is) {
+                    is.close();
+                }
+                if (null != br) {
+                    br.close();
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        return null;
+    }
+}

+ 7 - 0
ruoyi-admin/src/main/java/com/ruoyi/sendSMS/service/SendMessageService.java

@@ -0,0 +1,7 @@
+package com.ruoyi.sendSMS.service;
+
+public interface SendMessageService {
+
+    public String sendMessage(String phone, String str, String SMSsignature);
+
+}

+ 15 - 0
ruoyi-admin/src/main/java/com/ruoyi/sendSMS/service/impl/SendMessageServiceImpl.java

@@ -0,0 +1,15 @@
+package com.ruoyi.sendSMS.service.impl;
+
+import com.ruoyi.sendSMS.controller.SendSms;
+import com.ruoyi.sendSMS.service.SendMessageService;
+import org.springframework.stereotype.Service;
+
+@Service
+public class SendMessageServiceImpl implements SendMessageService {
+
+
+    public String sendMessage(String phone, String message, String SMSsignature) {
+
+        return  SendSms.sendMessage(phone, message,SMSsignature);
+    }
+}

+ 1 - 0
ruoyi-framework/src/main/java/com/ruoyi/framework/config/ShiroConfig.java

@@ -292,6 +292,7 @@ public class ShiroConfig
         filterChainDefinitionMap.put("/logout", "logout");
         // 不需要拦截的访问
         filterChainDefinitionMap.put("/hwMeeting/**", "anon");
+        filterChainDefinitionMap.put("/sendMessageController/**", "anon");
         filterChainDefinitionMap.put("/login", "anon,captchaValidate");
         // 注册相关
         filterChainDefinitionMap.put("/register", "anon,captchaValidate");