How send mail using spring
In Spring, you can send mail using the JavaMailSender
interface, which is part of the Spring Framework. Here's a step-by-step guide on how to send mail using Spring:
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 JavaMailSender
Create a configuration class that extends JavaMailSenderConfigurer
and configure the JavaMailSender
instance:
@Configuration
public class MailConfig extends JavaMailSenderConfigurerAdapter {
@Override
public void configureJavaMailSender(JMailSenderBuilder builder) {
builder
.setHost("your-smtp-host")
.setPort(587)
.setUsername("your-smtp-username")
.setPassword("your-smtp-password")
.setProtocol("smtp");
}
}
Step 3: Send mail
Create a service class that uses the JavaMailSender
instance to send mail:
@Service
public class MailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendMail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
javaMailSender.send(message);
}
}
Step 4: Use the MailService
Inject the MailService
instance into your controller or another service class and use it to send mail:
@RestController
public class MyController {
@Autowired
private MailService mailService;
@PostMapping("/send-mail")
public String sendMail(@RequestParam String to, @RequestParam String subject, @RequestParam String body) {
mailService.sendMail(to, subject, body);
return "Mail sent successfully!";
}
}
That's it! You can now send mail using Spring by calling the sendMail
method on the MailService
instance.
Note: Make sure to replace the placeholders (your-smtp-host
, your-smtp-username
, your-smtp-password
) with your actual SMTP server credentials.