// Step 1: Add the necessary dependencies to your Spring Boot project's build file, typically in your pom.xml for Maven.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
// Step 2: Configure your Gmail SMTP settings in your application.properties (or application.yml) file.
spring.mail.host=smtp.gmail.com
spring.mail.port=587
[email protected]
spring.mail.password=your-gmail-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
// Step 3: Create a service class to handle email sending. This class should use the JavaMailSender provided by Spring.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
javaMailSender.send(message);
}
}
// Step 4: Inject and use the EmailService in your controller or wherever you want to send emails.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private EmailService emailService;
@PostMapping("/send")
public void sendEmail(@RequestBody EmailRequest emailRequest) {
emailService.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getBody());
}
}
// Step 5: Create a simple DTO class to represent the email request.
public class EmailRequest {
private String to;
private String subject;
private String body;
// getters and setters
}