Sending Email with Attachments in Spring Boot

11,882

Solution 1

I propose you to apply SRP to sendMessageWithAttachment() method by extracting functionality around adding attachments:

private void addAttachments(MailMessageDto message, MimeMessageHelper helper) {
  message.getFiles().forEach(file -> addAttachment(file, helper));
}

This method streams over all files and adds every file by using addAttachment():

private void addAttachment(File file, MimeMessageHelper helper) {
  String fileName = file.getName();
  try {
    helper.addAttachment(fileName, file);
    log.debug("Added a file atachment: {}", fileName);
  } catch (MessagingException ex) {
    log.error("Failed to add a file atachment: {}", fileName, ex);
  }
}

This will log an error for each failed attachment. Can you try this approach?

Solution 2

step 1. add dependencies in porm.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

step 2. add configuration code in application.properties

spring.mail.host=smtp.gmail.com
spring.mail.port=465
spring.mail.username=username
spring.mail.password=password
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=5000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.properties.mail.smtp.starttls.enable=true

step 3. add code in controller masterconroller.java

@GetMapping("/sendmail")
@ResponseBody
String home() {
    try {
        masterServiceImpl.sendEmail("path");
        return "Email Sent!";
    } catch (Exception ex) {
        return "Error in sending email: " + ex;
    }
}

step 4. add code in MasterServiceImpl.java

@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String path) throws Exception{
         MimeMessage message = javaMailSender.createMimeMessage();
         MimeMessageHelper helper = new MimeMessageHelper(message, true);
         helper.setTo("[email protected]");
         helper.setText("<html><body><h1>hello Welcome!</h1><body></html>", true);
         FileSystemResource file  = new FileSystemResource(new File(path));
         helper.addAttachment("testfile", file);
         helper.addAttachment("test.png", new ClassPathResource("test.jpeg"));
         helper.setSubject("Hi");
         javaMailSender.send(message);
   }
Share:
11,882

Related videos on Youtube

Ver
Author by

Ver

Updated on June 04, 2022

Comments

  • Ver
    Ver almost 2 years

    I'm trying to send an email with file attachments in Spring Boot.

    This is a basic gmail SMTP server application properties config:

    This is my EmailService:

    EmailService
    

    When I call this method with mailMessageDto object passed, there is no exception thrown. Nothing happens, e-mail isn't sent.

    I have debugged on javaMailSender.send(messsage) line of code and everything seems fine.

    Update

    spring.mail.properties.mail.smtp.ssl.enable=false
    

    should be false not true spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

  • Ver
    Ver over 5 years
    Also I'm sending a fileDataSource instead of just a file. And it's not working with this approach.
  • Boris
    Boris over 5 years
    @FrankLabry why can't you call getFile() method? Also it means your approach will not work in Java 11 without software changes.
  • Ver
    Ver over 5 years
    the problem is that I'm retrieving multipartFiles from RestController on my client side. You have to, however, send them from the server side as FileSystemResource in that case, not only as a File. I have written the name of it wrong in the previous comment.
  • Boris
    Boris over 5 years
    @FrankLabry ok, so why not FileSystemResource.getFile()?