Example usage for javax.mail.internet MimeBodyPart setDataHandler

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

Introduction

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

Prototype

@Override
public void setDataHandler(DataHandler dh) throws MessagingException 

Source Link

Document

This method provides the mechanism to set this body part's content.

Usage

From source file:lucee.runtime.net.smtp.SMTPClient.java

public MimeBodyPart toMimeBodyPart(Multipart mp, lucee.runtime.config.Config config, Attachment att)
        throws MessagingException {

    MimeBodyPart mbp = new MimeBodyPart();

    // set Data Source
    String strRes = att.getAbsolutePath();
    if (!StringUtil.isEmpty(strRes)) {

        mbp.setDataHandler(new DataHandler(new ResourceDataSource(config.getResource(strRes))));
    } else//from  w w  w  .ja va  2  s  . c  o  m
        mbp.setDataHandler(new DataHandler(new URLDataSource2(att.getURL())));

    mbp.setFileName(att.getFileName());
    if (!StringUtil.isEmpty(att.getType()))
        mbp.setHeader("Content-Type", att.getType());
    if (!StringUtil.isEmpty(att.getDisposition())) {
        mbp.setDisposition(att.getDisposition());
        /*if(mp instanceof MimeMultipart) {
           ((MimeMultipart)mp).setSubType("related");
        }*/

    }
    if (!StringUtil.isEmpty(att.getContentID()))
        mbp.setContentID(att.getContentID());

    return mbp;
}

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

/**Uncompresses message data*/
public byte[] decompressData(AS2MessageInfo info, byte[] data, String contentType) throws Exception {
    MimeBodyPart compressedPart = new MimeBodyPart();
    compressedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    compressedPart.setHeader("content-type", contentType);
    return (this.decompressData(info, new SMIMECompressed(compressedPart), compressedPart.getSize()));
}

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

/**Returns the signed part of the passed data or null if the data is not detected to be signed*/
public Part getSignedPart(byte[] data, String contentType) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    MimeBodyPart possibleSignedPart = new MimeBodyPart();
    possibleSignedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    possibleSignedPart.setHeader("content-type", contentType);
    return (helper.getSignedEmbeddedPart(possibleSignedPart));
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

private void addAttachedFilePart(FileObject file) throws Exception {
    // create a data source

    MimeBodyPart files = new MimeBodyPart();
    // create a data source
    URLDataSource fds = new URLDataSource(file.getURL());
    // get a data Handler to manipulate this file type;
    files.setDataHandler(new DataHandler(fds));
    // include the file in the data source
    files.setFileName(file.getName().getBaseName());
    // insist on base64 to preserve line endings
    files.addHeader("Content-Transfer-Encoding", "base64");
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(files);/*from  www .j  a v a 2  s .c  om*/
    if (isDetailed()) {
        logDetailed(BaseMessages.getString(PKG, "Mail.Log.AttachedFile", fds.getName()));
    }

}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();/*from  w  w  w  .  j  a  v  a2  s .  c o m*/
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

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

/**Computes the received content MIC and writes it to the message info object
 *//*from   w  ww.  ja  v a2s. 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:com.youxifan.utils.EMail.java

/**
 *   Set the message content/*from   w w w.j  a  v a  2 s. c om*/
 *    @throws MessagingException
 *    @throws IOException
 */
private void setContent() throws MessagingException, IOException {
    //   Local Character Set
    String charSetName;
    if (m_encoding == null) {
        charSetName = System.getProperty("file.encoding"); //   Cp1252
        if (charSetName == null || charSetName.length() == 0)
            charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1
    } else {
        charSetName = m_encoding;
    }
    m_msg.setSubject(getSubject(), charSetName);

    //   Simple Message
    if (m_attachments == null || m_attachments.size() == 0) {
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            m_msg.setText(getMessageCRLF(), charSetName);
        else
            m_msg.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));
        //
        log.info("(simple) " + getSubject());
    } else //   Multi part message   ***************************************
    {
        //   First Part - Message
        MimeBodyPart mbp_1 = new MimeBodyPart();
        mbp_1.setText("");
        if (m_messageHTML == null || m_messageHTML.length() == 0)
            mbp_1.setText(getMessageCRLF(), charSetName);
        else
            mbp_1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html")));

        // Create Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp_1);
        log.info("(multi) " + getSubject() + " - " + mbp_1);

        //   for all attachments
        for (int i = 0; i < m_attachments.size(); i++) {
            Object attachment = m_attachments.get(i);
            DataSource ds = null;
            if (attachment instanceof File) {
                File file = (File) attachment;
                if (file.exists())
                    ds = new FileDataSource(file);
                else {
                    log.warn("File does not exist: " + file);
                    continue;
                }
            } else if (attachment instanceof URL) {
                URL url = (URL) attachment;
                ds = new URLDataSource(url);
            } else if (attachment instanceof DataSource)
                ds = (DataSource) attachment;
            else {
                log.warn("Attachement type unknown: " + attachment);
                continue;
            }
            //   Attachment Part
            MimeBodyPart mbp_2 = new MimeBodyPart();
            mbp_2.setDataHandler(new DataHandler(ds));
            mbp_2.setFileName(ds.getName());
            log.info("Added Attachment " + ds.getName() + " - " + mbp_2);
            mp.addBodyPart(mbp_2);
        }

        //   Add to Message
        m_msg.setContent(mp);
    } //   multi=part
}

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 www.j  a v a2 s  .  co  m*/
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:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;//  w  ww  .  ja v a 2  s  .c o m
    String contentType;
    String fileExtension;
    IDataStore emailDispatchDataStore;
    String nameSuffix;
    String descriptionSuffix;
    String containedFileName;
    String zipFileName;
    boolean reportNameInSubject;

    logger.debug("IN");
    try {
        parametersMap = dispatchContext.getParametersMap();
        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
        nameSuffix = dispatchContext.getNameSuffix();
        descriptionSuffix = dispatchContext.getDescriptionSuffix();
        containedFileName = dispatchContext.getContainedFileName() != null
                && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName()
                        : document.getName();
        zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("")
                ? dispatchContext.getZipMailName()
                : document.getName();
        reportNameInSubject = dispatchContext.isReportNameInSubject();

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = dispatchContext.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = dispatchContext.getMailTxt();

        String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return false;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }

            //session = Session.getDefaultInstance(props, auth);
            session = Session.getInstance(props, auth);
            //session.setDebug(true);
            //session.setDebugOut(null);
            logger.info("Session.getInstance(props, auth)");

        } else {
            //session = Session.getDefaultInstance(props);
            session = Session.getInstance(props);
            logger.info("Session.getInstance(props)");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type

        String subject = mailSubj;

        if (reportNameInSubject) {
            subject += " " + document.getName() + nameSuffix;
        }

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + descriptionSuffix);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = null;
        //if zip requested
        if (dispatchContext.isZipMailDocument()) {
            mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
        }
        //else 
        else {
            sds = new SchedulerDataSource(executionOutput, contentType,
                    containedFileName + nameSuffix + fileExtension);
            mbp2.setDataHandler(new DataHandler(sds));
            mbp2.setFileName(sds.getName());
        }

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

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

/**Decrypts the data of a message with all given certificates etc
 * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 *//*from   www  . j  av a  2s  .c om*/
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired",
                        new Object[] { info.getMessageId(), recipientInfo.getRID() }), info);
            }
        }
        if (this.logger != null) {
            this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned",
                    new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}