简体   繁体   中英

How to send email of webpage as an attachment using Spring Boot, JavaScript, Ajax?

I have implemented a feature to generate invoice in PDF format. So basically there are two buttons one for print and another one for Email. So when user clicks on email button then the invoice should be sent to specific email.

The thing is I am bit confused about the implementation. So If any one have any suggestion, would be appreciable.

显示电子邮件发票的屏幕截图

显示生成的 PDF 的屏幕截图

@Controller
@RequestMapping("/mail")
public class MailController {

    @Autowired
    public EmailService emailService;


    @RequestMapping(value = {"/send"}, method = RequestMethod.POST)
    public String sendEmailWithAttachment(Model model,
                             HttpServletRequest request) {

             //Logic to create 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("noreply@baeldung.com");
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);
    
    helper.addAttachment("PDFFile", pdfFileToSend);

    emailSender.send(message);
    // ...
}

Your Javascript then calls this /mail/send endpoint, which should generate the PDF for this user, create an Email, and send Email using spring-boot-mail-starter

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

References:

https://howtodoinjava.com/spring-boot2/send-email-with-attachment/#5

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