Example usage for javax.mail.internet MimePart getContentID

List of usage examples for javax.mail.internet MimePart getContentID

Introduction

In this page you can find the example usage for javax.mail.internet MimePart getContentID.

Prototype

public String getContentID() throws MessagingException;

Source Link

Document

Get the Content-ID of this part.

Usage

From source file:mailbox.CreationViaEmail.java

/**
 * Returns true if the given part is root part.
 *
 * The given part is root part, if the part is the first one and the given
 * root id is not defined or the content id of the part equals to the given
 * root id./*from w  ww. j a va 2  s  .c  o m*/
 *
 * @param part
 * @param nthPart
 * @param rootId
 * @return
 * @throws MessagingException
 */
private static boolean isRootPart(MimePart part, int nthPart, String rootId) throws MessagingException {
    return (rootId == null && nthPart == 0) || StringUtils.equals(part.getContentID(), rootId);
}

From source file:mailbox.CreationViaEmail.java

private static Map<String, Attachment> saveAttachments(Collection<MimePart> partsToAttach, Resource container)
        throws MessagingException, IOException, NoSuchAlgorithmException {
    Map<String, Attachment> result = new HashMap<>();

    for (MimePart partToAttach : partsToAttach) {
        Attachment attachment = saveAttachment(partToAttach, container);
        if (partToAttach.getContentID() != null) {
            String cid = partToAttach.getContentID().trim();
            cid = cid.replace("<", "");
            cid = cid.replace(">", "");
            result.put(cid, attachment);
        }// ww  w  . j a va2 s .c o  m
    }

    return result;
}

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Construct simple body part from binary data just adding file name as content.
 * @param mediaPart//  www.j av  a 2 s.c  o m
 * @param contentType
 * @return
 * @throws IOException
 */
protected BodyPart handleBinaryPart(MimePart mediaPart, String contentType)
        throws IOException, MessagingException {
    String contentId = mediaPart.getContentID() != null ? "(" + mediaPart.getContentID() + ")" : "";
    return new BodyPart(mediaPart.getFileName() + contentId, contentType);
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Get a textual description of a part./*from   w  ww.  ja v  a2 s . c  om*/
 *
 * @param part The part to interogate
 * @param buf a string buffer for the description
 * @param prefix a prefix for each line of the description
 * @param recurse boolean specifying wether to recurse through sub-parts or
 *        not
 *
 * @return StringBuffer containing the description of the part
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static StringBuffer getPartDescription(Part part, StringBuffer buf, String prefix, boolean recurse)
        throws MessagingException {
    if (buf == null) {
        return buf;
    }

    ContentType xctype = MessageUtilities.getContentType(part);

    String xvalue = xctype.toString();
    buf.append(prefix);
    buf.append("Content-Type: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDisposition();
    buf.append(prefix);
    buf.append("Content-Disposition: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = part.getDescription();
    buf.append(prefix);
    buf.append("Content-Description: ");
    buf.append(xvalue);
    buf.append('\n');

    xvalue = MessageUtilities.getFileName(part);
    buf.append(prefix);
    buf.append("Content-Filename: ");
    buf.append(xvalue);
    buf.append('\n');

    if (part instanceof MimePart) {
        MimePart xmpart = (MimePart) part;
        xvalue = xmpart.getContentID();
        buf.append(prefix);
        buf.append("Content-ID: ");
        buf.append(xvalue);
        buf.append('\n');

        String[] langs = xmpart.getContentLanguage();

        if (langs != null) {
            buf.append(prefix);
            buf.append("Content-Language: ");

            for (int pi = 0; pi < langs.length; ++pi) {
                if (pi > 0) {
                    buf.append(", ");
                }

                buf.append(xvalue);
            }

            buf.append('\n');
        }

        xvalue = xmpart.getContentMD5();
        buf.append(prefix);
        buf.append("Content-MD5: ");
        buf.append(xvalue);
        buf.append('\n');

        xvalue = xmpart.getEncoding();
        buf.append(prefix);
        buf.append("Content-Encoding: ");
        buf.append(xvalue);
        buf.append('\n');
    }

    buf.append('\n');

    if (recurse && xctype.match("multipart/*")) {
        Multipart xmulti = (Multipart) MessageUtilities.getPartContent(part);

        int xparts = xmulti.getCount();

        for (int xindex = 0; xindex < xparts; xindex++) {
            MessageUtilities.getPartDescription(xmulti.getBodyPart(xindex), buf, (prefix + "   "), true);
        }
    }

    return buf;
}

From source file:com.zimbra.cs.imap.ImapMessage.java

static void serializeStructure(PrintStream ps, MimeMessage root, boolean extensions)
        throws IOException, MessagingException {
    LinkedList<LinkedList<MPartInfo>> queue = new LinkedList<LinkedList<MPartInfo>>();
    LinkedList<MPartInfo> level = new LinkedList<MPartInfo>();
    level.add(Mime.getParts(root).get(0));
    queue.add(level);//from  w  w w .ja  v  a 2s .c om

    boolean pop = false;
    while (!queue.isEmpty()) {
        level = queue.getLast();
        if (level.isEmpty()) {
            queue.removeLast();
            pop = true;
            continue;
        }

        MPartInfo mpi = level.getFirst();
        MimePart mp = mpi.getMimePart();
        boolean hasChildren = mpi.getChildren() != null && !mpi.getChildren().isEmpty();

        // we used to force unset charsets on text/plain parts to US-ASCII, but that always seemed unwise...
        ContentType ctype = new ContentType(mp.getHeader("Content-Type", null))
                .setContentType(mpi.getContentType());
        String primary = nATOM(ctype.getPrimaryType()), subtype = nATOM(ctype.getSubType());

        if (!pop)
            ps.write('(');
        if (primary.equals("\"MULTIPART\"")) {
            if (!pop) {
                // 7.4.2: "Multiple parts are indicated by parenthesis nesting.  Instead of a body type
                //         as the first element of the parenthesized list, there is a sequence of one
                //         or more nested body structures.  The second element of the parenthesized
                //         list is the multipart subtype (mixed, digest, parallel, alternative, etc.)."
                if (!hasChildren) {
                    ps.print("NIL");
                } else {
                    queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren()));
                    continue;
                }
            }
            ps.write(' ');
            ps.print(subtype);
            if (extensions) {
                // 7.4.2: "Extension data follows the multipart subtype.  Extension data is never
                //         returned with the BODY fetch, but can be returned with a BODYSTRUCTURE
                //         fetch.  Extension data, if present, MUST be in the defined order.  The
                //         extension data of a multipart body part are in the following order:
                //         body parameter parenthesized list, body disposition, body language,
                //         body location"
                ps.write(' ');
                nparams(ps, ctype);
                ps.write(' ');
                ndisposition(ps, mp.getHeader("Content-Disposition", null));
                ps.write(' ');
                nlist(ps, mp.getContentLanguage());
                ps.write(' ');
                nstring(ps, mp.getHeader("Content-Location", null));
            }
        } else {
            if (!pop) {
                // 7.4.2: "The basic fields of a non-multipart body part are in the following order:
                //         body type, body subtype, body parameter parenthesized list, body id, body
                //         description, body encoding, body size."
                String cte = mp.getEncoding();
                cte = (cte == null || cte.trim().equals("") ? "7bit" : cte);
                aSTRING(ps, ctype.getPrimaryType());
                ps.write(' ');
                aSTRING(ps, ctype.getSubType());
                ps.write(' ');
                nparams(ps, ctype);
                ps.write(' ');
                nstring(ps, mp.getContentID());
                ps.write(' ');
                nstring2047(ps, mp.getDescription());
                ps.write(' ');
                aSTRING(ps, cte);
                ps.write(' ');
                ps.print(Math.max(mp.getSize(), 0));
            }
            boolean rfc822 = primary.equals("\"MESSAGE\"") && subtype.equals("\"RFC822\"");
            if (rfc822) {
                // 7.4.2: "A body type of type MESSAGE and subtype RFC822 contains, immediately
                //         after the basic fields, the envelope structure, body structure, and
                //         size in text lines of the encapsulated message."
                if (!pop) {
                    if (!hasChildren) {
                        ps.print(" NIL NIL");
                    } else {
                        MimeMessage mm = (MimeMessage) mpi.getChildren().get(0).getMimePart();
                        ps.write(' ');
                        serializeEnvelope(ps, mm);
                        ps.write(' ');
                        queue.addLast(new LinkedList<MPartInfo>(mpi.getChildren()));
                        continue;
                    }
                }
                ps.write(' ');
                ps.print(getLineCount(mp));
            } else if (primary.equals("\"TEXT\"")) {
                // 7.4.2: "A body type of type TEXT contains, immediately after the basic fields, the
                //         size of the body in text lines.  Note that this size is the size in its
                //         content transfer encoding and not the resulting size after any decoding."
                ps.write(' ');
                ps.print(getLineCount(mp));
            }
            if (extensions) {
                // 7.4.2: "Extension data follows the basic fields and the type-specific fields
                //         listed above.  Extension data is never returned with the BODY fetch,
                //         but can be returned with a BODYSTRUCTURE fetch.  Extension data, if
                //         present, MUST be in the defined order.  The extension data of a
                //         non-multipart body part are in the following order: body MD5, body
                //         disposition, body language, body location"
                ps.write(' ');
                nstring(ps, mp.getContentMD5());
                ps.write(' ');
                ndisposition(ps, mp.getHeader("Content-Disposition", null));
                ps.write(' ');
                nlist(ps, mp.getContentLanguage());
                ps.write(' ');
                nstring(ps, mp.getHeader("Content-Location", null));
            }
        }
        ps.write(')');

        level.removeFirst();
        pop = false;
    }
}

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Parses key data items from a MimeMessage for seperate storage.
 * TODO this is a mess, and should be completely revamped.
 *///from w ww .  jav  a2  s. c  o m
void parseMimePart(MimePart part) throws MessagingException {
    size = GreenMailUtil.getBody(part).length();

    // Section 1 - Message Headers
    if (part instanceof MimeMessage) {
        try {
            subject = ((MimeMessage) part).getSubject();
        } catch (MessagingException me) {
            //                if (DEBUG) getLogger().debug("Messaging Exception for getSubject: " + me);
        }
    }
    try {
        from = part.getHeader("From");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(From): " + me);
    }
    try {
        sender = part.getHeader("Sender");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Sender): " + me);
    }
    try {
        replyTo = part.getHeader("Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Reply To): " + me);
    }
    try {
        to = part.getHeader("To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        cc = part.getHeader("Cc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        bcc = part.getHeader("Bcc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        inReplyTo = part.getHeader("In Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(In Reply To): " + me);
    }
    try {
        date = part.getHeader("Date");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Date): " + me);
    }
    try {
        messageID = part.getHeader("Message-ID");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(messageID): " + me);
    }
    String contentTypeLine = null;
    try {
        contentTypeLine = part.getContentType();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentType(): " + me);
    }
    if (contentTypeLine != null) {
        decodeContentType(contentTypeLine);
    }
    try {
        contentID = part.getContentID();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentUD(): " + me);
    }
    try {
        contentDesc = part.getDescription();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getDescription(): " + me);
    }
    try {
        contentEncoding = part.getEncoding();
        // default value.
        if (contentEncoding == null) {
            contentEncoding = "7BIT";
        }
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getEncoding(): " + me);
    }

    try {
        //            contentDisposition = part.getDisposition();
        contentDisposition = Header.create(part.getHeader("Content-Disposition"));
    } catch (MessagingException me) {
        if (log.isDebugEnabled()) {
            log.debug("Can not create content disposition for part " + part, me);
        }
    }

    try {
        // TODO this doesn't work
        lineCount = getLineCount(part);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can not get line count for part " + part, e);
        }
    }

    // Recurse through any embedded parts
    if (primaryType.equalsIgnoreCase(MULTIPART)) {
        MimeMultipart container;
        try {
            container = (MimeMultipart) part.getContent();
            int count = container.getCount();
            parts = new SimpleMessageAttributes[count];
            for (int i = 0; i < count; i++) {
                BodyPart nextPart = container.getBodyPart(i);

                if (nextPart instanceof MimePart) {
                    SimpleMessageAttributes partAttrs = new SimpleMessageAttributes(null, receivedDate);
                    partAttrs.parseMimePart((MimePart) nextPart);
                    parts[i] = partAttrs;

                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not recurse through multipart content", e);
            }
        }
    } else if (primaryType.equalsIgnoreCase("message")) {
        if (secondaryType.equalsIgnoreCase("RFC822")) {
            //try {

            /*
            MimeMessageWrapper message = new MimeMessageWrapper(part.getInputStream());
            SimpleMessageAttributes msgAttrs = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message);
                    
            if (part instanceof MimeMessage) {
            Comments out because I don't know what it should do here
            MimeMessage msg1 = (MimeMessage) part;
            MimeMessageWrapper message2 = new MimeMessageWrapper(msg1);
            SimpleMessageAttributes msgAttrs2 = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message2);
            }
                    
            parts = new SimpleMessageAttributes[1];
            parts[0] = msgAttrs;
            */
            //} catch (Exception e) {
            //getLogger().error("Error interpreting a message/rfc822: " + e);
            //e.printStackTrace();
            //}

            // TODO: Warn till fixed!
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        } else {
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        }
    }
}

From source file:davmail.imap.ImapConnection.java

protected void appendBodyStructure(StringBuilder buffer, MimePart bodyPart)
        throws IOException, MessagingException {
    String contentType = MimeUtility.unfold(bodyPart.getContentType());
    int slashIndex = contentType.indexOf('/');
    if (slashIndex < 0) {
        throw new DavMailException("EXCEPTION_INVALID_CONTENT_TYPE", contentType);
    }//w  ww.  ja va2 s.  com
    String type = contentType.substring(0, slashIndex).toUpperCase();
    buffer.append("(\"").append(type).append("\" \"");
    int semiColonIndex = contentType.indexOf(';');
    if (semiColonIndex < 0) {
        buffer.append(contentType.substring(slashIndex + 1).toUpperCase()).append("\" NIL");
    } else {
        // extended content type
        buffer.append(contentType.substring(slashIndex + 1, semiColonIndex).trim().toUpperCase()).append('\"');
        int charsetindex = contentType.indexOf("charset=");
        int nameindex = contentType.indexOf("name=");
        if (charsetindex >= 0 || nameindex >= 0) {
            buffer.append(" (");

            if (charsetindex >= 0) {
                buffer.append("\"CHARSET\" ");
                int charsetSemiColonIndex = contentType.indexOf(';', charsetindex);
                int charsetEndIndex;
                if (charsetSemiColonIndex > 0) {
                    charsetEndIndex = charsetSemiColonIndex;
                } else {
                    charsetEndIndex = contentType.length();
                }
                String charSet = contentType.substring(charsetindex + "charset=".length(), charsetEndIndex);
                if (!charSet.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(charSet.trim().toUpperCase());
                if (!charSet.endsWith("\"")) {
                    buffer.append('"');
                }
            }

            if (nameindex >= 0) {
                if (charsetindex >= 0) {
                    buffer.append(' ');
                }

                buffer.append("\"NAME\" ");
                int nameSemiColonIndex = contentType.indexOf(';', nameindex);
                int nameEndIndex;
                if (nameSemiColonIndex > 0) {
                    nameEndIndex = nameSemiColonIndex;
                } else {
                    nameEndIndex = contentType.length();
                }
                String name = contentType.substring(nameindex + "name=".length(), nameEndIndex).trim();
                if (!name.startsWith("\"")) {
                    buffer.append('"');
                }
                buffer.append(name.trim());
                if (!name.endsWith("\"")) {
                    buffer.append('"');
                }
            }
            buffer.append(')');
        } else {
            buffer.append(" NIL");
        }
    }
    appendBodyStructureValue(buffer, bodyPart.getContentID());
    appendBodyStructureValue(buffer, bodyPart.getDescription());
    appendBodyStructureValue(buffer, bodyPart.getEncoding());
    appendBodyStructureValue(buffer, bodyPart.getSize());
    if ("MESSAGE".equals(type) || "TEXT".equals(type)) {
        // line count not implemented in JavaMail, return fake line count
        appendBodyStructureValue(buffer, bodyPart.getSize() / 80);
    } else {
        // do not send line count for non text bodyparts
        appendBodyStructureValue(buffer, -1);
    }
    buffer.append(')');
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

private boolean hasNotContentID(Part part) throws MessagingException {
    if (part instanceof MimePart) {
        MimePart mime = (MimePart) part;
        return StringUtils.isEmpty(mime.getContentID());
    } else {/*w w  w.  j  a va 2 s.c  om*/
        return false;
    }
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Extracts the content of a MimeMessage recursively.
 *
 * @param part   the current MimePart/*from w  ww. ja v  a2 s.  c  o  m*/
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private void parse(final MimePart part) throws MessagingException, IOException {
    extractCustomUserHeaders(part);

    if (isMimeType(part, "text/plain") && plainContent == null
            && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        plainContent = (String) part.getContent();
    } else {
        if (isMimeType(part, "text/html") && htmlContent == null
                && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
            htmlContent = (String) part.getContent();
        } else {
            if (isMimeType(part, "multipart/*")) {
                final Multipart mp = (Multipart) part.getContent();
                final int count = mp.getCount();

                // iterate over all MimeBodyPart
                for (int i = 0; i < count; i++) {
                    parse((MimeBodyPart) mp.getBodyPart(i));
                }
            } else {
                final DataSource ds = createDataSource(part);
                // If the diposition is not provided, the part should be treat as attachment
                if (part.getDisposition() == null || Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                    this.attachmentList.put(part.getContentID(), ds);
                } else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) {
                    this.cidMap.put(part.getContentID(), ds);
                } else {
                    throw new IllegalStateException("invalid attachment type");
                }
            }
        }
    }
}