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:org.elasticsearch.river.email.EmailToJson.java

public static void saveAttachment(Part part, String destDir)
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();

        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            String disp = bodyPart.getDisposition();
            if (disp != null
                    && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart, destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }/*  w  w w  . ja  v  a2 s .c o  m*/
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();/*from   ww w.  j a v  a  2 s  . c  o  m*/

    byte[] pdfBytes = new byte[] { 1, 2, 3, 4, 6 };
    String fileName = "invoice.pdf";
    EmailAttachment pdfAttach = new EmailAttachment(pdfBytes, fileName);

    EmailInfo myInfo = new EmailInfo("test@example.com", "Test", null, "Test", pdfAttach);
    emailer.sendEmailAsync(myInfo);

    emailer.processQueuedEmails();

    MimeMessage msg = testMailSender.fetchSentEmail();
    MimeBodyPart attachment = getFirstAttachment(msg);

    // check content bytes
    InputStream content = (InputStream) attachment.getContent();
    byte[] data = IOUtils.toByteArray(content);
    assertByteArrayEquals(pdfBytes, data);

    // disposition
    assertEquals(Part.ATTACHMENT, attachment.getDisposition());

    // mime type
    String contentType = attachment.getContentType();
    assertTrue(contentType.contains("application/pdf"));
}

From source file:org.apache.axis2.transport.mail.SimpleMailListener.java

private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault {
    //TODO we assume for the time being that there is only one attachement and this attachement contains  the soap evelope
    try {//  www .  jav a  2 s.  c  om
        Multipart mp = (Multipart) msg.getContent();
        if (mp != null) {
            for (int i = 0, n = mp.getCount(); i < n; i++) {
                Part part = mp.getBodyPart(i);

                String disposition = part.getDisposition();

                if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                    String soapAction;

                    /* Set the Charactorset Encoding */
                    String contentType = part.getContentType();
                    String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType);
                    if (charSetEncoding != null) {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                charSetEncoding);
                    } else {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                MessageContext.DEFAULT_CHAR_SET_ENCODING);
                    }

                    /* SOAP Action */
                    soapAction = getMailHeaderFromPart(part,
                            org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION);
                    msgContext.setSoapAction(soapAction);

                    String contentDescription = getMailHeaderFromPart(part, "Content-Description");

                    /* As an input stream - using the getInputStream() method.
                    Any mail-specific encodings are decoded before this stream is returned.*/
                    if (contentDescription != null) {
                        msgContext.setTo(new EndpointReference(contentDescription));
                    }

                    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
                        TransportUtils.processContentTypeForAction(contentType, msgContext);
                    } else {
                        // According to the mail sepec, mail transport should support only
                        // application/soap+xml;
                        String message = "According to the mail sepec, mail transport "
                                + "should support only application/soap+xml";
                        log.error(message);
                        throw new AxisFault(message);
                    }

                    String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding");
                    if (!(cte != null && cte.equalsIgnoreCase("base64"))) {
                        String message = "Processing of Content-Transfer-Encoding faild.";
                        log.error(message);
                        throw new AxisFault(message);
                    }
                    InputStream inputStream = part.getInputStream();
                    SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream,
                            contentType);
                    msgContext.setEnvelope(envelope);
                }
            }

        }
    } catch (IOException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (XMLStreamException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

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

/**
 * Prepare extract multipart./*w  w  w .  j  a  v  a  2  s . com*/
 *
 * @param xhtml
 *            the xhtml
 * @param part
 *            the part
 * @param parentPart
 *            the parent part
 * @param context
 *            the context
 * @param attachmentList
 *            is list with attachments to fill
 * @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
 */
private void prepareExtractMultipart(XHTMLContentHandler xhtml, Part part, Part parentPart,
        ParseContext context, List<String> attachmentList)
        throws MessagingException, IOException, SAXException, TikaException {

    String disposition = part.getDisposition();
    if ((disposition != null && disposition.contains(Part.ATTACHMENT))) {
        String fileName = part.getFileName();
        if (fileName != null && fileName.startsWith("=?")) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attachmentList.add(fileName);
    }

    String[] header = part.getHeader("Content-ID");
    String key = null;
    if (header != null) {
        for (String string : header) {
            key = string;
        }
    }

    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            prepareExtractMultipart(xhtml, mp.getBodyPart(i), part, context, attachmentList);
        }
    } else if (part.isMimeType(MimetypeMap.MIMETYPE_RFC822)) {
        prepareExtractMultipart(xhtml, (Part) part.getContent(), part, context, attachmentList);
    } else {

        if (key == null) {
            return;
        }
        // if ((disposition != null && disposition.contains(Part.INLINE))) {
        InputStream stream = part.getInputStream();

        File file = new File(workingDirectory, System.currentTimeMillis() + "");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(stream, fileOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
        String src = file.getName();
        String replace = key.replace("<", "").replace(">", "");
        referencesCache.put(replace, src);
        // }

    }
}

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

/**
 * Processes part of a message/*from w  w  w.  ja v a2  s . co  m*/
 */
private static String handleSimplePart(Part part, List<EmailAttachment> attachments, boolean ignoreAttachments)
        throws MessagingException, IOException {
    // Check for content disposition and content type
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    LOGGER.debug("disposition=" + disposition);
    LOGGER.debug("Body type is: " + contentType);

    // tread if the part is a message
    boolean inlineMessage = part.isMimeType("message/rfc822");
    if (inlineMessage) {
        LOGGER.debug("Inner message:" + part.getFileName());
        Message subMessage = (Message) part.getContent();
        StringBuffer s = handlePart(subMessage, attachments, ignoreAttachments);
        System.out.println();
        return s.toString();
    }
    if (disposition == null) {
        if ("image/BMP".equals(contentType)) {
            // BMP image add as attachment
            if (ignoreAttachments == false) {
                try {
                    attachments.add(createEmailAttachment(part, "image.bmp"));
                } catch (Exception e) {
                    // just ignore
                }
            }
            return null;
        } else if (part.isMimeType("text/*")) {
            return getText(part);
        } else {
            if (ignoreAttachments == false) {
                handleAttachment(part, attachments);
            }
            return null;
        }
    }
    if (disposition.equalsIgnoreCase(Part.INLINE)) {
        return handleInline(part, attachments, ignoreAttachments);
    }
    if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (ignoreAttachments == false) {
            handleAttachment(part, attachments);
        }
        return null;
    }
    LOGGER.debug("Unknown disposition:" + disposition + "Threat as attachment");
    if (ignoreAttachments == false) {
        handleAttachment(part, attachments);
    }
    return null;
}

From source file:org.apache.camel.component.mail.MailBinding.java

private MimeMultipart createMixedMultipartAttachments(MailConfiguration configuration, Exchange exchange)
        throws MessagingException, IOException {

    // fill the body with text
    MimeMultipart multipart = new MimeMultipart();
    multipart.setSubType("mixed");
    addBodyToMultipart(configuration, multipart, exchange);
    String partDisposition = configuration.isUseInlineAttachments() ? Part.INLINE : Part.ATTACHMENT;
    if (exchange.getIn().hasAttachments()) {
        addAttachmentsToMultipart(multipart, partDisposition, exchange);
    }/*from   www.  j a  va  2  s. c o m*/
    return multipart;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Create a mail from a Mail object//from w ww  .  j a  v a 2s . co m
 */
public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException,
        AccessDeniedException, RepositoryException, IOException, DatabaseException {
    log.debug("create({})", mail);
    Session mailSession = getMailSession();
    MimeMessage msg = new MimeMessage(mailSession);

    if (mail.getFrom() != null) {
        InternetAddress from = new InternetAddress(mail.getFrom());
        msg.setFrom(from);
    } else {
        msg.setFrom();
    }

    InternetAddress[] to = new InternetAddress[mail.getTo().length];
    int i = 0;

    for (String strTo : mail.getTo()) {
        to[i++] = new InternetAddress(strTo);
    }

    // Build a multiparted mail with HTML and text content for better SPAM behaviour
    MimeMultipart content = new MimeMultipart();

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        // HTML Part
        MimeBodyPart htmlPart = new MimeBodyPart();
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
        htmlContent.append("<html>\n<head>\n");
        htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n");
        htmlContent.append("</head>\n<body>\n");
        htmlContent.append(mail.getContent());
        htmlContent.append("\n</body>\n</html>");
        htmlPart.setContent(htmlContent.toString(), "text/html");
        htmlPart.setHeader("Content-Type", "text/html");
        htmlPart.setDisposition(Part.INLINE);
        content.addBodyPart(htmlPart);
    } else {
        log.warn("Email does not specify content MIME type");

        // Text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText(mail.getContent());
        textPart.setHeader("Content-Type", "text/plain");
        textPart.setDisposition(Part.INLINE);
        content.addBodyPart(textPart);
    }

    for (Document doc : mail.getAttachments()) {
        InputStream is = null;
        FileOutputStream fos = null;
        String docName = PathUtils.getName(doc.getPath());

        try {
            is = OKMDocument.getInstance().getContent(token, doc.getPath(), false);
            File tmp = File.createTempFile("okm", ".tmp");
            fos = new FileOutputStream(tmp);
            IOUtils.copy(is, fos);
            fos.flush();

            // Document attachment part
            MimeBodyPart docPart = new MimeBodyPart();
            DataSource source = new FileDataSource(tmp.getPath());
            docPart.setDataHandler(new DataHandler(source));
            docPart.setFileName(docName);
            docPart.setDisposition(Part.ATTACHMENT);
            content.addBodyPart(docPart);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);
        }
    }

    msg.setHeader("MIME-Version", "1.0");
    msg.setHeader("Content-Type", content.getContentType());
    msg.addHeader("Charset", "UTF-8");
    msg.setRecipients(Message.RecipientType.TO, to);
    msg.setSubject(mail.getSubject(), "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content);
    msg.saveChanges();

    log.debug("create: {}", msg);
    return msg;
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

public static void handlePart(String foldername, Part part) throws MessagingException, IOException {
    String disposition = part.getDisposition();
    // String contentType = part.getContentType();

    if ((disposition != null)
            && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
        saveFile(foldername, MimeUtility.decodeText(part.getFileName()), part.getInputStream());
    }/*from  ww  w  .j av a2 s  . co m*/
}

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

public static void attach(MimeMultipart multipart, Vector attachments, String charset)
        throws MessagingException {
    for (int xindex = 0; xindex < attachments.size(); xindex++) {
        Object xobject = attachments.elementAt(xindex);

        // attach based on type of object
        if (xobject instanceof Part) {
            attach(multipart, (Part) xobject, charset);
        } else if (xobject instanceof File) {
            attach(multipart, (File) xobject, charset);
        } else if (xobject instanceof String) {
            attach(multipart, (String) xobject, charset, Part.ATTACHMENT, false);
        } else if (xobject instanceof vCard) {
            attach(multipart, (vCard) xobject, charset);
        } else {//w w w  .  java  2  s  .  co m
            throw new MessagingException("Cannot attach objects of type " + xobject.getClass().getName());
        }
    }
}

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

/**
 * DOCUMENT ME!/*  ww w .  j  a va  2 s  .co  m*/
 *
 * @param multipart DOCUMENT ME!
 * @param file DOCUMENT ME!
 * @param charset DOCUMENT ME!
 *
 * @throws MessagingException DOCUMENT ME!
 */
public static void attach(MimeMultipart multipart, File file, String charset) throws MessagingException {
    // UNDONE how to specify the character set of the file???
    MimeBodyPart xbody = new MimeBodyPart();
    FileDataSource xds = new FileDataSource(file);
    DataHandler xdh = new DataHandler(xds);
    xbody.setDataHandler(xdh);

    //System.out.println(xdh.getContentType());
    // UNDONE
    // xbody.setContentLanguage( String ); // this could be language from Locale
    // xbody.setContentMD5( String md5 ); // don't know about this yet
    xbody.setDescription("File Attachment: " + file.getName(), charset);
    xbody.setDisposition(Part.ATTACHMENT);
    MessageUtilities.setFileName(xbody, file.getName(), charset);

    multipart.addBodyPart(xbody);
}