Example usage for javax.mail Part getHeader

List of usage examples for javax.mail Part getHeader

Introduction

In this page you can find the example usage for javax.mail Part getHeader.

Prototype

public String[] getHeader(String header_name) throws MessagingException;

Source Link

Document

Get all the headers for this header name.

Usage

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public static String getDisposition(Part _mess) throws MessagingException {
    String dispos = _mess.getDisposition();
    // getDisposition isn't 100% reliable 
    if (dispos == null) {
        String[] disposHdr = _mess.getHeader("Content-Disposition");
        if (disposHdr != null && disposHdr.length > 0 && disposHdr[0].startsWith(Part.ATTACHMENT)) {
            return Part.ATTACHMENT;
        }/*  ww  w .  j  a va  2s.c om*/
    }

    return dispos;
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

public static String getFilename(Part Mess) throws MessagingException {
    // Part.getFileName() doesn't take into account any encoding that may have been 
    // applied to the filename so in order to obtain the correct filename we
    // need to retrieve it from the Content-Disposition

    String[] contentType = Mess.getHeader("Content-Disposition");
    if (contentType != null && contentType.length > 0) {
        int nameStartIndx = contentType[0].indexOf("filename=\"");
        if (nameStartIndx != -1) {
            String filename = contentType[0].substring(nameStartIndx + 10,
                    contentType[0].indexOf('\"', nameStartIndx + 10));
            try {
                filename = MimeUtility.decodeText(filename);
                return filename;
            } catch (UnsupportedEncodingException e) {
            }//from ww  w .  ja v  a2 s. c o m
        }
    }

    // couldn't determine it using the above, so fall back to more reliable but 
    // less correct option
    return Mess.getFileName();
}

From source file:immf.Util.java

public static String getFileName(Part part) throws MessagingException {
    String[] disposition = part.getHeader("Content-Disposition");
    if (disposition == null || disposition.length < 1) {
        return part.getFileName();
    }//from  ww w .  j ava  2  s  .  c  o m
    // ??????????????
    return decodeParameterSpciallyJapanese(getParameter(disposition[0], "filename"));
}

From source file:dtw.webmail.model.JwmaMessagePartImpl.java

/**
 * Creates a <tt>JwmaMessagePartImpl</tt> instance from a given
 * <tt>javax.mail.Part</tt> instance.
 *
 * @param part a <tt>javax.mail.Part</tt> instance.
 * @param number the number of the part as <tt>int</tt>.
 *
 * @return the newly created instance.//from ww  w  .j  a  va2s.com
 * @throws JwmaException if it fails to create the new instance.
 */
public static JwmaMessagePartImpl createJwmaMessagePartImpl(Part part, int number) throws JwmaException {
    JwmaMessagePartImpl partinfo = new JwmaMessagePartImpl(part, number);

    //content type
    try {
        partinfo.setContentType(part.getContentType());

        //size
        int size = part.getSize();
        //JwmaKernel.getReference().debugLog().write("Part size="+size);
        String fileName = part.getFileName();
        //correct size of encoded parts
        String[] encoding = part.getHeader("Content-Transfer-Encoding");
        if (fileName != null && encoding != null && encoding.length > 0
                && (encoding[0].equalsIgnoreCase("base64") || encoding[0].equalsIgnoreCase("uuencode"))) {
            if ((fileName.startsWith("=?GB2312?B?") && fileName.endsWith("?="))) {
                byte[] decoded = Base64.decodeBase64(fileName.substring(11, fileName.indexOf("?=")).getBytes());
                fileName = new String(decoded, "GB2312");
                /*fileName = CipherUtils.decrypt(fileName);
                System.out.println("fileName----"+fileName);*/
                //fileName = getFromBASE64(fileName.substring(11,fileName.indexOf("?=")));  
            } else if ((fileName.startsWith("=?UTF-8?") || fileName.startsWith("=?UTF8?"))
                    && fileName.endsWith("?=")) {
                fileName = MimeUtility.decodeText(fileName);
            }
            //an encoded file is about 35% smaller in reality,
            //so correct the size
            size = (int) (size * 0.65);
        }

        partinfo.setSize(size);
        //description
        partinfo.setDescription(part.getDescription());

        //filename
        partinfo.setName(fileName);

        //textcontent
        if (partinfo.isMimeType("text/*")) {
            Object content = part.getContent();
            if (content instanceof String) {
                partinfo.setTextContent((String) content);
            } else if (content instanceof InputStream) {
                InputStream in = (InputStream) content;
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int amount = 0;
                while ((amount = in.read(buffer)) >= 0) {
                    bout.write(buffer, 0, amount);
                }
                partinfo.setTextContent(new String(bout.toString()));
            }
        }
    } catch (Exception mex) {
        throw new JwmaException("jwma.messagepart.failedcreation", true).setException(mex);
    }
    return partinfo;
}

From source file:immf.Util.java

public static void setFileName(Part part, String filename, String charset, String lang)
        throws MessagingException {

    ContentDisposition disposition;//w  w w . j a  v  a2s .  c  o  m
    String[] strings = part.getHeader("Content-Disposition");
    if (strings == null || strings.length < 1) {
        disposition = new ContentDisposition(Part.ATTACHMENT);
    } else {
        disposition = new ContentDisposition(strings[0]);
        disposition.getParameterList().remove("filename");
    }

    part.setHeader("Content-Disposition",
            disposition.toString() + encodeParameter("filename", filename, charset, lang));

    ContentType cType;
    strings = part.getHeader("Content-Type");
    if (strings == null || strings.length < 1) {
        cType = new ContentType(part.getDataHandler().getContentType());
    } else {
        cType = new ContentType(strings[0]);
    }

    try {
        // I want to public the MimeUtility#doEncode()!!!
        String mimeString = MimeUtility.encodeWord(filename, charset, "B");
        // cut <CRLF>...
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = mimeString.indexOf('\r')) != -1) {
            sb.append(mimeString.substring(0, i));
            mimeString = mimeString.substring(i + 2);
        }
        sb.append(mimeString);

        cType.setParameter("name", new String(sb));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("Encoding error", e);
    }
    part.setHeader("Content-Type", cType.toString());
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

private static EmailAttachment createEmailAttachment(Part part, String fileName)
        throws java.io.IOException, javax.mail.MessagingException {
    EmailAttachment emailAttachment = new EmailAttachment();
    File file = MailReader.saveFile(fileName, part.getInputStream());
    emailAttachment.setFile(file);/*from  w w  w  .j a  v  a 2s. co  m*/
    emailAttachment.setFileName(fileName);
    String cid = null;
    String[] contentIDs = part.getHeader("Content-ID");
    if (contentIDs != null && contentIDs.length > 0) {
        cid = contentIDs[0];
        if (cid != null && cid.startsWith("<")) {
            cid = cid.substring(1, cid.length() - 1);
        }
    }
    emailAttachment.setCid(cid);
    return emailAttachment;
}

From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java

private Part findAttachment(MimeMessage containerMessage)
        throws MessagingException, IOException, PartException {
    final MutableObject smimePart = new MutableObject();
    final MutableObject octetPart = new MutableObject();

    PartListener partListener = new PartScanner.PartListener() {
        @Override/* w  w  w .  ja  v  a 2s.  c  o m*/
        public boolean onPart(Part parent, Part part, Object context) throws PartException {
            try {
                if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER),
                        DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
                    smimePart.setValue(part);

                    /*
                     * we found the part with the marker so we can stop scanning
                     */
                    return false;
                }

                /*
                 * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER
                 */
                if (part.isMimeType("application/octet-stream")) {
                    octetPart.setValue(part);
                }

                return true;
            } catch (MessagingException e) {
                throw new PartException(e);
            }
        }
    };

    PartScanner partScanner = new PartScanner(partListener, MAX_DEPTH);

    partScanner.scanPart(containerMessage);

    Part result = (Part) smimePart.getValue();

    if (result == null) {
        result = (Part) octetPart.getValue();

        if (result != null) {
            logger.debug("Marker not found. Using octet-stream instead.");
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    return result;
}

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

/**
 * Get the content dispostion of a part. The part is interogated for a
 * valid content disposition. If the content disposition is missing, a
 * default disposition is created based on the type of the part.
 *
 * @param part The part to interogate//from  w ww.  j av a 2s  . c o m
 *
 * @return ContentDisposition of the part
 *
 * @throws MessagingException DOCUMENT ME!
 *
 * @see javax.mail.Part
 */
public static ContentDisposition getContentDisposition(Part part) throws MessagingException {
    String[] xheaders = part.getHeader("Content-Disposition");

    try {
        if (xheaders != null) {
            return new ContentDisposition(xheaders[0]);
        }
    } catch (ParseException xex) {
        throw new MessagingException(xex.toString());
    }

    // set default disposition based on part type
    if (part instanceof MimeBodyPart) {
        return new ContentDisposition("attachment");
    }

    return new ContentDisposition("inline");
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Writes a passed payload part to the passed message object. 
 *///ww w .ja  v a 2 s  .  co  m
public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception {
    List<Part> attachmentList = new ArrayList<Part>();
    AS2Info info = message.getAS2Info();
    if (!info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (payloadPart.isMimeType("multipart/*")) {
            //check if it is a CEM
            if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) {
                messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM);
                if (this.logger != null) {
                    this.logger.log(Level.FINE, this.rb.getResourceString("found.cem",
                            new Object[] { messageInfo.getMessageId(), message }), info);
                }
            }
            ByteArrayOutputStream mem = new ByteArrayOutputStream();
            payloadPart.writeTo(mem);
            mem.flush();
            mem.close();
            MimeMultipart multipart = new MimeMultipart(
                    new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType()));
            //add all attachments to the message
            for (int i = 0; i < multipart.getCount(); i++) {
                //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature
                if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) {
                    attachmentList.add(multipart.getBodyPart(i));
                }
            }
        } else {
            attachmentList.add(payloadPart);
        }
    } else {
        //its a MDN, write whole part
        attachmentList.add(payloadPart);
    }
    //write the parts
    for (Part attachmentPart : attachmentList) {
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        InputStream payloadIn = attachmentPart.getInputStream();
        this.copyStreams(payloadIn, payloadOut);
        payloadOut.flush();
        payloadOut.close();
        byte[] data = payloadOut.toByteArray();
        AS2Payload as2Payload = new AS2Payload();
        as2Payload.setData(data);
        String[] contentIdHeader = attachmentPart.getHeader("content-id");
        if (contentIdHeader != null && contentIdHeader.length > 0) {
            as2Payload.setContentId(contentIdHeader[0]);
        }
        String[] contentTypeHeader = attachmentPart.getHeader("content-type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            as2Payload.setContentType(contentTypeHeader[0]);
        }
        try {
            as2Payload.setOriginalFilename(payloadPart.getFileName());
        } catch (MessagingException e) {
            if (this.logger != null) {
                this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                        new Object[] { info.getMessageId(), e.getMessage(), }), info);
            }
        }
        if (as2Payload.getOriginalFilename() == null) {
            String filenameheader = header.getProperty("content-disposition");
            if (filenameheader != null) {
                //test part for convinience: extract file name
                MimeBodyPart filenamePart = new MimeBodyPart();
                filenamePart.setHeader("content-disposition", filenameheader);
                try {
                    as2Payload.setOriginalFilename(filenamePart.getFileName());
                } catch (MessagingException e) {
                    if (this.logger != null) {
                        this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                                new Object[] { info.getMessageId(), e.getMessage(), }), info);
                    }
                }
            }
        }
        message.addPayload(as2Payload);
    }
}

From source file:com.stimulus.archiva.extraction.MessageExtraction.java

private static void dumpPart(Part p, Hashtable<String, Part> attachments, Hashtable<String, String> inlines,
        Hashtable<String, String> images, Hashtable<String, String> nonImages, ArrayList<String> mimeTypes,
        String subject) throws Exception {
    mimeTypes.add(p.getContentType());//from w  w w  .  ja  va 2  s .c om
    if (!p.isMimeType("multipart/*")) {

        String disp = p.getDisposition();
        String fname = p.getFileName();
        if (fname != null) {
            try {
                fname = MimeUtility.decodeText(fname);
            } catch (Exception e) {
                logger.debug("cannot decode filename:" + e.getMessage());
            }
        }
        if ((disp != null && Compare.equalsIgnoreCase(disp, Part.ATTACHMENT)) || fname != null) {
            String filename = getFilename(subject, p);
            if (!filename.equalsIgnoreCase("winmail.dat")) {
                attachments.put(filename, p);
            }
            /*if (p.isMimeType("image/*")) {
               String str[] = p.getHeader("Content-ID");
               if (str != null) images.put(filename,str[0]);
               else images.put(filename, filename);
            }
            return;*/
        }
    }
    if (p.isMimeType("text/plain")) {
        String str = "";
        if (inlines.containsKey("text/plain"))
            str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n";
        inlines.put("text/plain", str + getTextContent(p));
    } else if (p.isMimeType("text/html")) {
        inlines.put("text/html", getTextContent(p));
    } else if (p.isMimeType("text/xml")) {
        attachments.put(getFilename(subject, p), p);
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++)
            dumpPart(mp.getBodyPart(i), attachments, inlines, images, nonImages, mimeTypes, subject);
    } else if (p.isMimeType("message/rfc822")) {
        dumpPart((Part) p.getContent(), attachments, inlines, images, nonImages, mimeTypes, subject);
    } else if (p.isMimeType("application/ms-tnef")) {
        Part tnefpart = TNEFMime.convert(null, p, false);
        if (tnefpart != null) {
            dumpPart((Part) tnefpart, attachments, inlines, images, nonImages, mimeTypes, subject);
        }
    } else if (p.isMimeType("application/*")) {
        String filename = getFilename("application", p);
        attachments.put(filename, p);
        String str[] = p.getHeader("Content-ID");
        if (str != null)
            nonImages.put(filename, str[0]);
    } else if (p.isMimeType("image/*")) {
        String fileName = getFilename("image", p);
        attachments.put(fileName, p);
        String str[] = p.getHeader("Content-ID");
        if (str != null)
            images.put(fileName, str[0]);
        else
            images.put(fileName, fileName);
    } else {
        String contentType = p.getContentType();
        Object o = p.getContent();
        if (o instanceof String) {
            String str = "";
            if (inlines.containsKey("text/plain"))
                str = (String) inlines.get("text/plain") + "\n\n-------------------------------\n";
            inlines.put(contentType, str + (String) o);
        } else {
            String fileName = getFilenameFromContentType("attach", contentType);
            attachments.put(fileName, p);
        }
    }
}