In this blog post, we’ll delve into the process of creating a Java Spring service that leverages JavaMail to send emails, both with and without attachments. This capability is crucial for many web applications, from sending user registration confirmations to delivering reports and notifications.

Let’s get started.

1. Set up Your Project

  • Make sure you have a Spring Boot project ready.
  • Include the following dependency in your pom.xml (for Maven) or build.gradle (for Gradle):
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. Configure Email Properties

  • In your application.properties or application.yml file, configure the necessary email properties. Here’s an example for application.properties:
spring.mail.host=smtp.gmail.com 
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
  • Replace the placeholders with your actual email settings. If you’re using a different email provider, adjust the host and port accordingly.

3. Create the Email Service

  • Now let’s create a Spring service to handle email sending.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSimpleEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
    }

    public void sendEmailWithAttachment(String to, String subject, String text, String attachmentPath) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);

        FileSystemResource file = new FileSystemResource(new File(attachmentPath));
        helper.addAttachment(file.getFilename(), file);

        javaMailSender.send(message);
    }
}
  • We inject the JavaMailSender, which Spring Boot auto-configures based on our properties.
  • The sendSimpleEmail method handles sending plain text emails.
  • The sendEmailWithAttachment method allows sending emails with file attachments.

4. Use the Email Service

  • You can now autowire this EmailService into any of your Spring components (controllers, services, etc.) and use it to send emails.
@Autowired
private EmailService emailService;

// ...

emailService.sendSimpleEmail("recipient@example.com", "Hello", "This is a test email.");

// ...

try {
    emailService.sendEmailWithAttachment("recipient@example.com", "Report", "Please find the attached report.", "/path/to/report.pdf");
} catch (MessagingException e) {
    // Handle exception
}

Important Notes:

  • Ensure that you have the necessary permissions to send emails from your email provider.
  • For production environments, consider using a dedicated email service provider for better deliverability and scalability.
  • Handle exceptions gracefully, especially when dealing with attachments or network issues.
  • Always test your email sending functionality thoroughly.

Discover more from GhostProgrammer - Jeff Miller

Subscribe to get the latest posts sent to your email.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.