欢迎访问宙启技术站
智能推送

如何用springboot实现发送邮件功能

发布时间:2023-05-14 01:23:40

SpringBoot是基于Spring Framework的快速开发框架之一,提供了许多快速构建Web应用程序所需的功能。发送邮件功能在许多应用程序中都是必不可少的,SpringBoot也提供了方便快捷的发送邮件功能。本文将介绍如何使用SpringBoot实现发送邮件功能。

1. 添加Maven依赖

要使用SpringBoot发送邮件功能,需要在Maven中添加相关依赖。最简单的方式是使用SpringBoot的依赖管理工具进行添加。

在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 配置邮件服务器信息

SpringBoot发送邮件需要连接一个邮件服务器,需要在配置文件中配置相应的信息。在application.properties或application.yml文件中添加以下配置:

spring.mail.host=smtp.sina.com
spring.mail.port=465
spring.mail.username=xxxx@sina.com
spring.mail.password=xxxx
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
spring.mail.properties.mail.smtp.socketFactory.port=465

- spring.mail.host:邮件服务器主机名

- spring.mail.port:邮件服务器端口号

- spring.mail.username:发件人邮箱地址

- spring.mail.password:发件人邮箱密码

- spring.mail.properties.mail.smtp.auth:是否需要身份验证

- spring.mail.properties.mail.smtp.ssl.enable:是否使用SSL连接

- spring.mail.properties.mail.smtp.socketFactory.class:SSL连接的Socket工厂类

- spring.mail.properties.mail.smtp.socketFactory.fallback:是否允许Socket工厂类降级

- spring.mail.properties.mail.smtp.socketFactory.port:SSL连接的Socket端口号

3. 编写邮件服务

SpringBoot发送邮件的核心是邮件服务。可以在需要发送邮件的类中添加@Autowired注解,注入JavaMailSender对象。JavaMailSender对象是Spring提供的用于发送邮件的发送器。

@Service
public class MailService {
 
    @Autowired
    private JavaMailSender mailSender;
 
    public void sendMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("xxxx@sina.com");
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        mailSender.send(message);
    }
}

sendMail方法接收三个参数,分别是收件人地址、邮件主题和邮件内容。在方法内部,创建MimeMessageHelper对象时需要设置第二个参数为true,表示创建支持附件、html格式和图片的MimeMessage对象。在sendMail方法内使用mailSender的send方法发送邮件即可。

4. 发送邮件

在需要发送邮件的地方调用邮件服务即可。

@RestController
public class MailController {
 
    @Autowired
    private MailService mailService;
 
    @GetMapping("/send_mail")
    public String sendMail() throws MessagingException {
        mailService.sendMail("xxxx@qq.com", "SpringBoot发送邮件", "<h1>Hello, SpringBoot发送邮件</h1>");
        return "发送邮件成功";
    }
}

在控制器中注入MailService对象,调用其sendMail方法发送邮件。

5. 测试邮件服务

启动应用程序后,访问/send_mail接口,即可发送验证邮件。在收件人邮箱中查看是否收到了该邮件。

SpringBoot发送邮件功能的实现就是这么简单。通过简单的配置和编写代码,即可在应用程序中实现发送邮件功能。SpringBoot减少了很多繁琐的配置和编写代码的步骤,极大地提高了开发效率。