SpringBootを使用してメールを送信する方法は何ですか?
Spring Bootを使用してメールを送信するためには、次の手順が必要です。
- pom.xmlファイル
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- アプリケーションの設定ファイル
- アプリケーションの設定ファイル、application.yml
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
- 電子メールサービス
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("邮件发送成功!");
} catch (MailException e) {
System.out.println("邮件发送失败:" + e.getMessage());
}
}
}
- 電子メールサービス (Denshi Mēru Sābisu)
- メールを送信する
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", "测试邮件", "这是一封测试邮件。");
return "邮件发送成功!";
}
}
Spring Bootを使用してメールを送信するための基本ステップを示しました。必要に応じて、さらなる設定やカスタマイズを行うことができます。