How to send a mail to others using spring boot

To send an email using Spring Boot, you can use the JavaMailSender interface provided by Spring Framework. Here's a step-by-step guide:

Step 1: Add dependencies

In your pom.xml file (if you're using Maven) or build.gradle file (if you're using Gradle), add the following dependencies:

<!-- Maven -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

<!-- Gradle -->
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-mail'
}

Step 2: Configure email settings

Create a configuration file (e.g., application.properties or application.yml) and add the following settings:

spring:
  mail:
    host: your-email-host
    port: 587
    username: your-email-username
    password: your-email-password
    protocol: smtp
    default-encoding: UTF-8

Replace the placeholders with your actual email host, port, username, password, and protocol.

Step 3: Create a JavaMailSender instance

Create a Java class that will send the email. You can inject the JavaMailSender instance using the @Autowired annotation:

@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail(String to, String subject, String body) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(body);
        javaMailSender.send(mailMessage);
    }
}

Step 4: Send the email

Call the sendEmail method and pass the recipient's email address, subject, and body as arguments:

EmailService emailService = new EmailService();
emailService.sendEmail("[email protected]", "Hello from Spring Boot", "This is a test email.");

Step 5: Run the application

Start your Spring Boot application, and the email should be sent to the recipient.

Additional tips

That's it! With these steps, you should be able to send emails using Spring Boot.