0
votes

I've made a jsp program that when the form is submitted a pdf is created using the itext library and an email is sent out with that pdf as an attachment, it creates the pdf but doesn't attach the file, I can get it to send the email and create the pdf without attaching it when I get rid of the multipart code but I can't get it to do both things at once.

Now I've tried attaching the file the email won't send at all but I'm guessing that's probably down to not being able to find the file I want to attach thus not sending the email as I believe when I removed all the code for attaching the file the email sent without any problems. Has anyone experienced this issue before or can anybody offer any advice as I've searched high and low for the answers and I keep finding the same post over and over, things have got that desperate I've been going beyond the first 2 pages of a google search.

<%@page import="javax.activation.DataHandler"%>
<%@page import="javax.activation.FileDataSource"%>
<%@page import="javax.mail.Multipart"%>
<%@page import="javax.mail.internet.MimeMultipart"%>
<%@page import="javax.mail.internet.MimeBodyPart"%>
<%@page import="javax.mail.Address"%>
<%@page import="com.sun.mail.smtp.SMTPTransport"%>
<%@page import="javax.mail.URLName"%>
<%@page import="javax.mail.internet.InternetAddress"%>
<%@page import="javax.mail.internet.MimeMessage"%>
<%@page import="javax.mail.Transport"%>
<%@page import="javax.mail.Session"%>

<%@ page import="java.io.*, com.itextpdf.text.*, com.itextpdf.text.pdf.*" %>

<%
            String fileStr = request.getParameter("employeeid") + " Daily Briefing Sheet " + request.getParameter("date") + ".pdf";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileStr + "\"");
            Document document=new Document();

            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            document.add(new Paragraph("Daily Briefing Sheet"));

            // Employee Data the ID and the dates they entered
            document.add(new Paragraph(request.getParameter("employeeid")));
            document.add(new Paragraph(request.getParameter("date")));
            document.add(new Paragraph(request.getParameter("date2")));
            document.add( Chunk.NEWLINE );

            document.add(new Paragraph("Employee Overview of Yesterdays Performance"));
            // The Overview of yesterday and today
            document.add(new Paragraph(request.getParameter("overview")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Todays Work Plan"));
            document.add(new Paragraph(request.getParameter("overviewtoday")));
            document.add( Chunk.NEWLINE );

            // Measures Table Data
            document.add(new Paragraph("Daily Briefing Sheet"));
            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure1")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay1")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt1")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt1")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma1")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg1")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt1")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya1")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg1")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure2")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay2")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt2")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt2")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma2")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg2")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt2")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya2")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg2")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure3")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay3")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt3")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt3")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma3")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg3")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt3")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya3")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg3")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure4")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay4")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt4")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt4")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma4")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg4")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt4")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya4")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg4")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure5")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay5")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt5")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt5")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma5")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg5")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt5")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya5")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg5")));

            // Narratives 
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("What got left behind yesterday which needs to be rescheduled? When is it to be planned?"));
            document.add(new Paragraph(request.getParameter("leftbehind")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any critical issues which need to be discussed or passed on?"));
            document.add(new Paragraph(request.getParameter("criticalissues")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("What progress has been made on Projects/Tasks?"));
            document.add(new Paragraph(request.getParameter("progress")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any improvement suggestions to be tabled or action sheets to be handed over?"));
            document.add(new Paragraph(request.getParameter("improvements")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any quality matters which needs discussed or passed on?"));
            document.add(new Paragraph(request.getParameter("qualitymatters")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any internal or external customer complaints which need to be discussed or handed over?"));
            document.add(new Paragraph(request.getParameter("complaints")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Is there any information which needs to be shared or handed over?"));
            document.add(new Paragraph(request.getParameter("information")));
            document.add( Chunk.NEWLINE );


            try{
              Session mailSession = Session.getInstance(System.getProperties());
              Transport transport = new SMTPTransport(mailSession,new URLName("smtp.gmail.com"));
              transport = mailSession.getTransport("smtps");
              transport.connect("smtp.gmail.com", 465 ,"[email protected]","mypass");

              MimeMessage m = new MimeMessage(mailSession); 
              m.setFrom(new InternetAddress("[email protected]"));
              Address[] toAddr = new InternetAddress[] {
              new InternetAddress("[email protected]")
              };
              m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
              m.setHeader("Content-Type", "multipart/mixed");
              m.setSubject("Performance Portal Figures");
              m.setSentDate(new java.util.Date());

              MimeBodyPart messageBodyPart = new MimeBodyPart();
              messageBodyPart.setText("See attached");
              Multipart multipart = new MimeMultipart();
              multipart.addBodyPart(messageBodyPart);

              messageBodyPart = new MimeBodyPart();
              javax.activation.DataSource source = new FileDataSource(fileStr);
              messageBodyPart.setDataHandler(new DataHandler(source));
              messageBodyPart.setFileName(fileStr);
              multipart.addBodyPart(messageBodyPart);

              m.setContent(multipart);

              transport.sendMessage(m,m.getAllRecipients());
              transport.close();
              out.println("Thanks for sending mail!");
            }
            catch(Exception e){
              out.println(e.getMessage());
              e.printStackTrace();
            } 
            document.close(); 
 %>
2
First of all having the java codes inside jsp is considered as the bad practice for more than a decade . so move them to the servlet and in your code the pdf file may not be ready when you are trying to send the email - Santhosh
I know that but I have no experience of using servlets really, how do I get the servlet to run and all that. Other than that if that's the case is there a way around that? - Crouch
reason is that servlets are made for that purposes . can you identify the thrown when are you trying to the send pdf as attachment? - Santhosh
No error at all that I can see in netbeans another reason why I came here also. I'm not sure what the error is - Crouch

2 Answers

2
votes

You are creating a PDF that is sent to the browser:

PdfWriter.getInstance(document, response.getOutputStream());

Then you are complaining that this PDF isn't attached to a mail.

That's... weird. It goes against elementary logic that bytes sent to a ServletOutputStream could be recuperated to send them to a mail.

In your mail, you try to attache fileStr which seems to be nothing more than a String with a filename:

String fileStr = request.getParameter("employeeid") + " Daily Briefing Sheet " + request.getParameter("date") + ".pdf";

If you want to send a PDF to the browser and use it to attach the PDF to a mail, you need to create the PDF in memory:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);

Once the PDF is fully created, you can send the PDF to the ServletOutputStream like this:

baos.writeTo(response.getOutputStream());

You can also get a byte[] with the PDF like this:

byte[] pdf = baos.toByteArray();

You can use these pdf as many times as you want to, for instance: to add the PDF as an attachment to a mail.

Extra remark: I agree with the comment made by san krish that using JSP for this purpose is suboptimal. You should use a Servlet instead. I'm very surprised that your JSP file actually works. I'm very surprised you don't get the following error:

java.lang.IllegalStateException: Already using output stream
0
votes

Got it working using the example you mentioned everything works spot on.

Thanks for that below is the code I have used for anyone curious on how to do it, sorry I've used jsp again but this project is a pretty urgent one I need it up and running before I optimize it as there is a high demand for it.

<%@page import="javax.activation.DataSource"%>
<%@page import="javax.mail.util.ByteArrayDataSource"%>
<%@page import="javax.activation.DataHandler"%>
<%@page import="javax.activation.FileDataSource"%>
<%@page import="javax.mail.Multipart"%>
<%@page import="javax.mail.internet.MimeMultipart"%>
<%@page import="javax.mail.internet.MimeBodyPart"%>
<%@page import="javax.mail.Address"%>
<%@page import="com.sun.mail.smtp.SMTPTransport"%>
<%@page import="javax.mail.URLName"%>
<%@page import="javax.mail.internet.InternetAddress"%>
<%@page import="javax.mail.internet.MimeMessage"%>
<%@page import="javax.mail.Transport"%>
<%@page import="javax.mail.Session"%>


<%@ page import="java.io.*, com.itextpdf.text.*, com.itextpdf.text.pdf.*" %>
<%


    /**
     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
     */
            // step 1
            Document document = new Document();
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(document, baos);
            // step 3
            document.open();
            // step 4
            document.add(new Paragraph("Daily Briefing Sheet"));

            // Employee Data the ID and the dates they entered
            document.add(new Paragraph(request.getParameter("employeeid")));
            document.add(new Paragraph(request.getParameter("date")));
            document.add(new Paragraph(request.getParameter("date2")));
            document.add( Chunk.NEWLINE );

            document.add(new Paragraph("Employee Overview of Yesterdays Performance"));
            // The Overview of yesterday and today
            document.add(new Paragraph(request.getParameter("overview")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Todays Work Plan"));
            document.add(new Paragraph(request.getParameter("overviewtoday")));
            document.add( Chunk.NEWLINE );

            // Measures Table Data
            document.add(new Paragraph("Daily Briefing Sheet"));
            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure1")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay1")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt1")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt1")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma1")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg1")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt1")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya1")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg1")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure2")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay2")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt2")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt2")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma2")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg2")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt2")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya2")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg2")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure3")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay3")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt3")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt3")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma3")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg3")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt3")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya3")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg3")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure4")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay4")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt4")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt4")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma4")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg4")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt4")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya4")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg4")));

            document.add( Chunk.NEWLINE );

            document.add(new Paragraph(request.getParameter("measure5")));
            document.add(new Paragraph("Achieved Yesterday: " + request.getParameter("ay5")));
            document.add(new Paragraph("Plan Today: " + request.getParameter("pt5")));
            document.add(new Paragraph("Monthly Target: " + request.getParameter("mmt5")));
            document.add(new Paragraph("Monthly Achieved: " + request.getParameter("mma5")));
            document.add(new Paragraph("Monthly Gap/Over: " + request.getParameter("mmg5")));
            document.add(new Paragraph("Yearly Target: " + request.getParameter("myt5")));
            document.add(new Paragraph("Yearly Achieved: " + request.getParameter("mya5")));
            document.add(new Paragraph("Yearly Gap/Over: " + request.getParameter("myg5")));

            // Narratives 
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("What got left behind yesterday which needs to be rescheduled? When is it to be planned?"));
            document.add(new Paragraph(request.getParameter("leftbehind")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any critical issues which need to be discussed or passed on?"));
            document.add(new Paragraph(request.getParameter("criticalissues")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("What progress has been made on Projects/Tasks?"));
            document.add(new Paragraph(request.getParameter("progress")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any improvement suggestions to be tabled or action sheets to be handed over?"));
            document.add(new Paragraph(request.getParameter("improvements")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any quality matters which needs discussed or passed on?"));
            document.add(new Paragraph(request.getParameter("qualitymatters")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Are there any internal or external customer complaints which need to be discussed or handed over?"));
            document.add(new Paragraph(request.getParameter("complaints")));
            document.add( Chunk.NEWLINE );
            document.add(new Paragraph("Is there any information which needs to be shared or handed over?"));
            document.add(new Paragraph(request.getParameter("information")));
            document.add( Chunk.NEWLINE );
            // step 5
            document.close();

            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control",
                "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();


            try{
              Session mailSession = Session.getInstance(System.getProperties());
              Transport transport = new SMTPTransport(mailSession,new URLName("smtp.gmail.com"));
              transport = mailSession.getTransport("smtps");
              transport.connect("smtp.gmail.com", 465 ,"*******@gmail.com","*********");

              MimeMessage m = new MimeMessage(mailSession); 
              m.setFrom(new InternetAddress("[email protected]"));
              Address[] toAddr = new InternetAddress[] {
              new InternetAddress("[email protected]")
              };
              m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
              m.setHeader("Content-Type", "multipart/mixed");
              m.setSubject("Performance Portal Figures");
              m.setSentDate(new java.util.Date());

              MimeBodyPart messageBodyPart = new MimeBodyPart();
              messageBodyPart.setText("See attached");
              Multipart multipart = new MimeMultipart();
              multipart.addBodyPart(messageBodyPart);

              messageBodyPart = new MimeBodyPart();

              DataSource source = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
              messageBodyPart.setDataHandler(new DataHandler(source));
              messageBodyPart.setFileName("test.pdf");
              multipart.addBodyPart(messageBodyPart);

              m.setContent(multipart);

              transport.sendMessage(m,m.getAllRecipients());
              transport.close();
              out.println("Thanks for sending mail!");
            }
            catch(Exception e){
              out.println(e.getMessage());
              e.printStackTrace();
            }

%>

Thanks Bruno Lowagie