Sending emails with attachments is a common requirement in many web applications. In Django, the built-in send_mail
function allows you to send simple text-based emails. However, to send emails with attachments, we need to use the EmailMessage
class. In this blog, we will explore how to send email with attachments in Django.
Note: For this tutorial, we will continue the project which we used to in blog – How to Send Email with HTML Template in Spring Boot
Prerequisites
Before we dive into the implementation, make sure you have the following prerequisites covered:
- JDK (Java Development Kit) installed on your system.
- A working Spring Boot project.
- SMTP Server Details, In this project we are using Gmail SMTP
Step 1: Include Dependencies
Open your pom.xml
(for Maven) or build.gradle
(for Gradle) and include the necessary dependencies:
For Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
For Gradle:
implementation 'org.springframework.boot:spring-boot-starter-mail'
These dependencies provide the necessary classes and components for email sending in Spring Boot.
Step 2: Configure Email Properties
In the application.properties
file of your project (located in the src/main/resources
directory), configure the email properties as follows:
# Email Configuration
spring.mail.host=smtp.gmail.com
[email protected]
spring.mail.password=your-email-password
spring.mail.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
Replace your-smtp-server
, [email protected]
, and your-email-password
with the appropriate values for your SMTP server and email account.
Please watch bellow video, to get email smtp details using Gmail.
Step 3: Sending Email with Attachment
Attaching files to emails can be extremely useful when sending documents, images, or any other type of file. Here, we’ll modify your Spring Boot application to send emails with attachments.
Step 4: Create an Email Service
Within your project, create an email service (EmailService.java
) class that will encapsulate the email sending logic. Here’s an example of how it might look:
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
@Service
public class EmailService {
private final JavaMailSender mailSender;
private final TemplateEngine templateEngine;
@Autowired
public EmailService(JavaMailSender mailSender, TemplateEngine templateEngine) {
this.mailSender = mailSender;
this.templateEngine = templateEngine;
}
public void sendEmail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
public void sendEmailWithHtmlTemplate(String to, String subject, String templateName, Context context) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
try {
helper.setTo(to);
helper.setSubject(subject);
String htmlContent = templateEngine.process(templateName, context);
helper.setText(htmlContent, true);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
// Handle exception
}
}
public void sendEmailWithAttachment(String to, String subject, String body, String filePath) {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body);
FileSystemResource file = new FileSystemResource(new File(filePath));
helper.addAttachment(file.getFilename(), file);
mailSender.send(mimeMessage);
} catch (MessagingException e) {
// Handle exception
}
}
}
Step 2: Create EmailRequest Class
Create the EmailRequest.java
class to represent the details of the email you want to send. This class should have fields for the recipient’s email address, the email subject, and the email body. You can create the EmailRequest
class as follows:
public class EmailRequest {
private String to;
private String subject;
private String body;
private String attachmentFilePath;
public String getAttachmentFilePath() {
return attachmentFilePath;
}
public void setAttachmentFilePath(String attachmentFilePath) {
this.attachmentFilePath = attachmentFilePath;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
This class acts as a container for the email details, allowing you to easily pass them to the sendEmail
method in the EmailService
.
Step 3: Sending Emails
With the EmailService
and EmailRequest
class in place, you can now use them to send emails from your project application. For instance, you could send an email from a controller like bellow, please create EmailController.java
Class and paste the below code:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
@RestController
public class EmailController {
private final EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@PostMapping("/send-email")
public String sendEmail(@RequestBody EmailRequest emailRequest) {
emailService.sendEmail(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getBody());
return "Email sent successfully!";
}
@PostMapping("/send-html-email")
public String sendHtmlEmail(@RequestBody EmailRequest emailRequest) {
Context context = new Context();
context.setVariable("message", emailRequest.getBody());
emailService.sendEmailWithHtmlTemplate(emailRequest.getTo(), emailRequest.getSubject(), "email-template", context);
return "HTML email sent successfully!";
}
@PostMapping("/send-email-with-attachment")
public String sendEmailWithAttachment(@RequestBody EmailRequest emailRequest) {
emailService.sendEmailWithAttachment(emailRequest.getTo(), emailRequest.getSubject(), emailRequest.getBody(), emailRequest.getAttachmentFilePath());
return "Email with attachment sent successfully!";
}
}
Step 4: Testing Email with Attachment
To test sending an email with an attachment, use tools like Postman or curl
to make a POST request to the /send-email-with-attachment
endpoint, providing a JSON payload:
{
"to": "[email protected]",
"subject": "Test Email with Attachment",
"body": "This is a test email with attachment sent from myproject.",
"attachmentFilePath": "/path/to/your/file.txt"
}
Using curl
:
curl -X POST -H "Content-Type: application/json" -d '{
"to": "[email protected]",
"subject": "Test Email with Attachment",
"body": "This is a test email with attachment sent from myproject.",
"attachmentFilePath": "/path/to/your/file.txt"
}' http://localhost:8080/send-email-with-attachment
Conclusion
By enhancing your SpringBoot application to send emails with attachments, you’ve expanded its capabilities to include file sharing through email communications. The steps provided in this guide have demonstrated how to integrate attachment functionality into your existing email framework, allowing you to seamlessly share files with your recipients.
Find this project on Github.