Solved

javax.mail.internet.ParseException

Posted on 2004-10-27
2,598 Views
Last Modified: 2010-05-19
I am trying to attach a PDF generated using itext as an attachment with email. I get a javax.mail.internet.ParseException.

Here is my code:
            

      Session session1 = Session.getDefaultInstance(props, null);
      Message message = new MimeMessage(session1);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject(sub);
                  
      //Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

               //Fill the message
      messageBodyPart.setText("Here's the file");
                  
      
             //      Create a Multipart
      Multipart multipart = new MimeMultipart();
          multipart.addBodyPart(messageBodyPart);

           // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            javax.activation.DataSource ds = new ByteArrayDataSource(baosPDF,"application/pdf");
            messageBodyPart.setDataHandler(new DataHandler(ds));
                  
      messageBodyPart.setFileName("test.pdf");
                  
        // Add part two
                  
         multipart.addBodyPart(messageBodyPart);
     
 // Put parts in message
message.setContent(multipart);
 // Send the message
Transport.send(message);


in the ByteArrayDataSoruce if I change from boasPDF.toByteArrya() it still gives me this exception.

WHERE baosPDF is the ByteArrayOutputStream().

If I change it to boasPDF.toString() it sends a PDF but does not have any content.

Can some please say what is wrong in the above block of code.

0
Question by:new2j4v4
    4 Comments
     
    LVL 2

    Expert Comment

    by:tdisessa
    How do you build "baosPDF"?
    0
     

    Author Comment

    by:new2j4v4
    protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req,final ServletContext ctx)
                      throws DocumentException {
                      Document doc = new Document();

                      ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
                      PdfWriter docWriter = null;

                      try {
                            docWriter = PdfWriter.getInstance(doc, baosPDF);

                            doc.addAuthor(this.getClass().getName());
                            doc.addCreationDate();
                            doc.addProducer();
                            doc.addCreator(this.getClass().getName());
                            doc.addTitle("Report");
                            doc.addKeywords("pdf, itext, Java, open source, http");

                            doc.setPageSize(PageSize.LETTER);
                            
                            HeaderFooter footer = new HeaderFooter(new Phrase("What to display",colFontInit),false);
                            doc.setFooter(footer);
                            Image gif = Image.getInstance("C:/Program Files/Apache Group/Tomcat 4.1/webapps/Test/images/tt.gif");
                            Chunk ch = new Chunk(gif,0,-5);
                            Chunk chHeader = new Chunk("The title",FontFactory.getFont(FontFactory.HELVETICA,12,Font.BOLDITALIC));
                            Chunk chHeader1 = new Chunk("Company title",FontFactory.getFont(FontFactory.HELVETICA,9,Font.BOLD));
                      
                            Paragraph myParagraph = new Paragraph();
                            myParagraph.add(gif);
                            int x = myParagraph.size();
                            Paragraph para = new Paragraph();
                                        
                            HeaderFooter header = new HeaderFooter(myParagraph,false);
                            header.setBorder(0);
                            doc.setHeader(header);
                            doc.open();
                            doc.add(new Paragraph("\n"));
                            doc.add(new Paragraph("The column name"));
                            doc.close();
                            docWriter.flush();
                            docWriter.close();
                      } catch (DocumentException dex) {
                            baosPDF.reset();
                            throw dex;
                      }catch (IOException ioe)
                      {
                            System.out.println("mdaPdf: "+ioe);
                      }
                      finally {
                            if (doc != null) {
                                  doc.close();
                            }
                            if (docWriter != null) {
                                  docWriter.close();
                            }
                      }

                      if (baosPDF.size() < 1) {
                            throw new DocumentException(
                                  "document has " + baosPDF.size() + " bytes");
                      }
                      return baosPDF;
                }

    Also the ByteArrayDataSource code:

    package com.mda.util;


    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.Date;

    import javax.activation.DataSource;


    /**
     * Used to create a DataSource for the mail message.
     * @see MailHelper
     */
    public class ByteArrayDataSource implements DataSource {
       

          /**
           * @param baosPDF
           * @param applicationType
           */
          public ByteArrayDataSource(ByteArrayOutputStream baosPDF, String applicationType) {
                
                this.data = baosPDF.toByteArray();
                this.type = type;
          }

          private byte[] data; // data for mail message
          private String type; // content type/mime type

       /**
          * Create a DataSource from a String
          * @param data is the contents of the mail message
          * @param type is the mime-type such as text/html
          */
          public ByteArrayDataSource(String data, String type) {
                try {
                       this.data = data.getBytes("UTF-8");
                      } catch (UnsupportedEncodingException uex) { }
                this.type = type;
          }

          /**
                * @param bs
                * @param applicationType
                */
             public ByteArrayDataSource(byte[] bs, String applicationType) {
                
                  try{
                      this.data = bs;
                      } catch(Exception e){
                      System.out.println(e);
                  }
                   this.type = type;
             }
          //DataSource interface methods

          public InputStream getInputStream() throws IOException {
                if (data == null)
                      throw new IOException("no data");
                return new ByteArrayInputStream(data);
          }

          public OutputStream getOutputStream() throws IOException {
                throw new IOException("cannot do this");
          }

          public String getContentType() {
                return type;
          }

          public String getName() {
                return "dummy";
          }
    }


    0
     
    LVL 2

    Accepted Solution

    by:
    First of all, a couple of the constructors for ByteArrayDataSource are specified incorrectly:

          public ByteArrayDataSource(ByteArrayOutputStream baosPDF, String applicationType) {
             
              this.data = baosPDF.toByteArray();
              this.type = type;
         }

            public ByteArrayDataSource(byte[] bs, String applicationType) {
             
                try{
                   this.data = bs;
                   } catch(Exception e){
                   System.out.println(e);
                }
                 this.type = type;
            }

    should be:

          public ByteArrayDataSource(ByteArrayOutputStream baosPDF, String applicationType) {
             
              this.data = baosPDF.toByteArray();
              this.type = applicationType;
         }

            public ByteArrayDataSource(byte[] bs, String applicationType) {
             
                try{
                   this.data = bs;
                   } catch(Exception e){
                   System.out.println(e);
                }
                 this.type = applicationType;
            }

    Try that and I'll keep looking for more.
    0
     

    Author Comment

    by:new2j4v4
    That worked thanks for the help
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
    Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now