Package javax.mail

Examples of javax.mail.Multipart


         if (holder.length == 0 && emailData.getContent() != null && emailData.getContent().length() > 0) {
            message.setText(emailData.getContent(), Constants.UTF8_ENCODING);
         }
         else {
            // create the Multipart and add its parts to it
            Multipart multi = new MimeMultipart();
  
            if (emailData.getContent() != null && emailData.getContent().length() > 0) {
               MimeBodyPart mbp = new MimeBodyPart();
               mbp.setFileName("content.txt");
               mbp.setText(emailData.getContent(), Constants.UTF8_ENCODING);
               mbp.setDisposition(MimeBodyPart.INLINE);
               multi.addBodyPart(mbp);
            }
  
            for (int i=0; i<holder.length; i++) {
               MimeBodyPart mbp = new MimeBodyPart();
               // 'AA xmlBlasterMessage.xbf' will be automatically quoted to '"AA xmlBlasterMessage.xbf"' by javamail implementation
               // 'xx.xbf' names will be send unquoted
               mbp.setFileName(holder[i].getFileName());
               byte[] content = holder[i].getContent();
               if (this.messageIdForceBase64 && emailData.isMessageIdAttachment(holder[i], msgIdFileName)
                    || this.contentForceBase64 && emailData.isMsgUnitAttachment(holder[i])) {
                  //We don't need to do it, javamail does it for us
                  //content = Base64.encode(holder[i].getContent()).getBytes(Constants.UTF8_ENCODING);
                  //Buggy: is not accepted by javamail: (Why? and How?)
                  mbp.setHeader(Constants.EMAIL_TRANSFER_ENCODING, Constants.ENCODING_BASE64)// "Content-Transfer-Encoding", "base64");
               }
               else {
                  // http://www.ietf.org/rfc/rfc2045.txt
                  // The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76
                  // characters long. (78 with CRLF), the line uses a trailing '=' as a soft line brake
                  mbp.setHeader(Constants.EMAIL_TRANSFER_ENCODING, Constants.ENCODING_QUOTED_PRINTABLE)// "Content-Transfer-Encoding", "quoted-printable");
                  if (holder[i].hasExtensionFromList(this.inlineExtension))
                     mbp.setDisposition(MimeBodyPart.INLINE);
               }
              
               // Encoding violates RFC 2231 but is very common to do so for non-ASCII character sets:
               //mbp.setFileName(MimeUtility.encodeText(holder[i].getFileName()));
               if (holder[i].getContentType().startsWith("text/")) {
                  //String tmp = MimeUtility.encodeText(new String(content, Constants.UTF8_ENCODING), Constants.UTF8_ENCODING, Constants.ENCODING_QUOTED_PRINTABLE);
                  //mbp.setText(tmp, Constants.UTF8_ENCODING);
                  String contentStr = new String(content, Constants.UTF8_ENCODING);
                  if (this.breakLongMessageIdLine && emailData.isMessageIdAttachment(holder[i], msgIdFileName)) {
                     // <messageId><sessionId>unknown</sessionId><requestId>1140597982821000000</requestId><methodName>update</methodName><expires>2006-02-23T08:46:22.821Z</expires></messageId>
                     contentStr = ReplaceVariable.replaceAll(contentStr, "<requestId>", "\r\n<requestId>");
                     contentStr = ReplaceVariable.replaceAll(contentStr, "<methodName>", "\r\n<methodName>");
                     contentStr = ReplaceVariable.replaceAll(contentStr, "<expires>", "\r\n<expires>");
                  }
                  mbp.setText(contentStr, Constants.UTF8_ENCODING);
               }
               else {
                  // "application/xmlBlaster-xbformat"
                  DataSource ds = new ByteArrayDataSource(
                        content,
                        holder[i].getContentType());
                  mbp.setDataHandler(new DataHandler(ds));
               }
               multi.addBodyPart(mbp);
            }
  
            // add the Multipart to the message
            message.setContent(multi);
         } // else multipart
View Full Code Here


            else {
               a = new AttachmentHolder(fileName, ct, ((String)p.getContent()).getBytes(Constants.UTF8_ENCODING));
            }
            attachments.add(a);
         } else if (p.isMimeType("multipart/*")) { // Go one level deeper ...
            Multipart mp = (Multipart) p.getContent();
            level++;
            int count = mp.getCount();
            for (int i = 0; i < count; i++)
               level = accessPart(mp.getBodyPart(i), level, attachments);
            level--;
         } else if (p.isMimeType("message/rfc822")) {
            level++;
            level = accessPart((Part) p.getContent(), level, attachments);
            level--;
View Full Code Here

         pr("=========This is plain text, level="+level+"===========", level);
         if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
      } else if (p.isMimeType("multipart/*")) {
         pr("=========This is a Multipart " + level + "==================", level);
         Multipart mp = (Multipart) p.getContent();
         level++;
         int count = mp.getCount();
         for (int i = 0; i < count; i++)
            level = dumpPart(mp.getBodyPart(i), level);
         level--;
      } else if (p.isMimeType("message/rfc822")) {
         pr("This is a Nested Message", level);
         pr("===========================", level);
         level++;
View Full Code Here

      throw new NullPointerException("DBMimeMessage.getContent() : Folder for message cannot be null");
    }

    if (DebugFile.trace) DebugFile.writeln("Folder type " + oFolder.getClass().getName());

    Multipart oRetVal;

    if (oFolder.getClass().getName().equals("com.knowgate.hipermail.DBFolder")) {

      if (sGuid==null) {
        if (DebugFile.trace) DebugFile.decIdent();
        throw new NullPointerException("DBMimeMessage.getContent() : message GUID cannot be null");
      }

      PreparedStatement oStmt = null;
      ResultSet oRSet = null;
      DBMimeMultipart oMultiPart = new DBMimeMultipart((Part) this);

      try {
        if (DebugFile.trace) {
          DebugFile.writeln("Connection.prepareStatement(SELECT id_part,id_content,id_disposition,len_part,de_part,tx_md5,id_encoding,file_name,id_type FROM "+ DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='"+sGuid+"')");
        }

    JDCConnection oJdcc = ((DBFolder)oFolder).getConnection();
        oStmt = oJdcc.prepareStatement("SELECT id_part,id_content,id_disposition,len_part,de_part,tx_md5,id_encoding,file_name,id_type FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "=?",
                                        ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        oStmt.setString(1, sGuid);

        oRSet = oStmt.executeQuery();

        while (oRSet.next()) {
          if (DebugFile.trace) DebugFile.writeln("DBMimeMultipart.addBodyPart("+sGuid+","+String.valueOf(oRSet.getInt(1))+","+oRSet.getString(2)+","+oRSet.getString(9)+","+oRSet.getString(6)+","+oRSet.getString(5)+","+oRSet.getString(3)+","+oRSet.getString(7)+","+oRSet.getString(8)+","+String.valueOf(oRSet.getInt(4)));

          MimePart oPart = new DBMimePart(oMultiPart, oRSet.getInt(1),oRSet.getString(2),oRSet.getString(9),oRSet.getString(6),oRSet.getString(5),oRSet.getString(3), oRSet.getString(7), oRSet.getString(8),oRSet.getInt(4));

          oMultiPart.addBodyPart(oPart );
        }

        oRSet.close();
        oRSet = null;
        oStmt.close();
        oStmt = null;

      } catch (SQLException sqle) {
        try { if (oRSet!=null) oRSet.close(); } catch (Exception e) {}
        try { if (oStmt!=null) oStmt.close(); } catch (Exception e) {}
        throw new MessagingException(sqle.getMessage(), sqle);
      }
      oRetVal = oMultiPart;
    }
    else {
      oRetVal = (MimeMultipart) super.getContent();
    }

    if (DebugFile.trace) {
      DebugFile.decIdent();
        DebugFile.writeln("End DBMimeMessage.getParts() : " + (oRetVal==null ? "null" : oRetVal.getClass().getName()));
    }

    return oRetVal;
  } // getParts
View Full Code Here

      DebugFile.writeln("Begin DBMimeMessage.getText()");
      DebugFile.incIdent();
    }

    if (null==oFolder) {
      Multipart oParts = (Multipart) super.getContent();

      if (DebugFile.trace) DebugFile.writeln("MimeBodyPart = MimeMultipart.getBodyPart(0)");

      BodyPart oPart0 = oParts.getBodyPart(0);

      if (DebugFile.trace) {
        if (null==oPart0)
          DebugFile.writeln("part 0 is null");
        else
View Full Code Here

      oBuffer.append(oStrBn.getStrings());
    }
    else {
      if (DebugFile.trace) DebugFile.writeln("Multipart = DBMimeMessage.getParts()");

      Multipart oParts = getParts();

      final int iParts = oParts.getCount();

      MimePart oPart;

      int p;
      for (p=0; p<iParts && !bHasPlainTextVersion; p++) {
        oPart = (MimePart) oParts.getBodyPart(p);

        String sType = oPart.getContentType();
        if (null!=sType) sType=sType.toLowerCase();
        String sDisp = oPart.getDisposition();
        if (null==sDisp) sDisp="inline"; else if (sDisp.length()==0) sDisp="inline";

        if (DebugFile.trace) DebugFile.writeln("scanning part " + String.valueOf(p) + sDisp + " " + sType.replace('\r',' ').replace('\n', ' '));

        if (sType.startsWith("text/plain") && sDisp.equalsIgnoreCase("inline")) {
          bHasPlainTextVersion = true;
          DBMimePart.parseMimePart (oBuffer, null,
                                    getFolder().getName(),
                                    getMessageID()!=null ? getMessageID() : getContentID(),
                                    oPart, p);
        }
      }

      if (DebugFile.trace) {
        if (bHasPlainTextVersion)
          DebugFile.writeln("MimeMultipart has plain text version at part " + String.valueOf(p));
        else
          DebugFile.writeln("MimeMultipart has no plain text version, converting part 0 from HTML");
      }

      if (!bHasPlainTextVersion) {
        oPart = (MimePart) oParts.getBodyPart(0);
        StringBuffer oHtml = new StringBuffer();
        DBMimePart.parseMimePart (oHtml, null, getFolder().getName(), getMessageID()!=null ? getMessageID() : getContentID(), oPart, 0);

        Parser oPrsr = Parser.createParser(oHtml.toString(), getEncoding());
        StringBean oStrBn = new StringBean();
View Full Code Here

      oPipe.between(oInStrm, oOutStrm);
      oInStrm.close();
      oMBox.close();
    }
    else {
      Multipart oDBParts = getParts();
      MimeMultipart oMimeParts = new MimeMultipart();

      for (int p=0;p<oDBParts.getCount(); p++) {
        oMimeParts.addBodyPart(oDBParts.getBodyPart(p));
        super.setContent(oMimeParts);
      }
      super.writeTo(oOutStrm);
    }
    if (DebugFile.trace)  {
View Full Code Here

  if (sEncoding==null) sEncoding="ASCII";

    SMTPMessage oSentMessage = new SMTPMessage(oMailSession);

    Multipart oDraftParts = getParts();
    final int iDraftParts = oDraftParts.getCount();

    if (DebugFile.trace) DebugFile.writeln("Multipart.getCount() = " + String.valueOf(iDraftParts));

    MimeBodyPart oMsgPlainText = new MimeBodyPart();
    MimeMultipart oSentMsgParts = new MimeMultipart("mixed");

    if (sContentType.equalsIgnoreCase("html")) {

      MimeMultipart oHtmlRelated  = new MimeMultipart("related");
      MimeMultipart oTextHtmlAlt  = new MimeMultipart("alternative");

      // ************************************************************************
      // Replace image CIDs

      String sSrc, sCid, sText = "";

      Parser oPrsr = Parser.createParser(sBody, getEncoding());

      // String sCid, sSrc;

      HtmlMimeBodyPart oHtmBdy = new HtmlMimeBodyPart(sBody, getEncoding());

      try {

        // ****************************
        // Extract plain text from HTML
        if (DebugFile.trace) DebugFile.writeln("new StringBean()");

        StringBean oStrBn = new StringBean();

        try {
          oPrsr.visitAllNodesWith (oStrBn);
        } catch (ParserException pe) {
          if (DebugFile.trace) {
            DebugFile.writeln("org.htmlparser.util.ParserException " + pe.getMessage());
          }
          throw new MessagingException(pe.getMessage(), pe);
        }

        sText = oStrBn.getStrings();

        oStrBn = null;

        // *******************************
        // Set plain text alternative part

        oMsgPlainText.setDisposition("inline");
        oMsgPlainText.setText(sText,Charset.forName(sEncoding).name(),"plain");
        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/alternative).addBodyPart(text/plain)");
        oTextHtmlAlt.addBodyPart(oMsgPlainText);

        // *****************************************
        // Iterate images from HTML and replace CIDs

    if (bAttachInlineImages) {
      sBody = oHtmBdy.addPreffixToImgSrc("cid:");         
    } // fi (bAttachInlineImages)
      }
      catch (ParserException pe) {
        if (DebugFile.trace) {
          DebugFile.writeln("org.htmlparser.util.ParserException " + pe.getMessage());
        }
        throw new MessagingException(pe.getMessage(), pe);
      }
      // End replace image CIDs
      // ************************************************************************


      // ************************************************************************
      // Some defensive programming: ensure that all src="..." attributes point
      // either to an absolute http:// URL or to a cid:
      oHtmBdy.setHtml (sBody);
      ArrayList<String> aLocalUrls = oHtmBdy.extractLocalUrls();
      if (aLocalUrls.size()>0) {
        if (DebugFile.trace) {
          DebugFile.writeln("HTML body part contains local references to external resources");
          for (String i : aLocalUrls) {
            DebugFile.writeln(i);
          }
          DebugFile.write(sBody+"\n");
        }
        throw new MessagingException("HTML body part "+(sId==null ? "" : "of message"+sId)+" contains local references to external resources such as "+aLocalUrls.get(0));
      } // aLocalUrls != {}

     
      // ************************************************************************
      // Add HTML related images

      if (oHtmBdy.getImagesCids().isEmpty()) {
          // Set HTML part
          MimeBodyPart oMsgHtml = new MimeBodyPart();
          oMsgHtml.setDisposition("inline");

          // ****************************************************************************
          // Replace <!--WEBBEACON SRC="http://..."--> tag by an <IMG SRC="http://..." />

        try {
            iWebBeaconStart = Gadgets.indexOfIgnoreCase(sBody,"<!--WEBBEACON", 0);
            if (iWebBeaconStart>0) {
              iSrcTagStart = sBody.indexOf('"', iWebBeaconStart+13);
              iSrcTagEnd = sBody.indexOf('"', iSrcTagStart+1);
              iWebBeaconEnd = sBody.indexOf("-->", iWebBeaconStart+13);
              if (iWebBeaconEnd>0) {
            sBody = sBody.substring(0,iWebBeaconStart)+"<IMG SRC=\""+sBody.substring(iSrcTagStart+1,iSrcTagEnd)+"\" WIDTH=\"1\" HEIGHT=\"1\" BORDER=\"0\" ALT=\"\" />"+sBody.substring(iWebBeaconEnd+3);
              }
            }
        } catch (Exception malformedwebbeacon) {
          if (DebugFile.trace) DebugFile.writeln("Malformed Web Beacon");
        }
         
          oMsgHtml.setText(sBody,Charset.forName(sEncoding).name(),"html");
          oTextHtmlAlt.addBodyPart(oMsgHtml);
         
      } else {

        // Set HTML text related part

        MimeBodyPart oMsgHtmlText = new MimeBodyPart();
        oMsgHtmlText.setDisposition("inline");

        // ****************************************************************************
        // Replace <!--WEBBEACON SRC="http://..."--> tag by an <IMG SRC="http://..." />
         
        try {
          iWebBeaconStart = Gadgets.indexOfIgnoreCase(sBody,"<!--WEBBEACON", 0);
          if (iWebBeaconStart>0) {
            iSrcTagStart = sBody.indexOf('"', iWebBeaconStart+13);
            iSrcTagEnd = sBody.indexOf('"', iSrcTagStart+1);
            iWebBeaconEnd = sBody.indexOf("-->", iWebBeaconStart+13);
            if (iWebBeaconEnd>0) {
            sBody = sBody.substring(0,iWebBeaconStart)+"<IMG SRC=\""+sBody.substring(iSrcTagStart+1,iSrcTagEnd)+"\" WIDTH=\"1\" HEIGHT=\"1\" BORDER=\"0\" ALT=\"\" />"+sBody.substring(iWebBeaconEnd+3);
            }
          }
      } catch (Exception malformedwebbeacon) {
          if (DebugFile.trace) DebugFile.writeln("Malformed Web Beacon");
      }
       
        oMsgHtmlText.setText(sBody,Charset.forName(sEncoding).name(),"html");
        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/related).addBodyPart(text/html)");
        oHtmlRelated.addBodyPart(oMsgHtmlText);

        // Set HTML text related inline images

        Iterator oImgs = oHtmBdy.getImagesCids().keySet().iterator();

        while (oImgs.hasNext()) {
          BodyPart oImgBodyPart = new MimeBodyPart();

          sSrc = (String) oImgs.next();
          sCid = (String) oHtmBdy.getImagesCids().get(sSrc);

          if (sSrc.startsWith("www."))
            sSrc = "http://" + sSrc;

          if (sSrc.startsWith("http://") || sSrc.startsWith("https://")) {
            oImgBodyPart.setDataHandler(new DataHandler(new URL(Hosts.resolve(sSrc))));
          }
          else {
            oImgBodyPart.setDataHandler(new DataHandler(new FileDataSource(sSrc)));
          }
     
      if (sSrc.endsWith(".png")) oImgBodyPart.setHeader("Content-Type", "image/png;name="+sCid);
          oImgBodyPart.setDisposition("inline");
          oImgBodyPart.setHeader("Content-ID", sCid);
          oImgBodyPart.setFileName(sCid);

          // Add image to multi-part
          if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/related).addBodyPart("+sCid+")");
          oHtmlRelated.addBodyPart(oImgBodyPart);
        } // wend

        // Set html text alternative part (html text + inline images)
        MimeBodyPart oTextHtmlRelated = new MimeBodyPart();
        oTextHtmlRelated.setContent(oHtmlRelated);
        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/alternative).addBodyPart(multipart/related)");
        oTextHtmlAlt.addBodyPart(oTextHtmlRelated);
      }

      // ************************************************************************
      // Create message to be sent and add main text body to it

      if (0==iDraftParts) {
        oSentMessage.setContent(oTextHtmlAlt);
      } else {
        MimeBodyPart oMixedPart = new MimeBodyPart();
        oMixedPart.setContent(oTextHtmlAlt);
        oSentMsgParts.addBodyPart(oMixedPart);
      }

    } else { // (sContentType=="plain")

      // *************************************************
      // If this is a plain text message just add the text

      if (0==iDraftParts) {
        oSentMessage.setText(sBody, Charset.forName(sEncoding).name(), "plain");
      } else {
        oMsgPlainText.setDisposition("inline");
        oMsgPlainText.setText(sBody,Charset.forName(sEncoding).name(),"plain");
        if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/mixed).addBodyPart(text/plain)");
        oSentMsgParts.addBodyPart(oMsgPlainText);
      }
    }
    // fi (sContentType=="html")

    // ************************************************************************
    // Add attachments to message to be sent

    if (iDraftParts>0) {

      for (int p=0; p<iDraftParts; p++) {
        DBMimePart oPart = (DBMimePart) oDraftParts.getBodyPart(p);

        String sDisposition = oPart.getDisposition();
        if (sDisposition==null)
          sDisposition = "inline";
        else if (sDisposition.equals("reference") || sDisposition.equals("pointer"))
View Full Code Here

    FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
    DataHandler dh = new DataHandler(fileAttachment);
    bp2.setDataHandler(dh);
    bp2.setFileName(fileAttachment.getName());

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bp1);
    multipart.addBodyPart(bp2);

    baseMsg.setFrom(new InternetAddress("Ted <ted@home.com>"));
    baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress(
        "success@subethamail.org"));
    baseMsg.setSubject("Test Big attached file message");
View Full Code Here

      resultText.append("-------------------------------------------------------------").append("\n");

      // multipart or not multipart
      if (message.getContent() instanceof Multipart) {
        //contentType = "multipart";
        Multipart mp = (Multipart) message.getContent();

        for (int i = 0; i < mp.getCount(); i++) {
          BodyPart bp = mp.getBodyPart(i);
          String disposition = bp.getDisposition();

          if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)))) {
            attachments.add("attachment: " + bp.getFileName());
            if (bp.isMimeType("text/*")) {
              textParts.add((String) bp.getContent());
              mLog.debug("added txt from attachment: " + bp.getFileName() + " : " + bp.getContentType());
            }

          } else if (disposition == null || disposition.equals(Part.INLINE)) {

            // Plain Text oder HTML
            if (bp.isMimeType("text/*")) {
              textParts.add((String) bp.getContent());

            } else if (bp.isMimeType("multipart/*")) {
              // another bodypart container
              // we process only depth = 1 and not deeper and only text.
              Multipart mpInner = (Multipart) bp.getContent();

              for (int k = 0; k < mpInner.getCount(); k++) {
                BodyPart bpInner = mpInner.getBodyPart(k);

                if (bpInner != null && (bpInner.getDisposition() == null ||
                        bpInner.getDisposition().equals(Part.INLINE))) {

                  if (bpInner.isMimeType("text/*")) {
View Full Code Here

TOP

Related Classes of javax.mail.Multipart

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.