Package javax.mail.internet

Examples of javax.mail.internet.MimeBodyPart


  if (sEncoding==null) sEncoding = "ASCII";
  String sCharEnc = Charset.forName(sEncoding).name();
   
  SMTPMessage oSentMessage = new SMTPMessage(getSmtpSession());

  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

    HashMap oDocumentImages = new HashMap(23);

    StringSubstitution oSrcSubs = new StringSubstitution();

    Parser oPrsr = Parser.createParser(sHtmlBody, sEncoding);

    String sCid, sSrc;

    try {

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

          StringBean oStrBn = new StringBean();

          try {
            oPrsr.visitAllNodesWith (oStrBn);
          } catch (ParserException pe) {
          throw new MessagingException(pe.getMessage(), pe);
          }

          sTextBody = oStrBn.getStrings();

          oStrBn = null;
      } // fi (sTextBody==null)

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

      oMsgPlainText.setDisposition("inline");
      oMsgPlainText.setText(sTextBody, sCharEnc, "plain");
      // oMsgPlainText.setContent(sTextBody, "text/plain; charset="+sCharEnc);
      if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/alternative).addBodyPart(text/plain)");
      oTextHtmlAlt.addBodyPart(oMsgPlainText);

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

      NodeList oCollectionList = new NodeList();
      TagNameFilter oImgFilter = new TagNameFilter ("IMG");
      for (NodeIterator e = oPrsr.elements(); e.hasMoreNodes();)
        e.nextNode().collectInto(oCollectionList, oImgFilter);

      final int nImgs = oCollectionList.size();

      if (DebugFile.trace) DebugFile.writeln("NodeList.size() = " + String.valueOf(nImgs));

      for (int i=0; i<nImgs; i++) {

        sSrc = ((ImageTag) oCollectionList.elementAt(i)).extractImageLocn();

        // Keep a reference to every related image name so that the same image is not included twice in the message
        if (!oDocumentImages.containsKey(sSrc)) {

          // Find last slash from image url
          int iSlash = sSrc.lastIndexOf('/');

          // Take image name
          if (iSlash>=0) {
            while (sSrc.charAt(iSlash)=='/') { if (++iSlash==sSrc.length()) break; }
            sCid = sSrc.substring(iSlash);
          }
          else {
            sCid = sSrc;
          }

          //String sUid = Gadgets.generateUUID();
          //sCid = sUid.substring(0,12)+"$"+sUid.substring(12,20)+"$"+sUid.substring(20,28)+"@hipergate.org";

          if (DebugFile.trace) DebugFile.writeln("HashMap.put("+sSrc+","+sCid+")");

          oDocumentImages.put(sSrc, sCid);
        } // fi (!oDocumentImages.containsKey(sSrc))

        try {
          Pattern oPattern = oCompiler.compile(sSrc, Perl5Compiler.SINGLELINE_MASK);
          oSrcSubs.setSubstitution("cid:"+oDocumentImages.get(sSrc));
          if (DebugFile.trace) DebugFile.writeln("Util.substitute([PatternMatcher],"+ sSrc + ",cid:"+oDocumentImages.get(sSrc)+",...)");
          sHtmlBody = Util.substitute(oMatcher, oPattern, oSrcSubs, sHtmlBody);
        } catch (MalformedPatternException neverthrown) { }

      } // next
    }
    catch (ParserException pe) {
      if (DebugFile.trace) {
        DebugFile.writeln("org.htmlparser.util.ParserException " + pe.getMessage());
      }
    }
    // End replace image CIDs
    // ************************************************************************

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

    if (oDocumentImages.isEmpty()) {
        // Set HTML part
        MimeBodyPart oMsgHtml = new MimeBodyPart();
        oMsgHtml.setDisposition("inline");
        oMsgHtml.setText(sHtmlBody, sCharEnc, "html");
        // oMsgHtml.setContent(sHtmlBody, "text/html; charset="+sCharEnc);
        oTextHtmlAlt.addBodyPart(oMsgHtml);
    } else {

      // Set HTML text related part

      MimeBodyPart oMsgHtmlText = new MimeBodyPart();
      oMsgHtmlText.setDisposition("inline");
      oMsgHtmlText.setText(sHtmlBody, sCharEnc, "html");
      // oMsgHtmlText.setContent(sHtmlBody, "text/html; charset="+sCharEnc);
      if (DebugFile.trace) DebugFile.writeln("MimeBodyPart(multipart/related).addBodyPart(text/html)");
      oHtmlRelated.addBodyPart(oMsgHtmlText);

      // Set HTML text related inline images

      Iterator oImgs = oDocumentImages.keySet().iterator();

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

        sSrc = (String) oImgs.next();
        sCid = (String) oDocumentImages.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((sBasePath==null ? "" : sBasePath)+sSrc)));
        }

        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 (aAttachmentsPath==null) {
      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 (aAttachmentsPath==null) {
      oSentMessage.setText(sTextBody, sCharEnc);
    } else {
      oMsgPlainText.setDisposition("inline");
      oMsgPlainText.setText(sTextBody, sCharEnc, "plain");
      //oMsgPlainText.setContent(sTextBody, "text/plain; charset="+sCharEnc);
      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 (aAttachmentsPath!=null) {
    final int nAttachments = aAttachmentsPath.length;

    FileSystem oFS = new FileSystem();
    for (int p=0; p<nAttachments; p++) {
      String sFilePath = aAttachmentsPath[p];
      if (sBasePath!=null) {
        if (!sFilePath.startsWith(sBasePath))
          sFilePath = sBasePath + sFilePath;
      }
      File oFile = new File(sFilePath);
     
      MimeBodyPart oAttachment = new MimeBodyPart();
      oAttachment.setDisposition("attachment");
      oAttachment.setFileName(oFile.getName());
      oAttachment.setHeader("Content-Transfer-Encoding", "base64");

      ByteArrayDataSource oDataSrc;
      try {
        oDataSrc = new ByteArrayDataSource(oFS.readfilebin(sFilePath), "application/octet-stream");
      } catch (com.enterprisedt.net.ftp.FTPException ftpe) {
      throw new IOException(ftpe.getMessage());
      }
      oAttachment.setDataHandler(new DataHandler(oDataSrc));
      oSentMsgParts.addBodyPart(oAttachment);
    } // next
    oSentMessage.setContent(oSentMsgParts);
  } // fi (iDraftParts>0)

View Full Code Here


         tos[0] = to;
         message.setRecipients(Message.RecipientType.TO, tos);
         message.setSubject(subject, encoding);

         // MimeBodyPart mbp1 = new MimeBodyPart(attachment);
         MimeBodyPart mbp1 = new MimeBodyPart(); // "application/x-any"
         // "application/xmlBlaster-xbformat"
         DataSource ds = new ByteArrayDataSource(attachment,
               "application/xmlBlaster-xbformat");
         mbp1.setDataHandler(new DataHandler(ds));
         mbp1.setFileName(attachmentName);
         // mbp1.getContentType(); "application/octet-stream"

         // create the Multipart and add its parts to it
         Multipart mp = new MimeMultipart();
         mp.addBodyPart(mbp1);

         if (attachmentName2 != null) {
            MimeBodyPart mbp2 = new MimeBodyPart(); // "text/plain"
            mbp2.setText(attachment2, encoding);
            mbp2.setFileName(attachmentName2);
            mp.addBodyPart(mbp2);
         }

         // add the Multipart to the message
         message.setContent(mp);
View Full Code Here

         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
View Full Code Here

      } else if (part.isMimeType("text/html")) {
         return part.getContent().toString();
      } else if (part.isMimeType("multipart/mixed")) {
         // Find the first body part, and determine what to do then.
         MimeMultipart multipart = (MimeMultipart) part.getContent();
         MimeBodyPart firstPart = (MimeBodyPart) multipart.getBodyPart(0);
         return retrieveContent(firstPart);
      } else if (part.isMimeType("multipart/alternative")) {
         MimeMultipart multipart = (MimeMultipart) part.getContent();
         int count = multipart.getCount();
         for (int index = 0; index < count; index++) {
            MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart
                  .getBodyPart(index);
            return retrieveContent(mimeBodyPart);
         }
         return "";
      } else {
View Full Code Here

    oHeaders = new Properties();
  }

  public DBMimePart(InputStream oInStrm)
    throws MessagingException {
    oMimeBody = new MimeBodyPart(oInStrm);

    iPartId = -1;
    iSize = oMimeBody.getSize();

    oHeaders = new Properties();
View Full Code Here

          byte[] byData = oFS.readfilebin(sFilePath);
          String sContentType = oRSet.getString(7);
          if (DebugFile.trace) DebugFile.writeln("new ByteArrayDataSource("+sFilePath+", "+sContentType+")");
          ByteArrayDataSource baDataSrc = new ByteArrayDataSource(byData, sContentType);

          oMimeBody = new MimeBodyPart();
          oMimeBody.setDataHandler(new DataHandler(baDataSrc));
        }
        else if (id_disposition.equals("pointer")) {
          if (DebugFile.trace) DebugFile.writeln("content disposition is pointer");
          lPos = oRSet.getBigDecimal(3).longValue();
          sFilePath = oRSet.getString(4);
          iLen = oRSet.getInt(5);
          lOff = oRSet.getBigDecimal(6).longValue();
          MboxFile oMbox = new MboxFile(sFilePath, MboxFile.READ_ONLY);
          InputStream oPartStrm = oMbox.getPartAsStream(lPos, lOff, iLen);
          oMimeBody = new MimeBodyPart(oPartStrm);
        }
        else if ((oFldr.getType()&DBFolder.MODE_BLOB)!=0) {
          if (DebugFile.trace) DebugFile.writeln("content disposition is " + id_disposition + " mode is BLOB");
          if (DebugFile.trace) DebugFile.writeln("new MimeBodyPart([InputStream])");
          oMimeBody = new MimeBodyPart(oRSet.getBinaryStream(8));
        }
        else {
          if (DebugFile.trace) DebugFile.writeln("content disposition is " + id_disposition + " mode is MBOX");
          BigDecimal oPosition;
          Object oLenPart, oOffset;

          oPosition = oRSet.getBigDecimal(3);
          if (!oRSet.wasNull()) lPos = Long.parseLong(oPosition.toString()); else lPos = -1;
          oLenPart = oRSet.getObject(5);
          if (!oRSet.wasNull()) iLen = Integer.parseInt(oLenPart.toString()); else iLen = -1;
          oOffset = oRSet.getObject(6);
          if (!oRSet.wasNull()) lOff = Long.parseLong(oOffset.toString()); else lOff = -1;

          if (lPos!=-1) {
            if (iLen==-1) throw new MessagingException("Part " + String.valueOf(iPartId) + " length not set at k_mime_parts table for message "+getMessage().getMessageGuid());
            if (lOff==-1 ) throw new MessagingException("Part " + String.valueOf(iPartId) + " offset not set at k_mime_parts table for message "+getMessage().getMessageGuid());

            if (DebugFile.trace) DebugFile.writeln("new MboxFile("+((DBFolder)getMessage().getFolder()).getFile()+")");

            MboxFile oMbox = new MboxFile(((DBFolder)getMessage().getFolder()).getFile(), MboxFile.READ_ONLY);

            InputStream oInStrm = oMbox.getPartAsStream(lPos, lOff, iLen);
            oMimeBody = new MimeBodyPart(oInStrm);
            oInStrm.close();

            oMbox.close();
          }
          else {
View Full Code Here

          if (oRSet.wasNull()) throw new SQLException ("nu_offset column may not be null for parts with pointer disposition", "22002", 22002);
          if (DebugFile.trace) DebugFile.writeln("new File(" + sTmpFilePath + ")");
          File oFile = new File (sTmpFilePath);
          MboxFile oMbox = new MboxFile(oFile, MboxFile.READ_ONLY);
          oRetVal = oMbox.getPartAsStream(oMsgPos.longValue(), oPartOffset.longValue(), Integer.parseInt(oPartLen.toString()));
          oMimeBody = new MimeBodyPart(oRetVal);
          oRetVal.close();
        }
        else if ((oFldr.getType()&DBFolder.MODE_BLOB)!=0) {
          if (DebugFile.trace) DebugFile.writeln("new MimeBodyPart(ResultSet.getBinaryStream(...))");
          oMimeBody = new MimeBodyPart(oRSet.getBinaryStream(7));
        }
        else {
          BigDecimal oPosition;
          Object oMsgNum, oLenPart, oOffset;
          long iPosition = -1, iOffset = -1;
          int iLenPart = -1;

          oMsgNum = oRSet.getObject(1);
          oPosition = oRSet.getBigDecimal(2);
          if (!oRSet.wasNull()) iPosition = Long.parseLong(oPosition.toString());
          oLenPart = oRSet.getObject(5);
          if (!oRSet.wasNull()) iLenPart = oRSet.getInt(5);
          oOffset = oRSet.getObject(6);
          if (!oRSet.wasNull()) iOffset = oRSet.getInt(6);

          if (iPosition!=-1) {
            if (iLenPart==-1) throw new MessagingException("Part " + String.valueOf(iPartId) + " length not set at k_mime_parts table");
            if (iOffset==-1 ) throw new MessagingException("Part " + String.valueOf(iPartId) + " offset not set at k_mime_parts table");

            if (DebugFile.trace) DebugFile.writeln("new MboxFile("+((DBFolder)getMessage().getFolder()).getFile()+")");

            MboxFile oMbox = new MboxFile(((DBFolder)getMessage().getFolder()).getFile(), MboxFile.READ_ONLY);

            oMimeBody = new MimeBodyPart(oMbox.getPartAsStream(iPosition, iOffset, iLenPart));

            oMbox.close();
          }
          else {
            if (DebugFile.trace) DebugFile.decIdent();
View Full Code Here

    ResultSet oRSet = oStmt.executeQuery();

    if (oRSet.next()) {

      oMimeBody = new MimeBodyPart (oRSet.getBinaryStream(4));

      oRSet.close();
      oStmt.close();

      StringBuffer oText = new StringBuffer();
View Full Code Here

  // ---------------------------------------------------------------------------

  public static MimePart getMessagePart (MimePart oPart, int nPart)
    throws MessagingException, IOException, UnsupportedEncodingException {

    MimeBodyPart oNext = null;
    MimeMultipart oAlt;
    String sType;
    MimePart oRetVal;

    sType = oPart.getContentType().toUpperCase();

    if (DebugFile.trace) DebugFile.writeln("Begin DBMimePart.getMessagePart("+String.valueOf(nPart)+", "+sType.replace('\n',' ').replace('\r',' ')+")");

    if (sType.startsWith("MESSAGE/RFC822")) {
      DBMimeMessage oAttachment = new  DBMimeMessage((MimeMessage) oPart.getContent());
      oRetVal = oAttachment.getBody ();
    }
    else if (sType.startsWith("MULTIPART/ALTERNATIVE") || sType.startsWith("MULTIPART/RELATED") || sType.startsWith("MULTIPART/SIGNED")) {
      oAlt = (MimeMultipart) oPart.getContent();

      int iAlt = 0;
      String[] aPreferred = {"TEXT/HTML","TEXT"};
      boolean bFound = false;

      while (iAlt<aPreferred.length && !bFound) {
        for (int q=0; q<oAlt.getCount(); q++) {
          oNext = (MimeBodyPart) oAlt.getBodyPart(q);
          if (DebugFile.trace && (iAlt==0)) DebugFile.writeln("  " + oNext.getContentType().toUpperCase().replace('\n',' ').replace('\r',' ') + " ID=" + oNext.getContentID());
          bFound = oNext.getContentType().toUpperCase().startsWith(aPreferred[iAlt]);
          if (bFound) break;
        } // next
        iAlt++;
      } // wend
View Full Code Here

  public static int parseMimePart (StringBuffer oStrBuff, LinkedList oAttachments,
                                   String sFolder, String sMsgId,
                                   MimePart oPart, int nPart)
    throws MessagingException, IOException, UnsupportedEncodingException {

    MimeBodyPart oNext = null;
    MimeMultipart oAlt;
    String sType;
    int iRetVal;
    String sContent;
View Full Code Here

TOP

Related Classes of javax.mail.internet.MimeBodyPart

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.