Example usage for javax.mail Transport connect

List of usage examples for javax.mail Transport connect

Introduction

In this page you can find the example usage for javax.mail Transport connect.

Prototype

public synchronized void connect(String host, int port, String user, String password)
        throws MessagingException 

Source Link

Document

Similar to connect(host, user, password) except a specific port can be specified.

Usage

From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java

/**
 * This method performs the treatment of the technical send:
 * <ul>//w w  w . j  a  v a2  s.co m
 * <li>connection to the SMTP server</li>
 * <li>sending</li>
 * <li>closing the connection</li>
 * </ul>
 * @param mail the original data from which the given {@link MimeMessage} has been initialized.
 * @param smtpConfiguration the SMTP configuration.
 * @param session the current mail session.
 * @param messageToSend the technical message to send.
 * @param batchedToAddresses the receivers of the message.
 * @throws MessagingException
 */
private void performSend(final MailToSend mail, final SmtpConfiguration smtpConfiguration, Session session,
        MimeMessage messageToSend, List<InternetAddress[]> batchedToAddresses) throws MessagingException {

    // Creating a Transport connection (TCP)
    final Transport transport;
    if (smtpConfiguration.isSecure()) {
        transport = session.getTransport(SmtpConfiguration.SECURE_TRANSPORT);
    } else {
        transport = session.getTransport(SmtpConfiguration.SIMPLE_TRANSPORT);
    }

    // Adding send reporting listener
    transport.addTransportListener(new SmtpMailSendReportListener(mail));

    try {
        if (smtpConfiguration.isAuthenticate()) {
            transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(),
                    smtpConfiguration.getUsername(), smtpConfiguration.getPassword());
        } else {
            transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), null, null);
        }

        for (InternetAddress[] toAddressBatch : batchedToAddresses) {
            messageToSend.setRecipients(mail.getTo().getRecipientType().getTechnicalType(), toAddressBatch);
            transport.sendMessage(messageToSend, toAddressBatch);
        }

    } finally {
        try {
            transport.close();
        } catch (Exception e) {
            SilverTrace.error("mail", "SmtpMailSender.send()", "root.EX_IGNORED", "ClosingTransport", e);
        }
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;/*w  w w  .  j av 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:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments
 * //  w  ww  . ja v  a2 s  .  co m
 * @param mailOptions
 * @return
 */

public boolean sendFiles(Map<String, Object> mailOptions) {

    logger.debug("IN");
    try {
        final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory";

        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        File tempFolder = new File(tempFolderPath);

        if (!tempFolder.exists() || !tempFolder.isDirectory()) {
            logger.error("Temp Folder " + tempFolderPath
                    + " does not exist or is not a directory: stop sending mail");
            return false;
        }

        String smtphost = null;
        String pass = null;
        String smtpssl = null;
        String trustedStorePath = null;
        String user = null;
        String from = null;
        int smtpPort = 25;

        try {

            smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
            String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
            smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
            logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl);
            //Custom Trusted Store Certificate Options
            trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file");

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

            from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
            if ((from == null) || from.trim().equals(""))
                from = "spagobi.scheduler@eng.it";
            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");
            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");
        } catch (Exception e) {
            logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.",
                    e);
            throw new Exception(
                    "Some E-mail configuration not set in table sbi_config: check you have all settings.");
        }

        String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null;
        Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP)
                : null;
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null;
        String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS)
                : null;

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

        // 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(smtpPort));
                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;

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null;
        Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null
                && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("")
                        ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT)
                        : null;
        //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null;
        String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME)
                : "Zipped Documents";
        String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE)
                : null;
        String fileExtension = mailOptions.get(FILE_EXTENSION) != null
                ? (String) mailOptions.get(FILE_EXTENSION)
                : null;

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

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt);

        // attach the file to the message

        boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null
                ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT)
                : false;
        zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME)
                : "Zipped Documents";

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        mp.addBodyPart(mbp1);

        if (isZipDocument) {
            logger.debug("Make zip");
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder);
            mp.addBodyPart(mbp2);
        } else {
            logger.debug("Attach single files");
            SchedulerDataSource sds = null;
            MimeBodyPart bodyPart = null;
            try {
                String[] entries = tempFolder.list();

                for (int i = 0; i < entries.length; i++) {
                    logger.debug("Attach file " + entries[i]);
                    File f = new File(tempFolder + File.separator + entries[i]);

                    byte[] content = getBytesFromFile(f);

                    bodyPart = new MimeBodyPart();

                    sds = new SchedulerDataSource(content, contentType, entries[i]);
                    //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension);

                    bodyPart.setDataHandler(new DataHandler(sds));
                    bodyPart.setFileName(sds.getName());

                    mp.addBodyPart(bodyPart);
                }

            } catch (Exception e) {
                logger.error("Error while attaching files", e);
            }

        }

        // add the Multipart to the message
        msg.setContent(mp);
        logger.debug("Preparing to send mail");
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            logger.debug("Smtps mode active user " + user);
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smtpPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            logger.debug("Smtp mode");
            //Use normal SMTP
            Transport.send(msg);
        }

        //         logger.debug("delete tempFolder path "+tempFolder.getPath());
        //         boolean deleted = tempFolder.delete();
        //         logger.debug("Temp folder deleted "+deleted);

    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {/*  w  w w.  j a v a2 s.  c o m*/
            protocol = "smtps";
            // required to get rid of a SSL exception :
            //  nested exception is:
            //  javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (!Const.isEmpty(port))
        data.props.put("mail." + protocol + ".port", port);
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        data.props.put("mail.debug", "true");

    if (meta.isUsingAuthentication())
        data.props.put("mail." + protocol + ".auth", "true");

    Session session = Session.getInstance(data.props);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low"))
            priority_int = "3";
        if (meta.getPriority().equals("normal"))
            priority_int = "2";

        msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        //seems to be needed for MS Outlook.
        //where it returns a string of high /normal /low.
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName))
            email_address = senderName + '<' + email_address + '>';
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to 
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++)
            address[i] = new InternetAddress(reply_Address_List[i]);

        // To add the real reply-to 
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String destinations[] = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++)
        address[i] = new InternetAddress(destinations[i]);

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String destinationsCc[] = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++)
            addressCc[i] = new InternetAddress(destinationsCc[i]);

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String destinationsBCc[] = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++)
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null)
        msg.setSubject(mailsubject);

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null)
        messageText.append(comment).append(Const.CR).append(Const.CR);

    if (meta.getIncludeDate())
        messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson)
                .append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding()))
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        else
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
    } else
        part1.setText(messageText.toString());

    data.parts.addBodyPart(part1);

    // attached files
    if (meta.isDynamicFilename())
        setAttachedFilesList(r, log);
    else
        setAttachedFilesList(null, log);

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (!Const.isEmpty(port)) {
                transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")),
                        Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null)
            transport.close();
    }

}

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

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//from  w  w w  . j a  v  a  2s .  co m
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

    if (isDebug()) {
        data.props.put("mail.debug", "true");
    }

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

    Session session = Session.getInstance(data.props);
    session.setDebug(isDebug());

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low")) {
            priority_int = "3";
        }
        if (meta.getPriority().equals("normal")) {
            priority_int = "2";
        }

        msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        // seems to be needed for MS Outlook.
        // where it returns a string of high /normal /low.
        msg.setHeader("Sensitivity", meta.getSensitivity());
        // Possible values are normal, personal, private, company-confidential
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++) {
            address[i] = new InternetAddress(reply_Address_List[i]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++) {
        address[i] = new InternetAddress(destinations[i]);
    }

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++) {
            addressCc[i] = new InternetAddress(destinationsCc[i]);
        }

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++) {
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null) {
        messageText.append(comment).append(Const.CR).append(Const.CR);
    }

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding())) {
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        } else {
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
        }
    } else {
        part1.setText(messageText.toString());
    }

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

    if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) {
        // If we need to embedd images...
        // We need to create a "multipart/related" message.
        // otherwise image will appear as attached file
        data.parts.setSubType("related");
    }

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);//from  w ww  .j  a  v  a 2 s.  c o  m
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;//from ww  w.  jav  a 2s  .c  o  m

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(),
                "Unable to send the mail because the mail-server (SMTP host) is not specified");
        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        protocol = "smtps";
    }

    props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", StringUtil.environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
        authenticator = new Authenticator()
        {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(
                        StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), 
                        StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))
                    );
        }
        };
        */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        String email_address = StringUtil.environmentSubstitute(replyAddress);
        if (!Const.isEmpty(email_address)) {
            msg.setFrom(new InternetAddress(email_address));
        } else {
            throw new MessagingException("reply e-mail address is not filled in");
        }

        // Split the mail-address: space separated
        String destinations[] = StringUtil.environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);

        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = StringUtil.environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = StringUtil.environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }

        msg.setSubject(StringUtil.environmentSubstitute(subject));
        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }

        if (!onlySendComment) {
            messageText.append("Job:").append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append("Name       : ").append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append("Directory  : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append("JobEntry   : ").append(getName()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            Value date = new Value("date", new Date());
            messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append("Previous result:").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append("Job entry nr         : ").append(result.getEntryNr()).append(Const.CR);
            messageText.append("Errors               : ").append(result.getNrErrors()).append(Const.CR);
            messageText.append("Lines read           : ").append(result.getNrLinesRead()).append(Const.CR);
            messageText.append("Lines written        : ").append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append("Lines input          : ").append(result.getNrLinesInput()).append(Const.CR);
            messageText.append("Lines output         : ").append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append("Lines updated        : ").append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append("Script exit status   : ").append(result.getExitStatus()).append(Const.CR);
            messageText.append("Result               : ").append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson))
                || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) {
            messageText.append("Contact information :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson))
                    .append(Const.CR);
            messageText.append("Telephone number  : ").append(StringUtil.environmentSubstitute(contactPhone))
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append("Path to this job entry:").append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part
        part1.setText(messageText.toString());
        parts.addBodyPart(part1);
        if (includingFiles && result != null) {
            List resultFiles = result.getResultFilesList();
            if (resultFiles != null && resultFiles.size() > 0) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                        ResultFile resultFile = (ResultFile) iter.next();
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                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(fds.getName());
                                // add the part with the file in the BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + StringUtil.environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (Iterator iter = resultFiles.iterator(); iter.hasNext();) {
                            ResultFile resultFile = (ResultFile) iter.next();

                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getURI());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        file.getContent().getInputStream());
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
                            StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    //System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

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 w  w  w.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:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/*from  ww  w  .  jav a2s. c  o  m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                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());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr) {
    File masterZipfile = null;//  w  w  w  .  ja  v  a 2  s . com

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port)) {
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    }

    if (log.isDebug()) {
        props.put("mail.debug", "true");
    }

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(log.isDebug());

    try {
        // create a message
        Message msg = new MimeMessage(session);

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
            msg.setHeader("Sensitivity", sensitivity);
            // Possible values are normal, personal, private, company-confidential

        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name)) {
                sender_address = sender_name + '<' + sender_address + '>';
            }
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++) {
                address[i] = new InternetAddress(reply_Address_List[i]);
            }
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String[] destinations = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++) {
            address[i] = new InternetAddress(destinations[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, address);

        String realCC = environmentSubstitute(getDestinationCc());
        if (!Const.isEmpty(realCC)) {
            // Split the mail-address Cc: space separated
            String[] destinationsCc = realCC.split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++) {
                addressCc[i] = new InternetAddress(destinationsCc[i]);
            }

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        String realBCc = environmentSubstitute(getDestinationBCc());
        if (!Const.isEmpty(realBCc)) {
            // Split the mail-address BCc: space separated
            String[] destinationsBCc = realBCc.split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++) {
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);
            }

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();
        String endRow = isUseHTML() ? "<br>" : Const.CR;
        String realComment = environmentSubstitute(comment);
        if (!Const.isEmpty(realComment)) {
            messageText.append(realComment).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow);
            messageText.append("-----").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + "   : ")
                    .append(getName()).append(endRow);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow);
        }
        if (!onlySendComment && result != null) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":")
                    .append(endRow);
            messageText.append("-----------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + "       : ")
                    .append(result.getNrLinesRejected()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(endRow);
            messageText.append(endRow);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :")
                    .append(endRow);
            messageText.append("---------------------").append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(endRow);
            messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(endRow);
            messageText.append(endRow);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(endRow);
                messageText.append("------------------------").append(endRow);

                addBacktracking(jobTracker, messageText);
                if (isUseHTML()) {
                    messageText.replace(0, messageText.length(),
                            messageText.toString().replace(Const.CR, endRow));
                }
            }
        }

        MimeMultipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // Attached files counter
        int nrattachedFiles = 0;

        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }
        } else {
            part1.setText(messageText.toString());
        }

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                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();
                                parts.addBodyPart(files);
                                nrattachedFiles++;
                                logBasic("Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType()) {
                                    found = true;
                                }
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                try {
                                    int c;
                                    while ((c = inputStream.read()) >= 0) {
                                        zipOutputStream.write(c);
                                    }
                                } finally {
                                    inputStream.close();
                                }
                                zipOutputStream.closeEntry();
                                nrattachedFiles++;
                                logBasic("Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        logError("Error zipping attachement files into file [" + masterZipfile.getPath()
                                + "] : " + e.toString());
                        logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                logError("Unable to close attachement zip file archive : " + e.toString());
                                logError(Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in the data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }

        int nrEmbeddedImages = 0;
        if (embeddedimages != null && embeddedimages.length > 0) {
            FileObject imageFile = null;
            for (int i = 0; i < embeddedimages.length; i++) {
                String realImageFile = environmentSubstitute(embeddedimages[i]);
                String realcontenID = environmentSubstitute(contentids[i]);
                if (messageText.indexOf("cid:" + realcontenID) < 0) {
                    if (log.isDebug()) {
                        log.logDebug("Image [" + realImageFile + "] is not used in message body!");
                    }
                } else {
                    try {
                        boolean found = false;
                        imageFile = KettleVFS.getFileObject(realImageFile, this);
                        if (imageFile.exists() && imageFile.getType() == FileType.FILE) {
                            found = true;
                        } else {
                            log.logError("We can not find [" + realImageFile + "] or it is not a file");
                        }
                        if (found) {
                            // Create part for the image
                            MimeBodyPart messageBodyPart = new MimeBodyPart();
                            // Load the image
                            URLDataSource fds = new URLDataSource(imageFile.getURL());
                            messageBodyPart.setDataHandler(new DataHandler(fds));
                            // Setting the header
                            messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">");
                            // Add part to multi-part
                            parts.addBodyPart(messageBodyPart);
                            nrEmbeddedImages++;
                            log.logBasic("Image '" + fds.getName() + "' was embedded in message.");
                        }
                    } catch (Exception e) {
                        log.logError(
                                "Error embedding image [" + realImageFile + "] in message : " + e.toString());
                        log.logError(Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (imageFile != null) {
                            try {
                                imageFile.close();
                            } catch (Exception e) { /* Ignore */
                            }
                        }
                    }
                }
            }
        }

        if (nrEmbeddedImages > 0 && nrattachedFiles == 0) {
            // If we need to embedd images...
            // We need to create a "multipart/related" message.
            // otherwise image will appear as attached file
            parts.setSubType("related");
        }
        // put all parts together
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            String authPass = getPassword(authenticationPassword);

            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")), authPass);
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    } catch (IOException e) {
        logError("Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        logError("Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    logError("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        logError("         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    logError("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        logError("         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        logError("         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}