天天看点

Springboot集成邮箱服务

做项目时集成一个简易的邮箱服务,用的是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>