简体   繁体   English

如何使用 Spring Boot、JavaScript、Ajax 将网页电子邮件作为附件发送?

[英]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.我已经实现了以 PDF 格式生成发票的功能。 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然后你的Javascript调用这个/mail/send端点,它应该为这个用户生成PDF,创建一个电子邮件,并使用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 https://howtodoinjava.com/spring-boot2/send-email-with-attachment/#5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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