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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中集成邮箱验证码功能,你可以按照以下步骤进行操作: 1. 在项目的pom.xml文件中添加mail模块的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 这样就可以使用Spring Boot提供的邮件功能了。\[1\] 2. 在配置文件(application.properties或application.yml)中填写相关的邮箱配置,例如使用163邮箱: ```properties # Mail spring.mail.host=smtp.163.com spring.mail.username=your-email@163.com spring.mail.password=your-password spring.mail.default-encoding=UTF-8 mail.from=your-email@163.com ``` 其中,`spring.mail.host`是SMTP服务器地址,`spring.mail.username`和`mail.from`是你的邮箱地址,`spring.mail.password`是你的邮箱授权码(不是邮箱密码)。你需要在相关邮箱设置中开启SMTP服务,并获取授权码。\[2\]\[3\] 3. 在你的代码中使用JavaMailSender发送邮件,可以通过注入`JavaMailSender`对象来实现: ```java @Autowired private JavaMailSender javaMailSender; public void sendVerificationCode(String email, String code) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email); message.setSubject("验证码"); message.setText("您的验证码是:" + code); javaMailSender.send(message); } ``` 以上代码示例中,`sendVerificationCode`方法用于发送验证码邮件,其中`email`是收件人邮箱地址,`code`是验证码内容。你可以根据实际需求自定义邮件的主题和内容。 这样,你就可以在Spring Boot中集成邮箱验证码功能了。记得替换相关配置为你自己的邮箱信息。 #### 引用[.reference_title] - *1* *2* *3* [Spring Boot 整合163或者qq邮箱发送验证码](https://blog.csdn.net/hghjgkjn/article/details/125952509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值