怎么使用SpringBoot发送邮件

   2024-11-08 4080
核心提示:使用Spring Boot发送邮件需要进行以下步骤:添加Spring Boot邮件依赖:在项目的pom.xml文件中添加Spring Boot的邮件依赖:depend

使用Spring Boot发送邮件需要进行以下步骤:

添加Spring Boot邮件依赖:在项目的pom.xml文件中添加Spring Boot的邮件依赖:
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-mail</artifactId></dependency>
application.propertiesapplication.yml文件中配置邮件服务器的相关信息,例如:
spring.mail.host=smtp.example.comspring.mail.port=587spring.mail.username=your-email@example.comspring.mail.password=your-email-passwordspring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=true
创建一个邮件发送服务类,例如EmailService
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.MailException;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.stereotype.Service;@Servicepublic class EmailService {    private JavaMailSender javaMailSender;    @Autowired    public EmailService(JavaMailSender javaMailSender) {        this.javaMailSender = javaMailSender;    }    public void sendEmail(String to, String subject, String text) {        try {            SimpleMailMessage message = new SimpleMailMessage();            message.setTo(to);            message.setSubject(subject);            message.setText(text);            javaMailSender.send(message);            System.out.println("邮件发送成功!");        } catch (MailException e) {            System.out.println("邮件发送失败:" + e.getMessage());        }    }}
在需要发送邮件的地方调用EmailServicesendEmail方法发送邮件:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class EmailController {    private EmailService emailService;    @Autowired    public EmailController(EmailService emailService) {        this.emailService = emailService;    }    @GetMapping("/send-email")    public String sendEmail() {        emailService.sendEmail("recipient@example.com", "测试邮件", "这是一封测试邮件。");        return "邮件发送成功!";    }}

以上是使用Spring Boot发送邮件的基本步骤。可以根据实际需求进行更多的配置和定制。

 
举报打赏
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行

网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策网站留言    |  赣ICP备2021007278号