Example usage for javax.mail.internet MimeBodyPart setHeader

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

Introduction

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

Prototype

@Override
public void setHeader(String name, String value) throws MessagingException 

Source Link

Document

Set the value for this header_name.

Usage

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Add attachments to a multipart message
 * //w w w .  java  2s .  com
 * @param multipart Multipart message
 * @param attachments List of attachments
 */
public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context)
        throws XWikiException, IOException, MessagingException {
    String name = attachment.getFilename();
    byte[] stream = attachment.getContent();
    File temp = File.createTempFile("tmpfile", ".tmp");
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(stream);
    fos.close();
    DataSource source = new FileDataSource(temp);
    MimeBodyPart part = new MimeBodyPart();
    String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name);

    part.setDataHandler(new DataHandler(source));
    part.setHeader("Content-Type", mimeType);
    part.setFileName(name);
    part.setContentID("<" + name + ">");
    part.setDisposition("inline");

    temp.deleteOnExit();

    return part;
}

From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java

public void send(EmailModel model) throws EmailException {

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Sending email: " + model);

    if (model == null)
        throw new NullPointerException("model");

    Properties emailProps;/*from w ww . ja va 2  s .  c  o  m*/
    Session emailSession;

    // set the relay host as a property of the email session
    emailProps = new Properties();
    emailProps.setProperty("mail.transport.protocol", "smtp");
    emailProps.put("mail.smtp.host", host);
    emailProps.setProperty("mail.smtp.port", String.valueOf(port));
    // set the timeouts
    emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS));
    emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS));

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Email properties: " + emailProps);

    // set up email session
    emailSession = Session.getInstance(emailProps, null);
    emailSession.setDebug(false);

    String from;
    String displayFrom;

    String body;
    String subject;
    List<EmailAttachment> attachments;

    if (model.getFrom() == null)
        throw new NullPointerException("from");
    if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc())
            && MiscUtils.isEmpty(model.getCc()))
        throw new IllegalArgumentException("model has no addresses");

    from = model.getFrom();
    displayFrom = model.getDisplayFrom();
    body = model.getBody();
    subject = model.getSubject();
    attachments = model.getAttachments();

    MimeMessage emailMessage;
    InternetAddress emailAddressFrom;

    // create an email message from the current session
    emailMessage = new MimeMessage(emailSession);

    // set the from
    try {
        emailAddressFrom = new InternetAddress(from, displayFrom);
        emailMessage.setFrom(emailAddressFrom);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    if (!MiscUtils.isEmpty(model.getTo()))
        setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO);
    if (!MiscUtils.isEmpty(model.getCc()))
        setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC);
    if (!MiscUtils.isEmpty(model.getBcc()))
        setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC);

    try {

        if (!MiscUtils.isEmpty(subject))
            emailMessage.setSubject(subject);

        Multipart multipart = new MimeMultipart();

        if (body != null) {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            String bodyContentType;
            //        body = Utils.base64Encode(body);
            bodyContentType = "text/html; charset=UTF-8";

            messageBodyPart.setContent(body, bodyContentType);
            //Content-Transfer-Encoding : base64
            //        messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
            multipart.addBodyPart(messageBodyPart);
        }
        // Part two is attachment
        if (attachments != null && !attachments.isEmpty()) {
            try {
                for (EmailAttachment a : attachments) {
                    MimeBodyPart attachBodyPart = new MimeBodyPart();
                    // don't base 64 encode
                    DataSource source = new StreamDataSource(
                            new DefaultStreamFactory(a.getInputStream(), false), a.getName(),
                            a.getContentType());
                    attachBodyPart.setDataHandler(new DataHandler(source));
                    attachBodyPart.setFileName(a.getName());
                    attachBodyPart.setHeader("Content-Type", a.getContentType());
                    attachBodyPart.addHeader("Content-Transfer-Encoding", "base64");

                    // add the attachment to the message
                    multipart.addBodyPart(attachBodyPart);

                }
            }
            // close all the input streams
            finally {
                for (EmailAttachment a : attachments)
                    MiscUtils.closeStream(a.getInputStream());
            }
        }

        // set the content
        emailMessage.setContent(multipart);
        emailMessage.saveChanges();

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email message: " + emailMessage);

        Transport.send(emailMessage);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Sending email complete.");

    } catch (Exception e) {
        throw new EmailException(e);
    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

private void addFormMultipart(HttpRequestInterface<?> request, MimeMultipart formMp, String name, String value)
        throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();

    if (value.startsWith("file:")) {
        String fileName = value.substring(5);
        File file = new File(fileName);
        part.setDisposition("form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"");
        if (file.exists()) {
            part.setDataHandler(new DataHandler(new FileDataSource(file)));
        } else {//from   w  w  w.j a va 2s .com
            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getName().equals(fileName)) {
                    part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));
                    break;
                }
            }
        }

        part.setHeader("Content-Type", ContentTypeHandler.getContentTypeFromFilename(file.getName()));
        part.setHeader("Content-Transfer-Encoding", "binary");
    } else {
        part.setDisposition("form-data; name=\"" + name + "\"");
        part.setText(value, System.getProperty("soapui.request.encoding", request.getEncoding()));
    }

    if (part != null) {
        formMp.addBodyPart(part);
    }
}

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

/**Writes a passed payload data to the passed message object. Could be called from either the MDN
 * processing or the message processing//from  www  .ja  v a  2  s  .  co m
 */
public void writePayloadsToMessage(byte[] data, AS2Message message, Properties header) throws Exception {
    ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
    MimeMessage testMessage = new MimeMessage(Session.getInstance(System.getProperties()),
            new ByteArrayInputStream(data));
    //multiple attachments?
    if (testMessage.isMimeType("multipart/*")) {
        this.writePayloadsToMessage(testMessage, message, header);
        return;
    }
    InputStream payloadIn = null;
    AS2Info info = message.getAS2Info();
    if (info instanceof AS2MessageInfo && info.getSignType() == AS2Message.SIGNATURE_NONE
            && ((AS2MessageInfo) info).getCompressionType() == AS2Message.COMPRESSION_NONE) {
        payloadIn = new ByteArrayInputStream(data);
    } else if (testMessage.getSize() > 0) {
        payloadIn = testMessage.getInputStream();
    } else {
        payloadIn = new ByteArrayInputStream(data);
    }
    this.copyStreams(payloadIn, payloadOut);
    payloadOut.flush();
    payloadOut.close();
    byte[] payloadData = payloadOut.toByteArray();
    AS2Payload as2Payload = new AS2Payload();
    as2Payload.setData(payloadData);
    String contentIdHeader = header.getProperty("content-id");
    if (contentIdHeader != null) {
        as2Payload.setContentId(contentIdHeader);
    }
    String contentTypeHeader = header.getProperty("content-type");
    if (contentTypeHeader != null) {
        as2Payload.setContentType(contentTypeHeader);
    }
    try {
        as2Payload.setOriginalFilename(testMessage.getFileName());
    } catch (MessagingException e) {
        if (this.logger != null) {
            this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                    new Object[] { info.getMessageId(), e.getMessage(), }), info);
        }
    }
    if (as2Payload.getOriginalFilename() == null) {
        String filenameHeader = header.getProperty("content-disposition");
        if (filenameHeader != null) {
            //test part for convinience: extract file name
            MimeBodyPart filenamePart = new MimeBodyPart();
            filenamePart.setHeader("content-disposition", filenameHeader);
            try {
                as2Payload.setOriginalFilename(filenamePart.getFileName());
            } catch (MessagingException e) {
                if (this.logger != null) {
                    this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                            new Object[] { info.getMessageId(), e.getMessage(), }), info);
                }
            }
        }
    }
    message.addPayload(as2Payload);
}

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   w  w w .java2s .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);
}

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

/**Writes a passed payload part to the passed message object. 
 */// w  w  w  . jav  a2  s. c om
public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception {
    List<Part> attachmentList = new ArrayList<Part>();
    AS2Info info = message.getAS2Info();
    if (!info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (payloadPart.isMimeType("multipart/*")) {
            //check if it is a CEM
            if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) {
                messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM);
                if (this.logger != null) {
                    this.logger.log(Level.FINE, this.rb.getResourceString("found.cem",
                            new Object[] { messageInfo.getMessageId(), message }), info);
                }
            }
            ByteArrayOutputStream mem = new ByteArrayOutputStream();
            payloadPart.writeTo(mem);
            mem.flush();
            mem.close();
            MimeMultipart multipart = new MimeMultipart(
                    new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType()));
            //add all attachments to the message
            for (int i = 0; i < multipart.getCount(); i++) {
                //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature
                if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) {
                    attachmentList.add(multipart.getBodyPart(i));
                }
            }
        } else {
            attachmentList.add(payloadPart);
        }
    } else {
        //its a MDN, write whole part
        attachmentList.add(payloadPart);
    }
    //write the parts
    for (Part attachmentPart : attachmentList) {
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        InputStream payloadIn = attachmentPart.getInputStream();
        this.copyStreams(payloadIn, payloadOut);
        payloadOut.flush();
        payloadOut.close();
        byte[] data = payloadOut.toByteArray();
        AS2Payload as2Payload = new AS2Payload();
        as2Payload.setData(data);
        String[] contentIdHeader = attachmentPart.getHeader("content-id");
        if (contentIdHeader != null && contentIdHeader.length > 0) {
            as2Payload.setContentId(contentIdHeader[0]);
        }
        String[] contentTypeHeader = attachmentPart.getHeader("content-type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            as2Payload.setContentType(contentTypeHeader[0]);
        }
        try {
            as2Payload.setOriginalFilename(payloadPart.getFileName());
        } catch (MessagingException e) {
            if (this.logger != null) {
                this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                        new Object[] { info.getMessageId(), e.getMessage(), }), info);
            }
        }
        if (as2Payload.getOriginalFilename() == null) {
            String filenameheader = header.getProperty("content-disposition");
            if (filenameheader != null) {
                //test part for convinience: extract file name
                MimeBodyPart filenamePart = new MimeBodyPart();
                filenamePart.setHeader("content-disposition", filenameheader);
                try {
                    as2Payload.setOriginalFilename(filenamePart.getFileName());
                } catch (MessagingException e) {
                    if (this.logger != null) {
                        this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                                new Object[] { info.getMessageId(), e.getMessage(), }), info);
                    }
                }
            }
        }
        message.addPayload(as2Payload);
    }
}

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:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();/*from www .  j  a  v a 2s  .c om*/
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

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  om*/
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");
    }
}