发表于: 2020-07-19 23:43:08

1 1392


今天完成的事:

注册SendCloud,获取API_USER和API_KEY

查看帮助文档


下载SDK,解压后打开


填写相关信息就可以运行了

整合到任务七工程里面,

写了一个工具类

public class MailUtil {

@Autowired
   RedisTemplate redisTemplate;

   private String url;

   private String apiUser;

   private String apiKey;

   public MailUtil(String url, String apiUser, String apiKey) {
this.url = url;
       this.apiUser = apiUser;
       this.apiKey = apiKey;
   }

public boolean send(String address) throws Throwable {
MailAddressReceiver receiver = new MailAddressReceiver();
       receiver.addTo(address);
       MailBody body = new MailBody();
       // 设置 From
       body.setFrom("danjiayitask7@jnshu.com");
       // 设置 FromName
       body.setFromName("task7mail");
       // 设置 ReplyTo
       body.setReplyTo("danjiayitask7@jnshu.com");
       // 设置标题
       body.setSubject("验证码");

//        //生成随机验证码
       String code = UUID.randomUUID().toString().substring(0, 4);

       TextContent content = new TextContent();
       content.setContent_type(TextContent.ScContentType.html);
       content.setText("<html><p>您的验证码为:"+ code +"。请不要泄露出去</p></html>");

       SendCloudMail mail = new SendCloudMail();
       mail.setTo(receiver);
       mail.setBody(body);
       mail.setContent(content);

       SendCloud sc = SendCloudBuilder.build();
       ResponseData res = sc.sendMail(mail);
       System.out.println(res.getResult());
       System.out.println(res.getStatusCode());
       System.out.println(res.getMessage());
       System.out.println(res.getInfo());
       return res.getResult();
   }
}


<!--    Spring管理短信接口的bean对象-->
<bean id="sendMail" class="com.ptt.utils.MailUtil">
   <constructor-arg name="url" value="${URL}"></constructor-arg>
   <constructor-arg name="apiUser" value="${API_USER}"></constructor-arg>
   <constructor-arg name="apiKey" value="${API_KEY}"></constructor-arg>
</bean>


但是不会调用工具类,发送邮件失败。。。

@Controller
public class MailApiController {

@Autowired
   private MailUtil mailUtil;

   @Autowired
   private RedisTemplate<String,String> redisTemplate;

   @RequestMapping(value = "/send1",method = RequestMethod.POST)
public String code(@RequestParam(value = "address",required = false)String address, Model model) throws Throwable {

boolean isSend = mailUtil.send(address);

       //生成随机验证码
       String code = UUID.randomUUID().toString().substring(0, 4);

       TextContent content = new TextContent();
       content.setContent_type(TextContent.ScContentType.html);
       content.setText("<html><p>您的验证码为:"+ code +"。请不要泄露出去</p></html>");


       if (isSend){
redisTemplate.opsForValue().set(address,code,5000, TimeUnit.SECONDS);//5分钟过期
           //return phone + ":" + code + "发送成功!";

       }else {
model.addAttribute("error","请检查电话号码");
           return "register";
           //return "发送失败";
       }
return "register";

   }
}







返回列表 返回列表
评论

    分享到