【智能排班系统】SpringBoot整合邮件发送服务

🎯导读:本文档指导如何配置Spring Boot应用以通过QQ邮箱发送邮件。首先,用户需登录QQ邮箱并开启SMTP服务以获取授权码。随后,在Spring Boot项目中,通过application.yml配置文件指定SMTP服务器的地址、端口及认证信息等参数。此外,还介绍了如何创建一个配置类MailConfig来读取这些配置,并使用Lombok简化getter和setter方法。为了封装邮件发送所需的属性,文档还提供了EmailDto类。接着,定义了一个EmailService接口及其实现类EmailServiceImpl,后者利用Spring Mail API构建邮件消息并发送。最后,通过MailController控制器暴露RESTful API以便客户端触发邮件发送操作。

开通邮件发送服务

首先登录QQ邮箱,登录之后,点击设置

在这里插入图片描述

进入账户设置

在这里插入图片描述

拉到下面,开启SMTP服务。在开发过程中,当我们需要通过电子邮件发送消息时,通常会使用SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)服务。SMTP是一种用于发送电子邮件的标准协议,它定义了如何在发送方和接收方之间传输邮件。

要通过编程语言如Java、Python等实现邮件发送功能,我们需要连接到一个SMTP服务器。这通常意味着以下几点:

  1. SMTP服务器配置:需要知道SMTP服务器的地址、端口以及认证信息(用户名和密码)。这些信息通常由你的邮件服务提供商(如Gmail、Outlook等)提供。

  2. SMTP服务开启:邮件服务提供商需要确保SMTP服务可用,并且允许外部应用进行连接。有时,默认情况下SMTP服务可能被禁用或者某些安全设置可能会阻止外部访问。

  3. 安全设置:对于安全性较高的邮件账户,可能还需要启用一些特定的安全设置,比如设置应用专用密码等。

  4. 编程实现:在代码中使用相应的库或API来建立与SMTP服务器的连接,并通过这个连接发送邮件。

开启SMTP服务之后,需要生成授权码,后面SpringBoot需要使用这个授权码来连接SMTP服务器

在这里插入图片描述

配置文件

  • spring.mail.host: 指定SMTP服务器的主机名或IP地址,smtp.qq.com是腾讯QQ邮箱提供的SMTP服务器地址;
  • spring.mail.port: 指定SMTP服务器使用的端口号,QQ邮箱提供的端口号是587;
  • spring.mail.username: 发送邮件时使用的邮箱账号,用开通了SMTP服务的邮箱号码;
  • spring.mail.password: 该邮箱账号的密码或授权码。由于直接存储明文密码存在安全隐患,通常推荐使用应用授权码,这是一串由邮件服务商生成的专用密码,用于第三方应用的登录;
  • spring.mail.default-encoding: 设置默认的字符编码。这里设置为utf-8,这是目前最常用的编码格式;
  • spring.mail.properties.mail.smtp.connectiontimeout: 连接SMTP服务器的超时时间(毫秒)。设置为5000毫秒(即5秒),表示如果超过5秒未能建立连接,则会抛出异常;
  • spring.mail.properties.mail.smtp.timeout: SMTP连接的套接字超时时间(毫秒)。设置为3000毫秒(即3秒),表示在读取或写入数据时如果超过3秒没有响应,则会抛出异常;
  • spring.mail.properties.mail.smtp.writetimeout: 写入SMTP服务器的超时时间(毫秒)。设置为5000毫秒(即5秒),表示在向SMTP服务器写入数据时如果超过5秒没有完成,则会抛出异常。

一定要设置的只有username和password

在这里插入图片描述

# 邮箱发送服务配置
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=你的邮箱号码
spring.mail.password=授权码
spring.mail.default-encoding=utf-8
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=3000
spring.mail.properties.mail.smtp.writetimeout=5000

配置类

该配置类从配置文件中读取配置信息,并作为Bean注册到Spring容器中,方便后面进行使用

package com.dam.config.mail;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 读取yml配置文件里面的信息
 */
@Configuration
@ConfigurationProperties(prefix = "spring.mail")
@Data
public class MailConfig {
//    private String email;
    private String host;
    private String port;
    private String username;
    private String password;
}

Dto类

该类封装了邮件发生所需属性

package com.dam.model.dto.third_party;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public
class EmailDto {

    /**
     * 接收邮箱
     */
    private String to;

    /**
     * 主题
     */
    private String subject;

    /**
     * 内容
     */
    private String content;

}

Service

package com.dam.service;

import com.dam.model.dto.third_party.EmailDto;

public interface EmailService {

    /**
     * 发送邮件
     *
     * @param emailDto 邮箱列表
     */
    boolean send(EmailDto emailDto);

}

package com.dam.service.impl;

import com.dam.config.mail.MailConfig;
import com.dam.model.dto.third_party.EmailDto;
import com.dam.service.EmailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {
    @Autowired
    private MailConfig mailConfig;
    @Autowired
    private JavaMailSenderImpl mailSender;

    @Override
    public boolean send(EmailDto emailDto) {
        String fromEmail = mailConfig.getUsername();

        //定制纯文本邮件信息SimpleMailMessage
        SimpleMailMessage message = new SimpleMailMessage();
        try {
            //设置发件箱
            message.setFrom(fromEmail);
            //设置收件箱
            message.setTo(emailDto.getTo());
            //设置邮件主题
            message.setSubject(emailDto.getSubject());
            //设置邮件内容
            message.setText(emailDto.getContent());
            //调用Java封装好的发送方法
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            System.out.println("邮件发送失败,原因:" + e.getMessage());
            return false;
        }

    }
}

Controller

package com.dam.controller;

import com.dam.model.dto.third_party.EmailDto;
import com.dam.model.enums.ResultCodeEnum;
import com.dam.model.result.R;
import com.dam.service.EmailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
@RequestMapping("/thirdParty/mail")
@Api(tags = "邮件服务")
public class MailController {
    @Autowired
    private EmailService emailService;

    @ApiOperation(value = "发送邮件")
    @PostMapping("/send")
    public R send(@RequestBody EmailDto emailDto) {
        boolean isSuccess = emailService.send(emailDto);
        if (isSuccess) {
            return R.ok();
        } else {
            return R.error(ResultCodeEnum.FAIL);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello Dam

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值