做項目時內建一個簡易的郵箱服務,用的是springboot自帶的mail:
1.依賴導入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.yaml檔案配置:
由于阿裡雲伺服器預設禁止使用25端口,在這裡我們開放465端口,使用阿裡雲伺服器465端口時要配置ssl協定加密,具體配置如下。
spring:
mail:
host: smtp.163.com
username: *******
password: *******(授權碼,向郵箱申請服務後會給)
from: ******
nickname: *******
default-encoding: utf-8
port: 465
protocol: smtp
properties:
mail:
smtp:
ssl:
enable: true
trust: smtp.163.com
socketFactory:
class: javax.net.ssl.SSLSocketFactory
port: 465
auth: true
starttls:
enable: false
required: true
3.具體實作類編寫(service層):
import edu.whut.mall.user.exception.MtonsException;
import edu.whut.mall.user.service.IMailService;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import java.util.Map;
@Slf4j
@Service
public class MailServiceImpl implements MailService {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.from}")
private String from;
@Value("${spring.mail.nickname}")
private String nickname;
@Override
public void sendTemplateEmail(String to, String title, String template, Map<String, Object> content) {
String text = render(template, content);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(nickname+'<'+from+'>');
message.setTo(to);
message.setSubject(title);
message.setText(text);
mailSender.send(message);
log.info("email: {} send success", to);
}
private String render(String templateName, Map<String, Object> model) {
try {
Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, "UTF-8");
t.setOutputEncoding("UTF-8");
return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
} catch (Exception e) {
throw new MtonsException(e.getMessage(), e);
}
}
}
4.controller層:
import edu.whut.mall.common.api.ResponseMap;
import edu.whut.mall.user.service.IMailService;
import edu.whut.mall.user.service.ISecurityCodeService;
import edu.whut.mall.user.service.IUserService;
import edu.whut.mall.user.vo.UserVo;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
/**
* @Author smq
* @Date 2021/8/19 9:28
* @Uint d9lab
* @Description:
*/
@RequiredArgsConstructor
@RequestMapping("/email")
@RestController
@Api(value = "郵箱驗證碼子產品", tags = {"郵箱驗證碼子產品"})
public class EmailController {
private final ISecurityCodeService securityCodeService;
private final IMailService mailService;
private final IUserService userService;
private static final String EMAIL_TITLE = "*********************";
private static final String TITLE = "******************";
@GetMapping("/send_code")
public Map<String, Object> sendCode(String email) {
ResponseMap map = ResponseMap.getInstance();
Assert.hasLength(email, "請輸入郵箱位址");
UserVo exist = userService.getByEmail(email);
Assert.isNull(exist, "該郵箱已被使用");
//String code = securityCodeService.generateCode(email);
//Map<String, Object> context = new HashMap<>();
//context.put("code", code);
// 這裡context即為向郵箱發送的内容,我原本項目寫的是郵件驗證碼,可以随意更改
String title = MessageFormat.format(EMAIL_TITLE, TITLE);
mailService.sendTemplateEmail(email, title, "email_code.ftl", context);
return map.putSuccess("郵件發送成功");
}
}
5.email_code.ftl,模闆檔案編寫:
其中的code與controller中傳入的code對應,即為發送的郵件内容。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>驗證郵件</title>
<style type="text/css">
body {
font-size:16px;
}
.main {
max-width: 780px;
margin: 0 auto;
}
.text {
color: #8c92a4;
}
</style>
</head>
<body>
<div class="main">
<p>驗證碼: <b class="code">${code}</b></p>
<p class="text">該驗證碼将會在30分鐘後失效</p>
<p class="text">請勿向任何人洩露您收到的驗證碼</p>
</div>
</body>
</html>