發送短信驗證碼
阿里云發送驗證碼
public Integer sendTelCode(String tel) {String url = "https://dfsns.market.alicloudapi.com/data/send_sms";String appcode = "a3198282fbdf443d97aa9f3cfbe1232e";int code = RandomUtil.randomInt(1000,10000);emailMap.put(tel,code);String result = HttpRequest.post(url).header("Authorization","APPCODE "+appcode).body("content=code:"+code+"&template_id=TPL_0000&phone_number="+tel).execute().body();JSONObject object = JSONUtil.parseObj(result);if (!object.get("status").equals("OK")){log.error("發送驗證碼錯誤:{}",object.get("reason"));throw new BizException(404,"發送驗證碼錯誤");}return 0;}
發送郵件功能
pom.xml 引入hutool和javax.mail
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version></dependency>
2.書寫代碼
首先你的郵箱要開啟SMTP服務.
書寫代碼:
public Integer sendCode(String email) {//MailAccount 郵件賬戶對象MailAccount account = new MailAccount();account.setHost("smtp.aliyun.com");//阿里云的郵箱服務器地址account.setPort(25); //郵件服務器端口,默認25account.setAuth(true);account.setUser("3813@aliyun.com");account.setFrom("3813@aliyun.com");account.setPass("這里是自己的郵箱密碼");int code = RandomUtil.randomInt(1000,10000);//RandomUtil:隨機工具類emailMap.put(email,code);//MailUtil:郵件的工具類MailUtil.send(account,email,"WMS驗證碼","驗證碼:"+code,false);return 0;}