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
- Make sure to replace the placeholders in the configuration file with your actual email settings.
- You can customize the email settings by creating a custom
JavaMailSender
instance or by using a third-party library like Apache Commons Email. - You can also use the
MimeMessagePreparator
interface to send more complex emails with attachments or HTML content.
That's it! With these steps, you should be able to send emails using Spring Boot.