简体   繁体   中英

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);

}

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.inte.net.MimeMultipart and then add it to javax.mail.inte.net.MimeMessage, however, you are using Spring with org.springframework.mail.javamail.MimeMessageHelper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM