怎么使用SpringBoot發(fā)送郵件

小億
85
2024-01-30 11:29:07
欄目: 編程語言

使用Spring Boot發(fā)送郵件需要進(jìn)行以下步驟:

  1. 添加Spring Boot郵件依賴:在項(xiàng)目的pom.xml文件中添加Spring Boot的郵件依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  1. application.propertiesapplication.yml文件中配置郵件服務(wù)器的相關(guān)信息,例如:
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
  1. 創(chuàng)建一個(gè)郵件發(fā)送服務(wù)類,例如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;

@Service
public 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("郵件發(fā)送成功!");
        } catch (MailException e) {
            System.out.println("郵件發(fā)送失敗:" + e.getMessage());
        }
    }
}
  1. 在需要發(fā)送郵件的地方調(diào)用EmailServicesendEmail方法發(fā)送郵件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmailController {

    private EmailService emailService;

    @Autowired
    public EmailController(EmailService emailService) {
        this.emailService = emailService;
    }

    @GetMapping("/send-email")
    public String sendEmail() {
        emailService.sendEmail("recipient@example.com", "測(cè)試郵件", "這是一封測(cè)試郵件。");
        return "郵件發(fā)送成功!";
    }
}

以上是使用Spring Boot發(fā)送郵件的基本步驟。可以根據(jù)實(shí)際需求進(jìn)行更多的配置和定制。

0