【问题标题】:How to create pdf file and send in mail of spring boot application如何创建pdf文件并发送spring boot应用程序的邮件
【发布时间】:2017-12-18 09:29:36
【问题描述】:

我正在尝试以创建的 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");

这就是 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());
        }
    }

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

另外我需要在邮件中发送多个pdf报告,我该怎么做,请朋友帮我解决这个问题,我找到了一个叫jasper的东西,是不是和我的环境有关,

【问题讨论】:

  • 太宽泛了。将问题分解为一组较小的问题。 PDF生成、附件使用等

标签: java spring email pdf spring-boot


【解决方案1】:

这是发送邮件的方式:

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) { }
        }
    }
}

您可以看到我们创建了一个 MimeBodyPart 和一个 DataSource,该 bytes 是由一个名为 writePdf() 的方法产生的:

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

由于我们使用ByteOutputStream 而不是FileOutputStream,因此没有文件写入磁盘。

【讨论】:

  • 这里的Document类是什么,javax.swing.text or org.dom4j or org.thymeleaf.dom or org.w3c.dom
  • 它是 iText 5 中的 com.itextpdf.text.Document 对象。如果您想要最新版本,请查看 iText 7 文档:developers.itextpdf.com/content/itext-7-jump-start-tutorial
  • iText 现在付费了。?除了 jasper 还有其他的 itext 替代品吗?
  • 是的@PawanTiwari,你可以使用 OpenPdf !它是 iText 的一个分支,并共享它的许多概念和类。
猜你喜欢
  • 2019-03-04
  • 1970-01-01
  • 2023-03-18
  • 2018-03-31
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多