Email in Java Spring

In this short article you will learn how to send an email in Java Spring. 

In order to send an email in Java Spring, you will need to use the Simple Mail Transfer Protocol (SMTP) protocol to send the email. Here is an example of how you can use the JavaMail API to send an email in Spring:

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

@Autowired
private JavaMailSender javaMailSender;

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

In this example, the sendEmail method takes in three parameters: the recipient’s email address, the subject of the email, and the body of the email. The JavaMailSender interface is used to send the email. This class uses the Simple Mail Transfer Protocol (SMTP) to send the email. You will need to configure the mail server properties in your application.properties or application.yml file. such as

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=yourusername
spring.mail.password=yourpassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
YAML

You will also need to add the JavaMail API dependency to your project. You can add the following to your build file (such as Maven or Gradle) to include the JavaMail API:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>
XML

Note that this example uses the SimpleMailMessage class to create the email message. You can also use other classes such as MimeMessage to send emails with attachments or HTML content.

Leave a Reply