@RestController
@RequestMapping("/mail")
public class MailController {
@Autowired
public EmailService emailService;
@RequestMapping(value = {"/send"}, method = RequestMethod.POST)
public String sendEmailWithAttachment(Model model,
HttpServletRequest request) {
//Implement logic to generate PDF file
emailService.sendMessageWithAttachment(to, subject, body, pdfFile);
}
public interface EmailService{
sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment, FileSystemResource pdfFileToSend);
}
@Component
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender emailSender;
@Override
public void sendMessageWithAttachment(
String to, String subject, String text, String pathToAttachment, FileSystemResource pdfFileToSend) {
// ...
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d53524f584d51447d5f5c58 515948535a135e5250">[email protected]</a>");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
helper.addAttachment("PDF File Attachment", pdfFileToSend);
emailSender.send(message);
// ...
}
Your front-end code will call the /mail/send endpoint, which triggers the generation of a PDF for the user, creates an email and sends it using spring-boot-mail-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
References: