Search code examples
javaspringspring-bootemailemail-attachments

Spring Boot API - Send email with attachment from URL


This is what I have so far. I think I need a line like: helper.addAttachment(attachment); in there, but that doesn't compile. I just can't figure out the syntax of how to add this attachment. Anyone have any tips? Thanks!

@RequestMapping(value = "/api/sendemailsubmitted")
public void sendEmailSubmitted(@RequestBody VerifyInfo newVerifyInfo) throws MessagingException, MalformedURLException {
    MimeMessage message = sender.createMimeMessage();
    String username = newVerifyInfo.getUsername();

    // Enable the multipart flag!
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    Part attachment = new MimeBodyPart();
    URL url = new URL("https://www.url.com/applicationsubmitted.pdf");
    attachment.setDataHandler(new DataHandler(url));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName(url.getFile());

    helper.setTo(username);
    helper.setFrom("AdmissionsApplication@gmail.com");
    helper.setText("<html><body>" +
            "Please see attachment" +
            "</body></html>", true);
    helper.setSubject("Begin Your Journey!");

    sender.send(message);

}

Solution

  • https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mail/javamail/MimeMessageHelper.html

    As you can see here you can just do a message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));

    No need to create MimeBodyPart MimeBodyPart is used to add it to javax.mail.internet.MimeMultipart and then add it to javax.mail.internet.MimeMessage, however, you are using Spring with org.springframework.mail.javamail.MimeMessageHelper