Search in sources :

Example 31 with MimePart

use of javax.mail.internet.MimePart in project spring-framework by spring-projects.

the class MimeMessageHelper method setText.

/**
	 * Set the given text directly as content in non-multipart mode
	 * or as default body part in multipart mode.
	 * The "html" flag determines the content type to apply.
	 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param text the text for the message
	 * @param html whether to apply content type "text/html" for an
	 * HTML mail, using default content type ("text/plain") else
	 * @throws MessagingException in case of errors
	 */
public void setText(String text, boolean html) throws MessagingException {
    Assert.notNull(text, "Text must not be null");
    MimePart partToUse;
    if (isMultipart()) {
        partToUse = getMainPart();
    } else {
        partToUse = this.mimeMessage;
    }
    if (html) {
        setHtmlTextToMimePart(partToUse, text);
    } else {
        setPlainTextToMimePart(partToUse, text);
    }
}
Also used : MimePart(javax.mail.internet.MimePart)

Example 32 with MimePart

use of javax.mail.internet.MimePart in project jodd by oblac.

the class ReceivedEmail method processPart.

/**
	 * Process single part of received message. All parts are simple added to the message, i.e. hierarchy is not saved.
	 */
protected void processPart(ReceivedEmail email, Part part) throws IOException, MessagingException {
    Object content = part.getContent();
    if (content instanceof String) {
        String stringContent = (String) content;
        String disposition = part.getDisposition();
        if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
            String contentType = part.getContentType();
            String mimeType = EmailUtil.extractMimeType(contentType);
            String encoding = EmailUtil.extractEncoding(contentType);
            String fileName = part.getFileName();
            String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
            if (encoding == null) {
                encoding = StringPool.US_ASCII;
            }
            email.addAttachment(fileName, mimeType, contentId, stringContent.getBytes(encoding));
        } else {
            String contentType = part.getContentType();
            String encoding = EmailUtil.extractEncoding(contentType);
            String mimeType = EmailUtil.extractMimeType(contentType);
            if (encoding == null) {
                encoding = StringPool.US_ASCII;
            }
            email.addMessage(stringContent, mimeType, encoding);
        }
    } else if (content instanceof Multipart) {
        Multipart mp = (Multipart) content;
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            Part innerPart = mp.getBodyPart(i);
            processPart(email, innerPart);
        }
    } else if (content instanceof InputStream) {
        String fileName = EmailUtil.resolveFileName(part);
        String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
        String mimeType = EmailUtil.extractMimeType(part.getContentType());
        InputStream is = (InputStream) content;
        FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
        StreamUtil.copy(is, fbaos);
        email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
    } else if (content instanceof MimeMessage) {
        MimeMessage mimeMessage = (MimeMessage) content;
        addAttachmentMessage(new ReceivedEmail(mimeMessage));
    } else {
        String fileName = part.getFileName();
        String contentId = (part instanceof MimePart) ? ((MimePart) part).getContentID() : null;
        String mimeType = EmailUtil.extractMimeType(part.getContentType());
        InputStream is = part.getInputStream();
        FastByteArrayOutputStream fbaos = new FastByteArrayOutputStream();
        StreamUtil.copy(is, fbaos);
        StreamUtil.close(is);
        email.addAttachment(fileName, mimeType, contentId, fbaos.toByteArray());
    }
}
Also used : Multipart(javax.mail.Multipart) FastByteArrayOutputStream(jodd.io.FastByteArrayOutputStream) MimeMessage(javax.mail.internet.MimeMessage) Part(javax.mail.Part) MimePart(javax.mail.internet.MimePart) InputStream(java.io.InputStream) MimePart(javax.mail.internet.MimePart)

Example 33 with MimePart

use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.

the class ImapPartSpecifier method getContent.

private Pair<Long, InputStream> getContent(MimeMessage msg) throws BinaryDecodingException {
    long length = -1;
    InputStream is = null;
    try {
        MimePart mp = Mime.getMimePart(msg, part);
        if (mp == null) {
            return null;
        }
        // TEXT and HEADER* modifiers operate on rfc822 messages
        if ((modifier.equals("TEXT") || modifier.startsWith("HEADER")) && !(mp instanceof MimeMessage)) {
            // FIXME: hackaround for JavaMail's failure to handle multipart/digest properly
            Object content = Mime.getMessageContent(mp);
            if (!(content instanceof MimeMessage)) {
                return null;
            }
            mp = (MimeMessage) content;
        }
        // get the content of the requested part
        if (modifier.equals("")) {
            if (mp instanceof MimeBodyPart) {
                if (command.startsWith("BINARY")) {
                    try {
                        is = ((MimeBodyPart) mp).getInputStream();
                    } catch (IOException ioe) {
                        throw new BinaryDecodingException();
                    }
                } else {
                    is = ((MimeBodyPart) mp).getRawInputStream();
                    length = Math.max(0, mp.getSize());
                }
            } else if (mp instanceof MimeMessage) {
                if (!isMessageBody(msg, mp)) {
                    String parentPart = part.substring(0, Math.max(0, part.length() - 2));
                    return new ImapPartSpecifier(command, parentPart, "TEXT").getContent(msg);
                } else if (command.startsWith("BINARY")) {
                    try {
                        is = ((MimeMessage) mp).getInputStream();
                    } catch (IOException ioe) {
                        throw new BinaryDecodingException();
                    }
                } else {
                    is = ((MimeMessage) mp).getRawInputStream();
                    length = Math.max(0, mp.getSize());
                }
            } else {
                ZimbraLog.imap.debug("getting content of part; not MimeBodyPart: " + this);
                return ImapMessage.EMPTY_CONTENT;
            }
        } else if (modifier.startsWith("HEADER")) {
            MimeMessage mm = (MimeMessage) mp;
            Enumeration<?> headers;
            if (modifier.equals("HEADER")) {
                headers = mm.getAllHeaderLines();
            } else if (modifier.equals("HEADER.FIELDS")) {
                headers = mm.getMatchingHeaderLines(getHeaders());
            } else {
                headers = mm.getNonMatchingHeaderLines(getHeaders());
            }
            StringBuilder result = new StringBuilder();
            while (headers.hasMoreElements()) {
                result.append(headers.nextElement()).append(ImapHandler.LINE_SEPARATOR);
            }
            byte[] content = result.append(ImapHandler.LINE_SEPARATOR).toString().getBytes();
            is = new ByteArrayInputStream(content);
            length = content.length;
        } else if (modifier.equals("MIME")) {
            if (mp instanceof MimeMessage) {
                String parentPart = part.substring(0, Math.max(0, part.length() - 2));
                return new ImapPartSpecifier(command, parentPart, "HEADER").getContent(msg);
            }
            Enumeration<?> mime = mp.getAllHeaderLines();
            StringBuilder result = new StringBuilder();
            while (mime.hasMoreElements()) {
                result.append(mime.nextElement()).append(ImapHandler.LINE_SEPARATOR);
            }
            byte[] content = result.append(ImapHandler.LINE_SEPARATOR).toString().getBytes();
            is = new ByteArrayInputStream(content);
            length = content.length;
        } else if (modifier.equals("TEXT")) {
            is = ((MimeMessage) mp).getRawInputStream();
            length = Math.max(0, mp.getSize());
        } else {
            return null;
        }
        return new Pair<Long, InputStream>(length, is);
    } catch (IOException e) {
        ByteUtil.closeStream(is);
        return null;
    } catch (MessagingException e) {
        ByteUtil.closeStream(is);
        return null;
    }
}
Also used : Enumeration(java.util.Enumeration) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) MimeMessage(javax.mail.internet.MimeMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) MimePart(javax.mail.internet.MimePart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Pair(com.zimbra.common.util.Pair)

Example 34 with MimePart

use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.

the class FeedManager method generateMessage.

private static ParsedMessage generateMessage(String title, String content, String ctype, InternetAddress addr, Date date, List<Enclosure> attach) throws ServiceException {
    // cull out invalid enclosures
    if (attach != null) {
        for (Iterator<Enclosure> it = attach.iterator(); it.hasNext(); ) {
            if (it.next().getLocation() == null) {
                it.remove();
            }
        }
    }
    boolean hasAttachments = attach != null && !attach.isEmpty();
    // clean up whitespace in the title
    if (title != null) {
        title = title.replaceAll("\\s+", " ");
    }
    // create the MIME message and wrap it
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
        MimePart body = hasAttachments ? new ZMimeBodyPart() : (MimePart) mm;
        body.setText(content, "utf-8");
        body.setHeader("Content-Type", ctype);
        if (hasAttachments) {
            // encode each enclosure as an attachment with Content-Location set
            MimeMultipart mmp = new ZMimeMultipart("mixed");
            mmp.addBodyPart((BodyPart) body);
            for (Enclosure enc : attach) {
                MimeBodyPart part = new ZMimeBodyPart();
                part.setText("");
                part.addHeader("Content-Location", enc.getLocation());
                part.addHeader("Content-Type", enc.getContentType());
                if (enc.getDescription() != null) {
                    part.addHeader("Content-Description", enc.getDescription());
                }
                part.addHeader("Content-Disposition", "attachment");
                mmp.addBodyPart(part);
            }
            mm.setContent(mmp);
        }
        mm.setSentDate(date);
        mm.addFrom(new InternetAddress[] { addr });
        mm.setSubject(title, "utf-8");
        // more stuff here!
        mm.saveChanges();
        return new ParsedMessage(mm, date.getTime(), false);
    } catch (MessagingException e) {
        throw ServiceException.PARSE_ERROR("error wrapping feed item in MimeMessage", e);
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) ParsedMessage(com.zimbra.cs.mime.ParsedMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimePart(javax.mail.internet.MimePart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 35 with MimePart

use of javax.mail.internet.MimePart in project zm-mailbox by Zimbra.

the class ContentServlet method getCommand.

private void getCommand(HttpServletRequest req, HttpServletResponse resp, AuthToken token) throws ServletException, IOException {
    ItemId iid = null;
    try {
        iid = new ItemId(req.getParameter(PARAM_MSGID), (String) null);
    } catch (ServiceException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errInvalidId, req));
        return;
    }
    String part = req.getParameter(PARAM_PART);
    String fmt = req.getParameter(PARAM_FORMAT);
    String dumpsterParam = req.getParameter(PARAM_DUMPSTER);
    boolean fromDumpster = dumpsterParam != null && !dumpsterParam.equals("0") && !dumpsterParam.equalsIgnoreCase("false");
    try {
        // need to proxy the fetch if the mailbox lives on another server
        if (!iid.isLocal()) {
            // wrong server; proxy to the right one...
            proxyServletRequest(req, resp, iid.getAccountId());
            return;
        }
        String authId = token.getAccountId();
        String accountId = iid.getAccountId() != null ? iid.getAccountId() : authId;
        AccountUtil.addAccountToLogContext(Provisioning.getInstance(), accountId, ZimbraLog.C_NAME, ZimbraLog.C_ID, token);
        if (!accountId.equalsIgnoreCase(authId))
            ZimbraLog.addToContext(ZimbraLog.C_AID, authId);
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(accountId);
        if (mbox == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMailboxNotFound, req));
            return;
        }
        ZimbraLog.addMboxToContext(mbox.getId());
        MailItem item = mbox.getItemById(new OperationContext(token), iid.getId(), MailItem.Type.UNKNOWN, fromDumpster);
        if (item == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMessageNotFound, req));
            return;
        }
        try {
            if (part == null) {
                // they want the entire message...
                boolean sync = "1".equals(req.getParameter(PARAM_SYNC));
                StringBuffer hdr = new StringBuffer();
                if (sync) {
                    // for sync, return metadata as headers to avoid extra SOAP round-trips
                    resp.addHeader("X-Zimbra-Tags", TagUtil.getTagIdString(item));
                    resp.addHeader("X-Zimbra-Tag-Names", TagUtil.encodeTags(item.getTags()));
                    resp.addHeader("X-Zimbra-Flags", item.getFlagString());
                    resp.addHeader("X-Zimbra-Received", Long.toString(item.getDate()));
                    resp.addHeader("X-Zimbra-Modified", Long.toString(item.getChangeDate()));
                    // also return metadata inline in the message content for now
                    hdr.append("X-Zimbra-Tags: ").append(TagUtil.getTagIdString(item)).append("\n");
                    hdr.append("X-Zimbra-Tag-Names: ").append(TagUtil.encodeTags(item.getTags()));
                    hdr.append("X-Zimbra-Flags: ").append(item.getFlagString()).append("\n");
                    hdr.append("X-Zimbra-Received: ").append(item.getDate()).append("\n");
                    hdr.append("X-Zimbra-Modified: ").append(item.getChangeDate()).append("\n");
                }
                if (item instanceof Message) {
                    Message msg = (Message) item;
                    if (sync) {
                        resp.addHeader("X-Zimbra-Conv", Integer.toString(msg.getConversationId()));
                        hdr.append("X-Zimbra-Conv: ").append(msg.getConversationId()).append("\n");
                        resp.getOutputStream().write(hdr.toString().getBytes());
                    }
                    resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
                    InputStream is = msg.getContentStream();
                    ByteUtil.copy(is, true, resp.getOutputStream(), false);
                } else if (item instanceof CalendarItem) {
                    CalendarItem calItem = (CalendarItem) item;
                    if (sync) {
                        resp.getOutputStream().write(hdr.toString().getBytes());
                    }
                    resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
                    if (iid.hasSubpart()) {
                        int invId = iid.getSubpartId();
                        MimeMessage mm = calItem.getSubpartMessage(invId);
                        if (mm == null) {
                            // Backward compatibility for pre-5.0.16 ZDesktop: Build a MIME message on the fly.
                            Invite[] invs = calItem.getInvites(invId);
                            if (invs != null && invs.length > 0) {
                                Invite invite = invs[0];
                                mm = CalendarMailSender.createCalendarMessage(invite);
                            }
                        }
                        if (mm != null)
                            mm.writeTo(resp.getOutputStream());
                    } else {
                        InputStream is = calItem.getRawMessage();
                        if (is != null)
                            ByteUtil.copy(is, true, resp.getOutputStream(), false);
                    }
                }
                return;
            } else {
                MimePart mp = null;
                if (item instanceof Message) {
                    mp = getMimePart((Message) item, part);
                } else {
                    CalendarItem calItem = (CalendarItem) item;
                    if (iid.hasSubpart()) {
                        MimeMessage mbp = calItem.getSubpartMessage(iid.getSubpartId());
                        if (mbp != null)
                            mp = Mime.getMimePart(mbp, part);
                    } else {
                        mp = getMimePart(calItem, part);
                    }
                }
                if (mp != null) {
                    String contentType = mp.getContentType();
                    if (contentType == null) {
                        contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
                    }
                    if (contentType.toLowerCase().startsWith(MimeConstants.CT_TEXT_HTML) && (FORMAT_DEFANGED_HTML.equals(fmt) || FORMAT_DEFANGED_HTML_NOT_IMAGES.equals(fmt))) {
                        sendbackDefangedHtml(mp, contentType, resp, fmt);
                    } else {
                        if (!isTrue(Provisioning.A_zimbraAttachmentsViewInHtmlOnly, mbox.getAccountId())) {
                            sendbackOriginalDoc(mp, contentType, req, resp);
                        } else {
                            req.setAttribute(ATTR_MIMEPART, mp);
                            req.setAttribute(ATTR_MSGDIGEST, item.getDigest());
                            req.setAttribute(ATTR_CONTENTURL, req.getRequestURL().toString());
                            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(CONVERSION_PATH);
                            dispatcher.forward(req, resp);
                        }
                    }
                    return;
                }
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errPartNotFound, req));
            }
        } catch (MessagingException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } catch (NoSuchItemException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, L10nUtil.getMessage(MsgKey.errNoSuchItem, req));
    } catch (ServiceException e) {
        returnError(resp, e);
    } finally {
        ZimbraLog.clearContext();
    }
/*
         out.println("hello world "+req.getParameter("id"));
         out.println("path info: "+req.getPathInfo());
         out.println("pathtrans: "+req.getPathTranslated());
         */
}
Also used : OperationContext(com.zimbra.cs.mailbox.OperationContext) Message(com.zimbra.cs.mailbox.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) RequestDispatcher(javax.servlet.RequestDispatcher) CalendarItem(com.zimbra.cs.mailbox.CalendarItem) MailItem(com.zimbra.cs.mailbox.MailItem) ServiceException(com.zimbra.common.service.ServiceException) Mailbox(com.zimbra.cs.mailbox.Mailbox) MimeMessage(javax.mail.internet.MimeMessage) MimePart(javax.mail.internet.MimePart) Invite(com.zimbra.cs.mailbox.calendar.Invite)

Aggregations

MimePart (javax.mail.internet.MimePart)46 MessagingException (javax.mail.MessagingException)22 MimeMessage (javax.mail.internet.MimeMessage)22 IOException (java.io.IOException)15 NoSuchMimePartException (com.axway.ats.action.objects.model.NoSuchMimePartException)12 PackageException (com.axway.ats.action.objects.model.PackageException)11 NoSuchMimePackageException (com.axway.ats.action.objects.model.NoSuchMimePackageException)10 PublicAtsApi (com.axway.ats.common.PublicAtsApi)10 InputStream (java.io.InputStream)10 ServiceException (com.zimbra.common.service.ServiceException)8 Test (org.junit.Test)8 MimePackage (com.axway.ats.action.objects.MimePackage)6 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ContentType (javax.mail.internet.ContentType)6 BaseTest (com.axway.ats.action.BaseTest)5 Message (com.zimbra.cs.mailbox.Message)5 MPartInfo (com.zimbra.cs.mime.MPartInfo)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 ContentType (com.zimbra.common.mime.ContentType)4 ArrayList (java.util.ArrayList)4