SpringBootでメール送信機能を実装する方法は何ですか?
SpringBootでメール送信機能を実装するには、Springのメール送信モジュールであるspring-boot-starter-mailを使用し、application.propertiesファイルでメール送信に関する情報を設定します。
最初に、pom.xmlファイルにspring-boot-starter-mailの依存関係を追加します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
その後、application.propertiesファイルにメール送信に関する情報を設定します。例えば:
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
次は、Javaコードでメール送信サービスクラスを記述します。以下はサンプルコードです。
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
最後に、メールを送信する必要がある場合は、EmailServiceクラスのsendEmailメソッドを呼び出すだけでメールを送信できます。例:
@Autowired
private EmailService emailService;
emailService.sendEmail("recipient@example.com", "Test Email", "This is a test email from SpringBoot.");
SpringBootでメール送信機能を実現できます。