Spring Boot Email Multipart File Attachment (2024)
In this tutorial, we'll demonstrate how to send email in Spring Boot with or without file/image attachments using gmail/outlook configurations.
Create Spring Boot application
Create Spring Boot application from Spring Initializr.
Project Structure
Add Dependencies
Add below dependencies for Web - spring-boot-starter-web
and for email - spring-boot-starter-mail
.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-email-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-email-example</name>
<description>Demo project for Spring Boot Email</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Application Properties
Add configuration details in application.properties
file.
## Gmail Configuration ##
spring.mail.host=smtp.gmail.com
spring.mail.port=25
spring.mail.username=test@gmail.com
## Outlook Configuration ##
#spring.mail.host=smtp-mail.outlook.com
#(With TLS)
#spring.mail.port=587
#25 (Without TLS/SSL)
#spring.mail.port=25
#spring.mail.username=test@outlook.com
#spring.mail.properties.mail.smtp.ssl.trust=smtp-mail.outlook.com
#spring.mail.properties.mail.tls=true
# provide password
spring.mail.password=ghsgdgdtymnb
# Common properties
spring.mail.properties.mail.debug=true
spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
GMAIL: Use an app password rather than the Gmail password if you want to be able to use 2-step verification and set the "enable less secure apps" option off.
- Login to Gmail -> Manage your Google Account -> Click on Security.
- Goto to App Passwords -> Provide login password.
- Select app with a some name -> Click on Generate.
- Can refer Gmail Sign in with App Passwords for detail steps.
OUTLOOK: Contact your administrator for Outlook Configurations for private server.
Email Data Model
Create model class called NotificationEmail
.
package com.techgeeknext.request;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NotificationEmail {
private String to;
private String cc;
private String subject;
private String bodyMsg;
private MultipartFile file;
private boolean isHtmlMsg;
}
Email Notification Service
package com.techgeeknext.service;
import com.techgeeknext.request.NotificationEmail;
import org.springframework.web.multipart.MultipartFile;
public interface NotificationService {
boolean sendTextNotificationEmail(NotificationEmail notificationEmail);
boolean sendNotificationEmailWithAttachment(NotificationEmail notificationEmail,
MultipartFile file);
}
Email Notification Service Implementation
Create a service class called NotificationServiceImpl
for email implementation.
package com.techgeeknext.service;
import com.techgeeknext.request.NotificationEmail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
@Slf4j
public class NotificationServiceImpl implements NotificationService {
@Autowired
private JavaMailSender mailSender;
/**
* Method to send email with simple text
*
* @param notificationEmail
* @return boolean
*/
@Override
public boolean sendTextNotificationEmail(NotificationEmail notificationEmail) {
try {
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(notificationEmail.getTo());
mailMessage.setSubject(notificationEmail.getSubject());
mailMessage.setText(notificationEmail.getBodyMsg());
mailSender.send(mailMessage);
return true;
} catch (Exception ex) {
log.info(ex.getMessage());
return false;
}
}
/**
* Method to send email with html tags message/simple message with attachment.
*
* @param notificationEmail
* @param file
* @return
*/
@Override
public boolean sendNotificationEmailWithAttachment(NotificationEmail notificationEmail,
MultipartFile file) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setTo(notificationEmail.getTo());
messageHelper.setSubject(notificationEmail.getSubject());
if (notificationEmail.isHtmlMsg()) {
//for html based text message set flag to true
//bodyMsg: <b>This is Notification email</b>
messageHelper.setText(notificationEmail.getBodyMsg(), true);
} else {
///for simple plain text message
messageHelper.setText(notificationEmail.getBodyMsg());
}
messageHelper.addAttachment(file.getOriginalFilename(), file);
mailSender.send(mimeMessage);
return true;
} catch (MessagingException ex) {
log.info(ex.getMessage());
return false;
}
}
}
Email Notification Controller
Create rest endpoint to send notification through email using simple/html message with/without attachment.
package com.techgeeknext.controller;
import com.techgeeknext.request.NotificationEmail;
import com.techgeeknext.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NotificationController {
@Autowired
NotificationService notificationService;
@PostMapping("/sendNotificationEmail")
public ResponseEntity<String> sendNotificationEmail(@ModelAttribute NotificationEmail notificationEmail) {
boolean emailSent = false;
if (notificationEmail.getFile()!=null) {
emailSent = notificationService.sendNotificationEmailWithAttachment(notificationEmail, notificationEmail.getFile());
} else {
emailSent = notificationService.sendTextNotificationEmail(notificationEmail);
}
if (emailSent) {
return ResponseEntity.ok("Email sent.");
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Error occurred while sending email.");
}
}
}
Test Spring Boot Email Example
- Start the Spring Boot Application by running
spring-boot:run
or by running main class. Spring Boot Email
Open Postman, use POST method with end point http://localhost:8080/sendNotificationEmail and provide email details to send the notification message through email.- As demonstrated below, our spring boot application will send an email to the mentioned email address.
We can implement email notification features either in Spring Boot Event Listener Example OR in case of error handling in Spring Boot AOP Exception Handling
Download Source Code
The full source code for this article can be found below.
- Download it here - Spring Boot Email Example