Sitemap

How to Send Email With Attachment in SpringBoot | step by step tutorial

2 min readJan 9, 2024

--

In this tutorial I will take you through how to send email attachment with spring boot.

First, we need to create a project with Spring Initializr a web based tool to helps you kick start a spring boot project, by visiting the website https://start.spring.io/.

Press enter or click to view image in full size
create a springboot project with spring initializr

2) Configure Project Essentials

  • Project: Select the type of project (Maven Project or Gradle Project).
  • Language: Choose the programming language (Java, Kotlin, etc.).
  • Spring Boot Version: Select the desired version of Spring Boot.
  • Group: Define the base package for your application (e.g., com.example).
  • Artifact: Specify the name of your project (e.g., my-spring-app).
  • Add Required Dependencies (Spring Web, Java Mail Sender & Lombok)

3) Generate Your Project Initiate project creation by clicking “Generate.”

4) Obtain Your Project Files Download the project archive (ZIP format).

5) Import into IDE Unzip and import into your IDE of choice (IntelliJ, Eclipse…). In my case I am using Intellij for this tutorial.

Get thexpertdev’s stories in your inbox

Join Medium for free to get updates from this writer.

The project structure

Press enter or click to view image in full size

Controller

@RestController
@RequestMapping("/api")
public class DemoEmailController {

private DemoEmailService demoEmailService;

public DemoEmailController(DemoEmailService demoEmailService) {
this.demoEmailService = demoEmailService;
}

@PostMapping("/sendmail")
public ResponseEntity<?> create(@RequestBody EmailRequest emailRequest){
this.demoEmailService.sendEmail(emailRequest);
return new ResponseEntity<>("Email Sent", HttpStatus.OK);
}
}

DemoEmailService

public interface DemoEmailService {

void sendEmail(EmailRequest emailRequest);

}

DemoEmailServiceImpl

public void sendEmail(EmailRequest emailRequest) {
//create an instance of the java mail sender
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("yourdomain.com");
mailSender.setPort(465);
mailSender.setUsername("username");
mailSender.setPassword("password");

Properties properties= mailSender.getJavaMailProperties();
properties.put("mail.transport.protocol","smtp");
properties.put("mail.smtp.auth","true");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.ssl.enable","true");
properties.put("mail.debug","true");

JavaMailSender javaMailSender= mailSender;
MimeMessagePreparator preparator = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailRequest.getRecipient()));
mimeMessage.setFrom(new InternetAddress("demo@thexpertdev.com"));
mimeMessage.setSubject("Demo Email With Attachment");
mimeMessage.setText(emailRequest.getMessage());

String attachment = "uploads/names.csv";
try{

FileSystemResource file = new FileSystemResource(new File(attachment));
if (file.exists()){
MimeMessageHelper helper= new MimeMessageHelper(mimeMessage,true);
helper.addAttachment(file.getFilename(), file);
helper.setText("",true);
} else {
System.out.println("File is not Found");
}
} catch (Exception ex){
ex.printStackTrace();
}

};
javaMailSender.send(preparator);
}

Result

Press enter or click to view image in full size

Best Practices

  1. store configurable values in prop files instead of hardcoding
  2. have unit tests
  3. securely store the credentials & extract at runtime

Video walkthrough

You can follow the video for a step by step guide

--

--

thexpertdev
thexpertdev

Written by thexpertdev

Java | SpringBoot | Software Engineering | Tutorials | distributed sytems | https://thexpertdev.com/