首先需要注册一个sendcloud账号,免费账号每天可以免费发10封邮件,发邮件需要API_USER,API_KEY,发信域名
mail-verifikations.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>邮箱验证</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>您的验证码为:<span th:text="${code}"></span> </div>
</body>
</html>
发送邮件
/**
* 发送邮箱验证码
* @return
*/
@Async
public void sendMailerifikation(String email){
try {
Map<String,Object> 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<String, Object> variables) {
final Context ctx = new Context();
if (!CollectionUtils.isEmpty(variables)) {
Iterator<Map.Entry<String, Object>> entries = variables.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Object> 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<String, String> params = new HashMap<String, String>();
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");
}