Example usage for javax.mail.internet MimeBodyPart getContentType

List of usage examples for javax.mail.internet MimeBodyPart getContentType

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart getContentType.

Prototype

@Override
public String getContentType() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Content-Type" header field.

Usage

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

private void doTestPdfAttachment(boolean useFs) throws IOException, MessagingException {
    emailerConfig.setFileStorageUsed(useFs);
    testMailSender.clearBuffer();//from  w  w  w  .  j  a  va 2 s.  c om

    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:com.haulmont.cuba.core.app.EmailerTest.java

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

    String attachmentText = "Test Attachment Text";
    EmailAttachment textAttach = EmailAttachment.createTextAttachment(attachmentText, "ISO-8859-1", "test.txt");

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

    emailer.processQueuedEmails();

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

    // check content bytes
    Object content = firstAttachment.getContent();
    assertTrue(content instanceof InputStream);
    byte[] data = IOUtils.toByteArray((InputStream) content);
    assertEquals(attachmentText, new String(data, "ISO-8859-1"));

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

    // charset header
    String contentType = firstAttachment.getContentType();
    assertTrue(contentType.toLowerCase().contains("charset=iso-8859-1"));
}

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

/**Computes the received content MIC and writes it to the message info object
 */// www  .  j a v a  2s  .  c o m
public void computeReceivedContentMIC(byte[] rawMessageData, AS2Message message, Part partWithHeader,
        String contentType) throws Exception {
    AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
    boolean encrypted = messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE;
    boolean signed = messageInfo.getSignType() != AS2Message.SIGNATURE_NONE;
    boolean compressed = messageInfo.getCompressionType() != AS2Message.COMPRESSION_NONE;
    BCCryptoHelper helper = new BCCryptoHelper();
    String sha1digestOID = helper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    //compute the MIC
    if (signed) {
        //compute the content-type for the signed part.
        //If the message was not encrypted the content-type should simply be taken from the header
        //else we have to look into the part
        String singedPartContentType = null;
        if (!encrypted) {
            singedPartContentType = contentType;
        } else {
            InputStream dataIn = message.getDecryptedRawDataInputStream();
            MimeBodyPart contentTypeTempPart = new MimeBodyPart(dataIn);
            dataIn.close();
            singedPartContentType = contentTypeTempPart.getContentType();
        }
        //ANY signed data
        //4.1 MIC Calculation For Signed Message
        //For any signed message, the MIC to be returned is calculated over
        //the same data that was signed in the original message as per [AS1].
        //The signed content will be a mime bodypart that contains either
        //compressed or uncompressed data.
        MimeBodyPart signedPart = new MimeBodyPart();
        signedPart.setDataHandler(
                new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType)));
        signedPart.setHeader("Content-Type", singedPartContentType);
        String digestOID = helper.getDigestAlgOIDFromSignature(signedPart);
        signedPart = null;
        String mic = helper.calculateMIC(partWithHeader, digestOID);
        String digestAlgorithmName = helper.convertOIDToAlgorithmName(digestOID);
        messageInfo.setReceivedContentMIC(mic + ", " + digestAlgorithmName);
    } else if (!signed && !compressed && !encrypted) {
        //uncompressed, unencrypted, unsigned: plaintext mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(rawMessageData, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && compressed && !encrypted) {
        //compressed, unencrypted, unsigned: uncompressed data mic
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.3 MIC Calculation For Unencrypted, Unsigned Message
        //For unsigned, unencrypted messages, the MIC is calculated
        //over the uncompressed data content including all MIME header
        //fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else if (!signed && encrypted) {
        //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
        //4.2 MIC Calculation For Encrypted, Unsigned Message
        //For encrypted, unsigned messages, the MIC to be returned is
        //calculated over the uncompressed data content including all
        //MIME header fields and any applied Content-Transfer-Encoding.
        String mic = helper.calculateMIC(message.getDecryptedRawData(), sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    } else {
        //this should never happen:
        String mic = helper.calculateMIC(partWithHeader, sha1digestOID);
        messageInfo.setReceivedContentMIC(mic + ", sha1");
    }
}

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

/**Verifies the signature of the passed message. If the transfer mode is unencrypted/unsigned, a new Bodypart will be constructed
 *@return the payload part, this is important to compute the MIC later
 *//*from   ww  w  .j a v  a2 s  .c  om*/
private Part verifySignature(AS2Message message, Partner sender, String contentType) throws Exception {
    if (this.certificateManagerSignature == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser.verifySignature: pass a certification manager for the signature before calling verifySignature()",
                message);
    }
    AS2Info as2Info = message.getAS2Info();
    if (!as2Info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) as2Info;
        if (messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            InputStream memIn = message.getDecryptedRawDataInputStream();
            MimeBodyPart testPart = new MimeBodyPart(memIn);
            memIn.close();
            contentType = testPart.getContentType();
        }
    }
    Part signedPart = this.getSignedPart(message.getDecryptedRawData(), contentType);
    //part is NOT signed but is defined to be signed
    if (signedPart == null) {
        as2Info.setSignType(AS2Message.SIGNATURE_NONE);
        if (as2Info.isMDN()) {
            this.logger.log(Level.INFO, this.rb.getResourceString("mdn.notsigned", as2Info.getMessageId()),
                    as2Info);
            //MDN is not signed but should be signed
            if (sender.isSignedMDN()) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("mdn.unsigned.error",
                        new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info);
            }
        } else {
            this.logger.log(Level.INFO, this.rb.getResourceString("msg.notsigned", as2Info.getMessageId()),
                    as2Info);
        }
        if (!as2Info.isMDN() && sender.getSignType() != AS2Message.SIGNATURE_NONE) {
            throw new AS2Exception(AS2Exception.INSUFFICIENT_SECURITY_ERROR,
                    "Incoming messages from AS2 partner " + sender.getAS2Identification()
                            + " are defined to be signed.",
                    message);
        }
        //if the message has been unsigned it is required to set a new datasource
        MimeBodyPart unsignedPart = new MimeBodyPart();
        unsignedPart.setDataHandler(
                new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType)));
        unsignedPart.setHeader("content-type", contentType);
        return (unsignedPart);
    } else {
        //it is definitly a signed mdn
        if (as2Info.isMDN()) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("mdn.signed", as2Info.getMessageId()),
                        as2Info);
            }
            as2Info.setSignType(this.getDigestFromSignature(signedPart));
            //MDN is signed but shouldn't be signed'
            if (!sender.isSignedMDN()) {
                if (this.logger != null) {
                    this.logger.log(Level.WARNING, this.rb.getResourceString("mdn.signed.error",
                            new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info);
                }
            }
        } else {
            //its no MDN, its a AS2 message
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("msg.signed", as2Info.getMessageId()),
                        as2Info);
            }
            int signDigest = this.getDigestFromSignature(signedPart);
            String digest = null;
            if (signDigest == AS2Message.SIGNATURE_SHA1) {
                digest = "SHA1";
            } else if (signDigest == AS2Message.SIGNATURE_MD5) {
                digest = "MD5";
            }
            as2Info.setSignType(signDigest);
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("signature.analyzed.digest",
                        new Object[] { as2Info.getMessageId(), digest }), as2Info);
            }
        }
    }
    MimeBodyPart payloadPart = null;
    try {
        String signAlias = this.certificateManagerSignature
                .getAliasByFingerprint(sender.getSignFingerprintSHA1());
        payloadPart = this.verifySignedPartUsingAlias(message, signAlias, signedPart, contentType);
    } catch (AS2Exception e) {
        //retry to verify the signature with the second certificate if this is possible
        String secondAlias = this.certificateManagerSignature
                .getAliasByFingerprint(sender.getSignFingerprintSHA1(2));
        if (secondAlias != null) {
            payloadPart = this.verifySignedPartUsingAlias(message, secondAlias, signedPart, contentType);
        } else {
            throw e;
        }
    }
    return (payloadPart);
}

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

/**Analyzes and creates passed message data
 *///from w  w w  .  j  a  v  a  2s .c om
public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType)
        throws AS2Exception {
    AS2Message message = new AS2Message(new AS2MessageInfo());
    if (this.configConnection == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message);
    }
    try {
        //decode the content transfer encoding if set
        rawMessageData = this.processContentTransferEncoding(rawMessageData, header);
        //check if this is a MDN
        MDNParser mdnParser = new MDNParser();
        AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType);
        //its a MDN
        if (mdnInfo != null) {
            message.setAS2Info(mdnInfo);
            mdnInfo.initializeByRequestHeader(header);
            return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser));
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            messageInfo.initializeByRequestHeader(header);
            //inbound AS2 message, no MDN
            //no futher processing if the message does not contain a message id
            if (messageInfo.getMessageId() == null) {
                return (message);
            }
            //figure out if the MDN should be signed NOW. If an error occurs beyond this point
            //the info has to know if the returned MDN should be signed
            messageInfo.getDispositionNotificationOptions()
                    .setHeaderValue(header.getProperty("disposition-notification-options"));
            //check for existing partners
            PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection);
            Partner sender = partnerAccess.getPartner(messageInfo.getSenderId());
            Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId());
            if (sender == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message);
            }
            if (receiver == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message);
            }
            if (!receiver.isLocalStation()) {
                throw new AS2Exception(
                        AS2Exception.PROCESSING_ERROR, "The receiver of the message ("
                                + receiver.getAS2Identification() + ") is not defined as a local station.",
                        message);
            }
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            //check if the message already exists
            AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess,
                    messageInfo.getMessageId());
            if (alreadyExistingInfo != null) {
                //perform notification: Resend detected, manual interaction might be required
                Notification notification = new Notification(this.configConnection, this.runtimeConnection);
                notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver);
                throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id "
                        + messageInfo.getMessageId()
                        + " has been already processed successfully by the system or is pending ("
                        + alreadyExistingInfo.getInitDate() + "). Please "
                        + " resubmit the message with a new message id instead or resending it if it should be processed again.",
                        new AS2Message(messageInfo));
            }
            messageAccess.initializeOrUpdateMessage(messageInfo);
            if (this.logger != null) {
                //do not log before because the logging process is related to an already created message in the transaction log
                this.logger.log(
                        Level.FINE, this.rb
                                .getResourceString("msg.incoming",
                                        new Object[] { messageInfo.getMessageId(),
                                                AS2Tools.getDataSizeDisplay(rawMessageData.length) }),
                        messageInfo);
            }
            //indicates if a sync or async mdn is requested
            messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option"));
            messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null
                    || header.getProperty("receipt-delivery-option").trim().length() == 0);
            message.setRawData(rawMessageData);
            byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver);
            //may be already compressed here. Decompress first before going further
            if (this.contentTypeIndicatesCompression(contentType)) {
                byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData,
                        contentType);
                message.setDecryptedRawData(decompressed);
                //content type has changed now, get it from the decompressed data
                ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed);
                MimeBodyPart tempPart = new MimeBodyPart(memIn);
                memIn.close();
                contentType = tempPart.getContentType();
            } else {
                //check the MIME structure that is embedded in decryptedData for its content type
                ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData);
                MimeMessage possibleCompressedPart = new MimeMessage(
                        Session.getInstance(System.getProperties()), memIn);
                memIn.close();
                if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) {
                    long compressedSize = possibleCompressedPart.getSize();
                    byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(),
                            new SMIMECompressed(possibleCompressedPart), compressedSize);
                    message.setDecryptedRawData(decompressed);
                } else {
                    message.setDecryptedRawData(decryptedData);
                }
            }
            decryptedData = null;
            Part payloadPart = this.verifySignature(message, sender, contentType);
            //decompress the data if it has been sent compressed, only possible for signed data
            if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) {
                //signed message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.1 MIC Calculation For Signed Message
                //For any signed message, the MIC to be returned is calculated over
                //the same data that was signed in the original message as per [AS1].
                //The signed content will be a mime bodypart that contains either
                //compressed or uncompressed data.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
                payloadPart = this.decompressData(payloadPart, message);
                this.writePayloadsToMessage(payloadPart, message, header);
            } else {
                //this is an unsigned message
                this.writePayloadsToMessage(message.getDecryptedRawData(), message, header);
                //unsigned message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.2 MIC Calculation For Encrypted, Unsigned Message
                //For encrypted, unsigned messages, the MIC to be returned is
                //calculated over the uncompressed data content including all
                //MIME header fields and any applied Content-Transfer-Encoding.

                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.3 MIC Calculation For Unencrypted, Unsigned Message
                //For unsigned, unencrypted messages, the MIC is calculated
                //over the uncompressed data content including all MIME header
                //fields and any applied Content-Transfer-Encoding.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
            }
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments",
                        new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }),
                        messageInfo);
            }
            return (message);
        }
    } catch (Exception e) {
        if (e instanceof AS2Exception) {
            throw (AS2Exception) e;
        } else {
            throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message);
        }
    }
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void notifyEmailUpdated(String oldAddress, String newAddress) {
    try {/*from   ww w.  j a  v a  2 s  . c o  m*/
        //Create the message body
        final MimeBodyPart msg = new MimeBodyPart();
        msg.setContent(
                "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n"
                        + "New Email Address: " + newAddress + "\n" + "\n"
                        + "If you have any questions, please contact your Human Resources department.",
                "text/plain");

        final MimeMessage message = this.javaMailSender.createMimeMessage();
        final Address[] recipients;
        if (StringUtils.isNotEmpty(oldAddress)) {
            recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) };
        } else {
            recipients = new Address[] { new InternetAddress(newAddress) };
        }
        message.setRecipients(RecipientType.TO, recipients);
        message.setFrom(new InternetAddress("payroll@ohr.wisc.edu"));
        message.setSubject("Business Email Address Change");

        // sign the message body
        if (this.smimeSignedGenerator != null) {
            final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC");
            message.setContent(mm, mm.getContentType());
        }
        // no signing keystore configured, send the message unsigned
        else {
            message.setContent(msg.getContent(), msg.getContentType());
        }

        message.saveChanges();

        this.javaMailSender.send(message);

        this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress);
    } catch (Exception e) {
        this.logger.error(
                "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImplTest.java

@Test
public void testEncryptSignedQuotedPrintableSoftBreaksDirectBC() throws Exception {
    MimeMessage message = loadMessage("qp-soft-breaks-signed.eml");

    SMIMEEnvelopedGenerator envelopedGenerator = new SMIMEEnvelopedGenerator();

    JceKeyTransRecipientInfoGenerator infoGenerator = new JceKeyTransRecipientInfoGenerator(
            encryptionCertificate);//from w w w.ja  v a 2 s.c  om

    envelopedGenerator.addRecipientInfoGenerator(infoGenerator);

    JceCMSContentEncryptorBuilder encryptorBuilder = new JceCMSContentEncryptorBuilder(
            new ASN1ObjectIdentifier("1.2.840.113549.3.7"), 0).setProvider("BC");

    MimeBodyPart bodyPart = envelopedGenerator.generate(message, encryptorBuilder.build());

    MimeMessage newMessage = new MimeMessage(MailSession.getDefaultSession());

    newMessage.setContent(bodyPart.getContent(), bodyPart.getContentType());

    newMessage.saveChanges();

    File file = new File(tempDir, "testEncryptSignedQuotedPrintableSoftBreaksDirectBC.eml");

    FileOutputStream output = new FileOutputStream(file);

    MailUtils.writeMessage(newMessage, output);

    newMessage = MailUtils.loadMessage(file);

    assertEquals(SMIMEHeader.Type.ENCRYPTED, SMIMEHeader.getSMIMEContentType(newMessage));

    File opensslOutputFileSigned = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl-signed.eml");

    decryptMessage(file, privateKeyEntry.getPrivateKey(), opensslOutputFileSigned);

    newMessage = MailUtils.loadMessage(opensslOutputFileSigned);

    assertTrue(newMessage.isMimeType("multipart/signed"));

    File opensslOutputFile = new File(tempDir,
            "testEncryptSignedQuotedPrintableSoftBreaksDirectBC-openssl.eml");

    verifyMessage(opensslOutputFileSigned, rootCertificate, opensslOutputFile);

    newMessage = MailUtils.loadMessage(opensslOutputFile);

    assertTrue(newMessage.isMimeType("text/plain"));

    assertEquals(SMIMEHeader.Type.NO_SMIME, SMIMEHeader.getSMIMEContentType(newMessage));
}

From source file:org.apache.synapse.transport.mail.MailUtils.java

public InputStream getInputStream(Object message) {
    try {/*from  ww w.  j  a v a2s  .  c o  m*/
        if (message instanceof MimeMessage) {
            MimeMessage msg = (MimeMessage) message;
            if (msg.getContent() instanceof Multipart) {
                MimeBodyPart firstTextPart = null;

                Multipart mp = (Multipart) msg.getContent();
                for (int i = 0; i < mp.getCount(); i++) {
                    MimeBodyPart mbp = (MimeBodyPart) mp.getBodyPart(i);
                    String contType = mbp.getContentType();

                    if (contType != null && (contType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) != -1
                            || contType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) != -1)) {
                        // this part is a SOAP 11 or 12 payload, treat this as the message
                        return mbp.getInputStream();
                    } else if (mbp == null && contType.indexOf("plain/text") != -1) {
                        firstTextPart = mbp;
                    }
                }
                // if a soap 11 or soap12 payload was not found, treat first text part as message
                return firstTextPart.getInputStream();

            } else {
                return ((Message) message).getInputStream();
            }
        }
    } catch (Exception e) {
        handleException("Error creating an input stream to : " + ((Message) message).getMessageNumber(), e);
    }
    return null;
}

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

private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception {

    MimeBodyPart mbp = (MimeBodyPart) part;
    String fileName = mbp.getFileName();
    String fileType = mbp.getContentType();
    String fileId = mbp.getContentID();
    String fileEncoding = mbp.getEncoding();
    String attContent;/*from w  ww  .ja v a 2s  .  c  o m*/

    if (fileName == null || fileName.length() < 2) {
        fileName = new String("Unknown");
        if (fileType.indexOf("name") > 0) {
            int i = fileType.indexOf("name");
            int j = fileType.indexOf("\"", i + 1);
            if (j != -1) {
                int k = fileType.indexOf("\"", j + 1);
                if (k != -1) {
                    fileName = fileType.substring(j + 1, k);
                }

            } else {
                int k = fileType.indexOf(";", i + 1);
                if (k != -1) {
                    fileName = fileType.substring(i + 5, k);

                } else {
                    fileName = fileType.substring(i + 5, fileType.length());
                }

            }
        }
    }

    InboxAttachment entryItem = new InboxAttachment();

    entryItem.setFileName(fileName);
    if (fileType != null)
        entryItem.setContentType(fileType);

    if (mbp.getContent() instanceof InputStream) {
        InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE);

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuffer att = new StringBuffer();
        String thisLine = reader.readLine();

        while (thisLine != null) {
            att.append(thisLine);
            thisLine = reader.readLine();
        }

        attContent = att.toString();
        //           MimeUtility.encode(part.getOutputStream(), "base64");
        //           attachments += saveFile(part.getFileName(), part.getInputStream());

    } else {
        attContent = part.getContent().toString();
    }

    entryItem.setContent(attContent);
    entryItem.setContentId(fileId);

    inboxentry.addInboxAttachment(entryItem);

}

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

public Attach getAttach(Part part, String baseStorePath) throws MessagingException, IOException {
    MimeBodyPart mimePart = (MimeBodyPart) part;
    Attach attach = new Attach();
    if (StringUtils.isEmpty(mimePart.getFileName())) {
        attach.setFileName("UNKNOWN");
    } else {/* w w  w .j  ava 2 s  . c  om*/
        String fileName = mimePart.getFileName();
        String encoded = System.getProperty("mail.mime.encodefilename");
        if (Boolean.parseBoolean(encoded)) {
            fileName = MimeUtility.decodeText(fileName);
        }
        attach.setFileName(fileName);
    }
    ContentType type = new ContentType(mimePart.getContentType());
    attach.setMimeType(type.getBaseType());
    InputStream inputStream = mimePart.getDataHandler().getInputStream();
    attach.buildMd5Checksum(inputStream);
    attach.buildPath(mimePart, baseStorePath);
    return attach;
}