JavaMail Overview
Imagine you own a business and need to send order confirmations, password reset links, or promotional offers to your customers. You could hire a messenger to deliver each message manually, but that would be slow and expensive. JavaMail is like having an automated postal service built into your application.
What is JavaMail?
JavaMail is an API that allows Java applications to send and receive emails. It supports various protocols:
- SMTP – Simple Mail Transfer Protocol (for sending emails).
- POP3 – Post Office Protocol (for receiving emails).
- IMAP – Internet Message Access Protocol (for managing emails on server).
Spring provides excellent support for JavaMail through
JavaMailSender interface, making it very easy to send emails.Setup: Add dependencies (if using Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
Configure mail properties in application.properties:
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-app-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Sending a simple email:
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendSimpleEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
message.setFrom("your-email@gmail.com");
mailSender.send(message);
}
}
Two Minute Drill
- JavaMail API enables Java apps to send and receive emails.
- Spring Boot provides spring-boot-starter-mail for easy integration.
- Configure SMTP settings in application.properties.
- Use JavaMailSender to send SimpleMailMessage or MimeMessage.
- For Gmail, use App Password instead of regular password.
Need more clarification?
Drop us an email at career@quipoinfotech.com
