如何创建pdf文件并通过Spring Boot应用程序的邮件发送

lea*_*ram 3 java pdf email spring spring-boot

我正在尝试发送带有创建的pdf文档作为附件的电子邮件,我正在工作的环境是基于REST的java spring boot应用程序,

实际上我知道如何使用 thymeleaf 模板引擎发送电子邮件,但是如何在内存中创建 pdf 文档,并将其作为附件发送,这是我用于发送电子邮件的代码。

Context cxt = new Context();
cxt.setVariable("doctorFullName", doctorFullName);
String message = templateEngine.process(mailTemplate, cxt);
emailService.sendMail(MAIL_FROM, TO_EMAIL,"Subject", "message");
Run Code Online (Sandbox Code Playgroud)

这是 sendmail() 函数

 @Override
    public void sendPdfMail(String fromEmail, String recipientMailId, String subject, String body) {
        logger.info("--in the function of sendMail");
        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        try {
            final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            message.setSubject(subject);
            message.setFrom(fromEmail);
            message.setTo(recipientMailId);
            message.setText(body, true);

            FileSystemResource file = new FileSystemResource("C:\\xampp\\htdocs\\project-name\\logs\\health360-logging.log");
            message.addAttachment(file.getFilename(), file);


            this.mailSender.send(mimeMessage);
            logger.info("--Mail Sent Successfully");
        } catch (MessagingException e) {
            logger.info("--Mail Sent failed ---> " + e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
Run Code Online (Sandbox Code Playgroud)

实际上我需要创建一种 2-3 页的 pdf 文件报告,并通过邮件发送。

另外我需要在邮件中发送多个pdf报告,我该怎么做,你的朋友能帮我吗,我发现了一个叫做jasper的东西,它与我的环境有关吗,

Bru*_*gie 6

您可以通过以下方式发送邮件:

public void email() {
    String smtpHost = "yourhost.com"; //replace this with a valid host
    int smtpPort = 587; //replace this with a valid port

    String sender = "sender@yourhost.com"; //replace this with a valid sender email address
    String recipient = "recipient@anotherhost.com"; //replace this with a valid recipient email address
    String content = "dummy content"; //this will be the text of the email
    String subject = "dummy subject"; //this will be the subject of the email

    Properties properties = new Properties();
    properties.put("mail.smtp.host", smtpHost);
    properties.put("mail.smtp.port", smtpPort);     
    Session session = Session.getDefaultInstance(properties, null);

    ByteArrayOutputStream outputStream = null;

    try {           
        //construct the text body part
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(content);

        //now write the PDF content to the output stream
        outputStream = new ByteArrayOutputStream();
        writePdf(outputStream);
        byte[] bytes = outputStream.toByteArray();

        //construct the pdf body part
        DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
        MimeBodyPart pdfBodyPart = new MimeBodyPart();
        pdfBodyPart.setDataHandler(new DataHandler(dataSource));
        pdfBodyPart.setFileName("test.pdf");

        //construct the mime multi part
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(textBodyPart);
        mimeMultipart.addBodyPart(pdfBodyPart);

        //create the sender/recipient addresses
        InternetAddress iaSender = new InternetAddress(sender);
        InternetAddress iaRecipient = new InternetAddress(recipient);

        //construct the mime message
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSender(iaSender);
        mimeMessage.setSubject(subject);
        mimeMessage.setRecipient(Message.RecipientType.TO, iaRecipient);
        mimeMessage.setContent(mimeMultipart);

        //send off the email
        Transport.send(mimeMessage);

        System.out.println("sent from " + sender + 
                ", to " + recipient + 
                "; server = " + smtpHost + ", port = " + smtpPort);         
    } catch(Exception ex) {
        ex.printStackTrace();
    } finally {
        //clean off
        if(null != outputStream) {
            try { outputStream.close(); outputStream = null; }
            catch(Exception ex) { }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到我们创建了一个由名为MimeBodyPart的方法产生的结果创建的:DataSourcebyteswritePdf()

public void writePdf(OutputStream outputStream) throws Exception {
    Document document = new Document();
    PdfWriter.getInstance(document, outputStream);
    document.open();
    Paragraph paragraph = new Paragraph();
    paragraph.add(new Chunk("hello!"));
    document.add(paragraph);
    document.close();
}
Run Code Online (Sandbox Code Playgroud)

由于我们使用 aByteOutputStream而不是 a,FileOutputStream因此不会将文件写入磁盘。