当前位置: 首页 > 知识库问答 >
问题:

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

章学义
2023-03-14

我正在尝试发送电子邮件,附件是创建的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的东西,它和我的环境有关吗,

共有1个答案

丁弘新
2023-03-14

这是您发送邮件的方式:

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,其中包含从bytes创建的DataSource,该方法由名为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();
}

因为我们使用字节输出流而不是文件输出流所以没有文件被写入磁盘。

 类似资料:
  • 我是一名新开发人员,致力于用AMP代码构建“mywebsite.com”网站。我想创建一个页面,其中包含用户名、电子邮件地址和消息的输入字段。我希望用户能够输入这三个字段,并将用户名、电子邮件地址和邮件发送到“myemail@gmail.com” 以下是我页面的超文本标记语言: 这是我的php文件: 在真正的代码中,我用我的网站URL和电子邮件代替了我的网站。com和admin@mywebsite

  • 当你有一个不成熟的 Idea 时,作为一个受精益思想影响的开发者,那么你可能会学习 Dropbox 创建一个 Landing Page 来验证你的想法。如下图所示: Launch Page 这个时候,你只需要大胆地公布出你的 Idea。等待用户的到来、在网页上提交他们的邮箱 blabla。然后在产品准备得差不多的时候,就可以大声地告诉全世界,你们可以来试用了。不过,这只里我们只讨论如何来发送邮件。

  • 我正在用Android开发一个应用程序。我不知道如何从应用程序发送电子邮件?

  • 问题内容: 在我的Node / Express应用程序中,我有以下代码,假设要从文件中读取PDF文档,并将其发送到浏览器: 我没有收到任何错误,但是我也没有在浏览器中获取文件。我究竟做错了什么? 问题答案: 您必须通过管道从Readable Stream到Writable流,而不是相反: 另外,您以错误的方式设置了编码,如果需要,可以通过编码传递对象。

  • 我正在尝试编写一个将图像转换为PDF文件的web应用程序。用户发送两幅图像(JPEG、PNG),并应接收和下载PDF文件。 目前的主要问题是我不知道如何将PDF文件返回给客户端。 这是我的控制器: 这是将图像转换为PDF文件的服务(这里我使用库): 另外,当生成文件以从存储中下载文件时,可以将PDF文件存储在某个位置,并在客户端创建“下载”按钮?

  • 我正在尝试创建一个发送邮件的应用程序。它获取用户输入(To、Subject、Message),单击表单按钮发送邮件,并将该邮件存储在mongodb上 前端 后端 > 架构 常量mongoose=require(“mongoose”); const UserSchema=new mongoose.schema({ 收件人:{type:String,},抄送:{type:String,},密件抄送:{