发送html模板短信

首先需要注册一个sendcloud账号,免费账号每天可以免费发10封邮件,发邮件需要API_USER,API_KEY,发信域名

mail-verifikations.html模板 



	
		邮箱验证
		
	
	
		
您的验证码为:

发送邮件 

    /**
     * 发送邮箱验证码
     * @return
     */
    @Async
    public void sendMailerifikation(String email){
        try {
            Map params = new HashMap<>();
            params.put("code", new Random().nextInt(9999));
            //mail-verifikations是写好的html模板名
            String html = inflatHtmlFrom("mail-verifikation",params);
            sendHtmlEmail(email,"邮箱验证",html);
        }catch (Exception e){
            logger.error("",e);
        }
    }

    /**
     * 渲染html内容
     * @param templateName 模板名
     * @param variables
     * @return
     */
    public String inflatHtmlFrom(String templateName, Map variables) {
        final Context ctx = new Context();
        if (!CollectionUtils.isEmpty(variables)) {
            Iterator> entries = variables.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = entries.next();
                ctx.setVariable(entry.getKey(), entry.getValue());
            }
        }
        String html = this.templateEngine.process(templateName, ctx);
        return html;
    }

    /**
     * 执行邮件发送
     * @param recipient
     * @param title
     * @param html
     * @return
     */
    public boolean sendHtmlEmail(String recipient,String title,String html) {
        Map params = new HashMap();
        params.put("html", html);
        params.put("apiUser", apiUser); //API_USER
        params.put("apiKey", apiKey); //API_KEY
        params.put("to", recipient);
        params.put("from", from); //from = API_USER@发信域名
        params.put("fromName", fromName); //发信人姓名
        params.put("subject", title); 

        String response = "error";
        try {
            response = HttpClientHelper.postFormData(SEND_CLOUD_URL, params);
            log.debug("send html email response={}",response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return !response.contains("error");
    }

 

你可能感兴趣的:(Java)