Example usage for javax.mail Part ATTACHMENT

List of usage examples for javax.mail Part ATTACHMENT

Introduction

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

Prototype

String ATTACHMENT

To view the source code for javax.mail Part ATTACHMENT.

Click Source Link

Document

This part should be presented as an attachment.

Usage

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Vera Oliphant <oli@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.setText("Good as gold");
    MimeMultipart multi = new ZMimeMultipart("mixed");
    ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
    cdisp.setParameter("filename", "fun.txt");

    ZMimeBodyPart bp = new ZMimeBodyPart();
    // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure
    // it gets called before setting Content-Type and CTE headers.
    try {//  w  w  w .java 2s .c om
        bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain")));
    } catch (IOException e) {
        throw new MessagingException("could not generate mime part content", e);
    }
    bp.addHeader("Content-Disposition", cdisp.toString());
    bp.addHeader("Content-Type", "text/plain");
    bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
    multi.addBodyPart(bp);

    mm.setContent(multi);
    mm.saveChanges();

    return new ParsedMessage(mm, false);
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception {

    Multipart multipart = (Multipart) o;

    for (int k = 0, n = multipart.getCount(); k < n; k++) {

        Part part = multipart.getBodyPart(k);
        String disposition = part.getDisposition();
        MimeBodyPart mbp = (MimeBodyPart) part;

        if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))) {
            log.debug("---------------> Saving File " + part.getFileName() + " " + part.getContent());
            saveAttachment(part, inboxentry);

        } else {/*from w  ww.jav a2  s .c om*/
            // Check if plain
            if (mbp.isMimeType("text/plain")) {
                log.debug("---------------> Handle plain. ");
                content += "<PRE style=\"font-size: 12px;\">" + (String) part.getContent() + "</PRE>";
                // Check if html
            } else if (mbp.isMimeType("text/html")) {
                log.debug("---------------> Handle plain. ");
                content += (String) part.getContent();
            } else {
                // Special non-attachment cases here of
                // image/gif, text/html, ...
                log.debug("---------------> Special non-attachment cases " + " " + part.getContentType());
                if (mbp.isMimeType("multipart/*")) {
                    Object ob = part.getContent();
                    content = this.handleMulitipart(ob, content, inboxentry) + "\n\n" + content;
                } else {
                    saveAttachment(part, inboxentry);
                }
            }
        }
    }

    return content;
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Analyze the part to check if it is an attachment, a base64 encoded file or some text.
 *
 * @param part the part to be analyzed./*from  w ww .jav a 2  s  .  c om*/
 * @return true if it is some text - false otherwise.
 * @throws MessagingException
 */
protected boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:msgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*from   ww  w .  j ava  2 s .  c  om*/

    /** Dump input stream .. 
            
    InputStream is = p.getInputStream();
    // If "is" is not already buffered, wrap a BufferedInputStream
    // around it.
    if (!(is instanceof BufferedInputStream))
        is = new BufferedInputStream(is);
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
            
    **/

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a
             * MIME type we know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && p instanceof MimeBodyPart && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration,
        final MimeMessage mimeMessage, final MultiFilesJob job)
        throws MessagingException, IOException, FileNotFoundException {

    final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName();
    if (StringUtils.isNotBlank(jobConfigurationFileName)) {
        final File jobConfigurationFile = getJobConfigurationFile(
                depositEmailConfiguration.getApplicationName(), jobConfigurationFileName);
        job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
    }/*from  ww w . ja  va  2s .c  om*/

    final Object content = mimeMessage.getContent();
    Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed");

    final Multipart multipart = (Multipart) content;
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        final Part part = multipart.getBodyPart(i);

        final String disposition = part.getDisposition();

        if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
            final String name = part.getFileName();
            final String contentType = StringUtils.substringBefore(part.getContentType(), ";");
            MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job);
        }
    }
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Adapted extract multipart is the recusrsive parser that splits the data and apend it to the
 * final xhtml file.// w w  w .  ja  va 2 s. com
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws SAXException
 *             the sAX exception
 * @throws TikaException
 *             the tika exception
 */
public void adaptedExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart, ParseContext context)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        return;
    }

    if (part.isMimeType("text/plain")) {
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            return;
        } else {
            // add file
            String data = part.getContent().toString();
            writeContent(part, data, MimetypeMap.MIMETYPE_TEXT_PLAIN, "txt");
        }
    } else if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        Part parentPartLocal = part;
        if (parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE)) {
            parentPartLocal = parentPart;
        }
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            adaptedExtractMultipart(xhtml, mp.getBodyPart(i), parentPartLocal, context);
        }
    } else if (part.isMimeType("message/rfc822")) {
        adaptedExtractMultipart(xhtml, (Part) part.getContent(), part, context);
    } else if (part.isMimeType("text/html")) {

        if ((parentPart != null && parentPart.isMimeType(MULTIPART_ALTERNATIVE))
                || (part.getDisposition() == null || !part.getDisposition().contains(Part.ATTACHMENT))) {
            Object data = part.getContent();
            String htmlFileData = prepareString(new String(data.toString()));
            writeContent(part, htmlFileData, MimetypeMap.MIMETYPE_HTML, "html");
        }

    } else if (part.isMimeType("image/*")) {

        String[] encoded = part.getHeader("Content-Transfer-Encoding");
        if (isContained(encoded, "base64")) {
            if (part.getDisposition() != null && part.getDisposition().contains(Part.ATTACHMENT)) {
                InputStream stream = part.getInputStream();
                byte[] binaryData = new byte[part.getSize()];
                stream.read(binaryData, 0, part.getSize());
                String encodedData = new String(Base64.encodeBase64(binaryData));
                String[] split = part.getContentType().split(";");
                String src = "data:" + split[0].trim() + ";base64," + encodedData;
                AttributesImpl attributes = new AttributesImpl();
                attributes.addAttribute(null, "src", "src", "String", src);
                xhtml.startElement("img", attributes);
                xhtml.endElement("img");
            }
        }

    } else {
        Object content = part.getContent();
        if (content instanceof String) {
            xhtml.element("div", prepareString(part.getContent().toString()));
        } else if (content instanceof InputStream) {
            InputStream fileContent = part.getInputStream();

            Parser parser = new AutoDetectParser();
            Metadata attachmentMetadata = new Metadata();

            BodyContentHandler handlerAttachments = new BodyContentHandler();
            parser.parse(fileContent, handlerAttachments, attachmentMetadata, context);

            xhtml.element("div", handlerAttachments.toString());

        }
    }
}

From source file:MainClass.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*from w  ww.ja va  2s .  com*/

    /**
     * Dump input stream ..
     * 
     * InputStream is = p.getInputStream(); // If "is" is not already buffered,
     * wrap a BufferedInputStream // around it. if (!(is instanceof
     * BufferedInputStream)) is = new BufferedInputStream(is); int c; while ((c =
     * is.read()) != -1) System.out.write(c);
     * 
     */

    String ct = p.getContentType();
    try {
        pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
        pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null)
        pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids fetching the actual
     * content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
        pr("This is plain text");
        pr("---------------------------");
        if (!showStructure && !saveAttachments)
            System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
        pr("This is a Multipart");
        pr("---------------------------");
        Multipart mp = (Multipart) p.getContent();
        level++;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
        level--;
    } else if (p.isMimeType("message/rfc822")) {
        pr("This is a Nested Message");
        pr("---------------------------");
        level++;
        dumpPart((Part) p.getContent());
        level--;
    } else {
        if (!showStructure && !saveAttachments) {
            /*
             * If we actually want to see the data, and it's not a MIME type we
             * know, fetch it and check its Java type.
             */
            Object o = p.getContent();
            if (o instanceof String) {
                pr("This is a string");
                pr("---------------------------");
                System.out.println((String) o);
            } else if (o instanceof InputStream) {
                pr("This is just an input stream");
                pr("---------------------------");
                InputStream is = (InputStream) o;
                int c;
                while ((c = is.read()) != -1)
                    System.out.write(c);
            } else {
                pr("This is an unknown type");
                pr("---------------------------");
                pr(o.toString());
            }
        } else {
            // just a separator
            pr("---------------------------");
        }
    }

    /*
     * If we're saving attachments, write out anything that looks like an
     * attachment into an appropriately named file. Don't overwrite existing
     * files to prevent mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // many mailers don't include a Content-Disposition
        if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
            if (filename == null)
                filename = "Attachment" + attnum++;
            pr("Saving attachment to file " + filename);
            try {
                File f = new File(filename);
                if (f.exists())
                    // XXX - could try a series of names
                    throw new IOException("file exists");
                ((MimeBodyPart) p).saveFile(f);
            } catch (IOException ex) {
                pr("Failed to save attachment: " + ex);
            }
            pr("---------------------------");
        }
    }
}

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;
        }//from w w  w.j  a  va  2  s  .  co m
    }

    return dispos;
}

From source file:com.stimulus.archiva.domain.Email.java

protected boolean hasAttachment(Part p) throws MessagingException, IOException {

    if (p.getDisposition() != null && Compare.equalsIgnoreCase(p.getDisposition(), Part.ATTACHMENT)) {
        logger.debug("hasAttachment() attachment disposition.");
        return true;
    }// ww w.  jav a2s.c o m
    if (p.getFileName() != null) {
        logger.debug("hasAttachment() filename specified.");
        return true;
    }

    try {
        if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                logger.debug("hasAttachment() scanning multipart[" + i + "]");
                if (hasAttachment(mp.getBodyPart(i)))
                    return true;
            }
        } else if (p.isMimeType("message/rfc822")) {
            return hasAttachment((Part) p.getContent());
        }
    } catch (Exception e) {
        logger.debug("exception occurred while detecting attachment", e);
    }
    return false;
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlTextWithAttachment() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    messageChecker.addMessageListener(mockListener1);
    messageChecker.addMessageListener(mockListener2);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Html Email test with attachment");
    String html = loadHtml();/* ww  w. j  a  va 2  s.  c  o m*/
    MimeBodyPart attachment = new MimeBodyPart(TestMessageChecker.class.getResourceAsStream("lemonde.html"));
    attachment.setDisposition(Part.ATTACHMENT);
    attachment.setFileName("lemonde.html");
    MimeBodyPart body = new MimeBodyPart();
    body.setContent(html, "text/html; charset=\"UTF-8\"");
    Multipart multiPart = new MimeMultipart();
    multiPart.addBodyPart(body);
    multiPart.addBodyPart(attachment);
    mail.setContent(multiPart);
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Html Email test with attachment", message.getTitle());
    assertEquals(html, message.getBody());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(ATT_SIZE, message.getAttachmentsSize());
    assertEquals(1, message.getAttachments().size());
    String path = MessageFormat.format(attachmentPath,
            messageChecker.getMailProcessor().replaceSpecialChars(message.getMessageId()));
    Attachment attached = message.getAttachments().iterator().next();
    assertEquals(path, attached.getPath());
    assertEquals("lemonde.html", attached.getFileName());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}