Spring mail example

Here is an example of using Spring Mail to send an email:

Step 1: Add dependencies

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

<!-- Maven -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-mail</artifactId>
    <version>5.2.5.RELEASE</version>
</dependency>

<!-- Gradle -->
dependencies {
    implementation 'org.springframework:spring-context:5.2.5.RELEASE'
    implementation 'org.springframework:spring-mail:5.2.5.RELEASE'
}

Step 2: Configure Spring Mail

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

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

Replace your-mail-server-host, your-mail-username, and your-mail-password with your actual mail server settings.

Step 3: Create a MailSender bean

Create a Java class that creates a MailSender bean:

@Configuration
public class MailConfig {

    @Bean
    public MailSender mailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("your-mail-server-host");
        mailSender.setPort(587);
        mailSender.setUsername("your-mail-username");
        mailSender.setPassword("your-mail-password");
        return mailSender;
    }
}

Step 4: Send an email

Create a Java class that sends an email using the MailSender bean:

@Service
public class EmailService {

    @Autowired
    private MailSender mailSender;

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

Step 5: Use the EmailService

Create a Java class that uses the EmailService to send an email:

@RestController
public class EmailController {

    @Autowired
    private EmailService emailService;

    @PostMapping("/send-email")
    public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String body) {
        emailService.sendEmail(to, subject, body);
        return "Email sent successfully!";
    }
}

Step 6: Test the email sending

Use a tool like Postman or cURL to send a request to the /send-email endpoint with the required parameters (e.g. to, subject, and body). The email should be sent successfully.

That's it! You've successfully configured and used Spring Mail to send an email.