How to send a mail through gmail by using spring
To send an email using Gmail with Spring, you can use the JavaMail API. Here's a step-by-step guide:
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-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.6.2</version>
</dependency>
<!-- Gradle -->
dependencies {
implementation 'org.springframework:spring-context:5.2.5.RELEASE'
implementation 'org.springframework:spring-web:5.2.5.RELEASE'
implementation 'javax.mail:mail:1.6.2'
}
Step 2: Configure Gmail settings
Create a application.properties
file (or application.yml
if you prefer YAML) and add the following settings:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-gmail-username
spring.mail.password=your-gmail-password
spring.mail.protocol=smtp
spring.mail.auth=true
Replace your-gmail-username
and your-gmail-password
with your actual Gmail credentials.
Step 3: Create a JavaMailSender instance
Create a Java class that will send the email. You'll need to create a JavaMailSender
instance and configure it with your Gmail settings:
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class EmailSender {
private JavaMailSender javaMailSender;
public EmailSender() {
javaMailSender = MailSenderConfig.createMailSender();
}
public void sendEmail(String to, String subject, String body) {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body);
javaMailSender.send(message);
}
}
Step 4: Send the email
Create a method that sends the email using the EmailSender
class:
public void sendEmail() {
EmailSender emailSender = new EmailSender();
emailSender.sendEmail("[email protected]", "Hello from Spring!", "This is a test email.");
}
Step 5: Run the application
Run your Spring application, and the email should be sent using your Gmail account.
That's it! You've successfully sent an email using Gmail with Spring.
Note: Make sure to enable "Less secure app access" in your Gmail account settings to allow Spring to send emails using your Gmail account.