📧

Sending Emails using Spring Boot

Jul 11, 2024

Lecture Notes: Sending Emails using Spring Boot

Introduction

  • Presented by: Suman from D-CODE
  • Topic: How to send emails using Spring Boot
  • Overview: Step-by-step tutorial to set up and send emails using Spring Boot

To-Do List

  1. Download Starter Package
    • Visit Spring Initializer (start.spring.io)
    • Project settings:
      • Task: Maven
      • Language: Java
      • Spring Boot Version: 3.1.1
      • Group Name: decode now
      • Artifact Name: mail demo
      • Packaging: jar
      • Java Version: 20
    • Add dependencies:
      • Spring Web: Handles HTTP requests and server creation
      • Lombok: Reduces boilerplate code
      • Java Mail Sender: For sending emails
    • Generate and download the package
  2. Add Necessary Configurations
    • Open application.properties file in src/main/resources
    • Add configurations for mail server: spring.mail.host=smtp.gmail.com spring.mail.port=587 [email protected] spring.mail.password=your_app_password spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true
    • Generate app password from Google account for use in application.properties
  3. Define Model for Mail Structure
    • Create a package named model
    • Create MailStructure class inside the model package: public class MailStructure { private String subject; private String message; // Lombok annotations for getters and setters @Getter @Setter }
  4. Create Controller Method
    • Create a package named controller
    • Create MailController class inside the controller package: @RestController @RequestMapping("/mail") public class MailController { @Autowired private MailService mailService; @PostMapping("/send/{mail}") public String sendMail(@PathVariable String mail, @RequestBody MailStructure mailStructure) { mailService.sendMail(mail, mailStructure); return "Mail sent successfully"; } }
  5. Create Service Method
    • Create a package named service
    • Create MailService class inside the service package: @Service public class MailService { @Autowired private JavaMailSender mailSender; @Value("${spring.mail.username}") private String fromMail; public void sendMail(String toMail, MailStructure mailStructure) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(fromMail); message.setTo(toMail); message.setSubject(mailStructure.getSubject()); message.setText(mailStructure.getMessage()); mailSender.send(message); } }

Sending a Mail

  • Test the application using Postman:
    • Method: POST
    • URL: http://localhost:8080/mail/send/{mailID}
    • Headers: Content-Type: application/json
    • Body: { "subject": "Testing", "message": "This is a test mail" }

Conclusion

  • Recap of steps taken to send an email using Spring Boot
  • Encouraged to like, comment, and subscribe for more tutorials