如何创建pdf文件并发送spring boot应用程序的邮件

时间:2017-07-13 14:16:36

标签: java spring email pdf spring-boot

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

其实我知道如何使用百万美元模板引擎发送电子邮件,但是如何在内存中创建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的东西,它是否与我的环境有关,

1 个答案:

答案 0 :(得分:2)

这是您发送邮件的方式:

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的{​​{1}},该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代替SELECT type, sum(1) FILTER (WHERE place = 'home') AS home, sum(1) FILTER (WHERE place = 'school') AS school, sum(1) FILTER (WHERE place = 'work') AS work, sum(1) FILTER (WHERE place = 'cafe') AS cafe, sum(1) FILTER (WHERE place = 'friends') AS friends, sum(1) FILTER (WHERE place = 'mall') AS mall FROM reports GROUP BY type ,因此没有文件写入磁盘。