Example usage for javax.mail Message getAllRecipients

List of usage examples for javax.mail Message getAllRecipients

Introduction

In this page you can find the example usage for javax.mail Message getAllRecipients.

Prototype

public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

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

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

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

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

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

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

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

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

    msg.setContent(multipart);

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

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

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;/*from ww w .ja v a2 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:com.clustercontrol.jobmanagement.util.SendApprovalMail.java

/**
 * ????// www .j a  va2s. com
 * @param toAddressStr
 *            ?To
 * @param ccAddressStr
 *            ?Cc
 * @param subject
 *            ??
 * @param content
 *            
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */

public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content)
        throws MessagingException, UnsupportedEncodingException {

    if (toAddressStr == null || toAddressStr.length <= 0) {
        // ??
        return;
    }
    /*
     *  https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html
     */
    Properties _properties = new Properties();
    _properties.setProperty("mail.debug",
            Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false)));
    _properties.setProperty("mail.store.protocol",
            HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3"));
    String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp");
    _properties.setProperty("mail.transport.protocol", protocol);
    _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault());
    _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault());

    setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".connectiontimeout",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.login.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.plain.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.authorizationid",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.class",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socketFactory.fallback",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.port",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".starttls.required",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH);

    setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING);

    /**
     * ?DB??
     */
    String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody");
    String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password");
    String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com");
    String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name",
            "Hinemos Admin");
    _fromPersonalName = convertNativeToAscii(_fromPersonalName);

    String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address",
            "admin@hinemos.com");
    String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name",
            "Hinemos Admin");
    _replyToPersonalName = convertNativeToAscii(_replyToPersonalName);

    String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address",
            "admin@hinemos.com");

    int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1))
            .intValue();
    int _transportTriesInterval = HinemosPropertyUtil
            .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue();

    String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address",
            _charsetAddressDefault);
    String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject",
            _charsetSubjectDefault);
    String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content",
            _charsetContentDefault);

    m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName
            + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress
            + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = "
            + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":"
            + _charsetSubject + ":" + _charsetContent + "]");

    // JavaMail Session
    Session session = Session.getInstance(_properties);

    Message mineMsg = new MimeMessage(session);

    // ?????
    if (_fromAddress != null && _fromPersonalName != null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress));
    } else if (_fromAddress != null && _fromPersonalName == null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress));
    }

    // REPLY-TO
    if (_replyToAddress != null && _replyToPersonalName != null) {
        InternetAddress reply[] = {
                new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    } else if (_replyToAddress != null && _replyToPersonalName == null) {
        InternetAddress reply[] = { new InternetAddress(_replyToAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    }

    // ERRORS-TO
    if (_errorsToAddress != null) {
        mineMsg.setHeader("Errors-To", _errorsToAddress);
    }

    // ?
    // TO
    InternetAddress[] toAddress = this.getAddress(toAddressStr);
    if (toAddress != null && toAddress.length > 0) {
        mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
    } else {
        return; // TO?
    }

    // CC
    if (ccAddressStr != null) {
        InternetAddress[] ccAddress = this.getAddress(ccAddressStr);
        if (ccAddress != null && ccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress);
        }
    }
    String message = "TO=" + Arrays.asList(toAddressStr);

    if (ccAddressStr != null) {
        message += ", CC=" + Arrays.asList(ccAddressStr);
    }
    m_log.debug(message);

    // ???
    mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B"));

    // ?
    mineMsg.setContent(content, "text/plain; charset=" + _charsetContent);

    // ?
    mineMsg.setSentDate(HinemosTime.getDateInstance());

    // ???true??????
    for (int i = 0; i < _transportTries; i++) {
        Transport transport = null;
        try {
            // ?
            transport = session.getTransport();
            boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false);
            if (flag) {
                transport.connect(_loginUser, _loginPassword);
            } else {
                transport.connect();
            }
            transport.sendMessage(mineMsg, mineMsg.getAllRecipients());
            break;
        } catch (AuthenticationFailedException e) {
            throw e;
        } catch (SMTPAddressFailedException e) {
            throw e;
        } catch (MessagingException me) {
            //_transportTries?sleep??? 
            if (i < (_transportTries - 1)) {
                m_log.info("sendMail() : retry sendmail. " + me.getMessage());
                try {
                    Thread.sleep(_transportTriesInterval);
                } catch (InterruptedException e) {
                }
                //_transportTries??INTERNAL????Exceptionthrow 
            } else {
                throw me;
            }
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    }
}

From source file:com.clustercontrol.notify.util.SendMail.java

public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject,
        String content) throws MessagingException, UnsupportedEncodingException {

    if (toAddressStr == null || toAddressStr.length <= 0) {
        // ??//from   ww  w.  jav a 2 s  .  c  o  m
        return;
    }

    /*
     *  https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html
     */
    Properties _properties = new Properties();
    _properties.setProperty("mail.debug",
            Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false)));
    _properties.setProperty("mail.store.protocol",
            HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3"));
    String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp");
    _properties.setProperty("mail.transport.protocol", protocol);
    _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault());
    _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault());

    setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".connectiontimeout",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.login.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.plain.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.authorizationid",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.class",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socketFactory.fallback",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.port",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".starttls.required",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH);

    setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING);

    /**
     * ?DB??
     */
    String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody");
    String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password");
    String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com");
    String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name",
            "Hinemos Admin");
    _fromPersonalName = convertNativeToAscii(_fromPersonalName);

    String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address",
            "admin@hinemos.com");
    String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name",
            "Hinemos Admin");
    _replyToPersonalName = convertNativeToAscii(_replyToPersonalName);

    String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address",
            "admin@hinemos.com");

    int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1))
            .intValue();
    int _transportTriesInterval = HinemosPropertyUtil
            .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue();

    String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address",
            _charsetAddressDefault);
    String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject",
            _charsetSubjectDefault);
    String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content",
            _charsetContentDefault);

    m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName
            + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress
            + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = "
            + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":"
            + _charsetSubject + ":" + _charsetContent + "]");

    // JavaMail Session
    Session session = Session.getInstance(_properties);

    Message mineMsg = new MimeMessage(session);

    // ?????
    if (_fromAddress != null && _fromPersonalName != null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress));
    } else if (_fromAddress != null && _fromPersonalName == null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress));
    }
    // REPLY-TO
    if (_replyToAddress != null && _replyToPersonalName != null) {
        InternetAddress reply[] = {
                new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    } else if (_replyToAddress != null && _replyToPersonalName == null) {
        InternetAddress reply[] = { new InternetAddress(_replyToAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    }

    // ERRORS-TO
    if (_errorsToAddress != null) {
        mineMsg.setHeader("Errors-To", _errorsToAddress);
    }

    // ?
    // TO
    InternetAddress[] toAddress = this.getAddress(toAddressStr);
    if (toAddress != null && toAddress.length > 0) {
        mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
    } else {
        return; // TO?
    }
    // CC
    if (ccAddressStr != null) {
        InternetAddress[] ccAddress = this.getAddress(ccAddressStr);
        if (ccAddress != null && ccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress);
        }
    }
    // BCC
    if (bccAddressStr != null) {
        InternetAddress[] bccAddress = this.getAddress(bccAddressStr);
        if (bccAddress != null && bccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress);
        }
    }
    String message = "TO=" + Arrays.asList(toAddressStr);

    if (ccAddressStr != null) {
        message += ", CC=" + Arrays.asList(ccAddressStr);
    }
    if (bccAddressStr != null) {
        message += ", BCC=" + Arrays.asList(bccAddressStr);
    }
    m_log.debug(message);

    // ???
    mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B"));

    // ?
    mineMsg.setContent(content, "text/plain; charset=" + _charsetContent);

    // ?
    mineMsg.setSentDate(HinemosTime.getDateInstance());

    // ???true??????
    for (int i = 0; i < _transportTries; i++) {
        Transport transport = null;
        try {
            // ?
            transport = session.getTransport();
            boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false);
            if (flag) {
                transport.connect(_loginUser, _loginPassword);
            } else {
                transport.connect();
            }
            transport.sendMessage(mineMsg, mineMsg.getAllRecipients());
            break;
        } catch (AuthenticationFailedException e) {
            throw e;
        } catch (SMTPAddressFailedException e) {
            throw e;
        } catch (MessagingException me) {
            //_transportTries?sleep??? 
            if (i < (_transportTries - 1)) {
                m_log.info("sendMail() : retry sendmail. " + me.getMessage());
                try {
                    Thread.sleep(_transportTriesInterval);
                } catch (InterruptedException e) {
                }
                //_transportTries??INTERNAL????Exceptionthrow 
            } else {
                throw me;
            }
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    }
}

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
 * /*from  w  w  w.  ja  v a 2s.c  om*/
 * @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 {/*from w w w  .  java  2 s. com*/
            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: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  2  s .  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.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;//  w  w  w. j  a v a  2  s  . 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:net.spfbl.core.Core.java

public static synchronized boolean sendMessage(Message message, int timeout) throws Exception {
    if (message == null) {
        return false;
    } else if (isDirectSMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: false.");
        Server.logSendMTP("start TLS: true.");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", "false");
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        InternetAddress[] recipients = (InternetAddress[]) message.getAllRecipients();
        Exception lastException = null;
        for (InternetAddress recipient : recipients) {
            String domain = Domain.normalizeHostname(recipient.getAddress(), false);
            for (String mx : Reverse.getMXSet(domain)) {
                mx = mx.substring(1);/*from w w w.  ja v  a  2  s  .c  o m*/
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", mx);
                props.put("mail.smtp.ssl.trust", mx);
                InternetAddress[] recipientAlone = new InternetAddress[1];
                recipientAlone[0] = (InternetAddress) recipient;
                Session session = Session.getDefaultInstance(props);
                SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
                try {
                    transport.setLocalHost(HOSTNAME);
                    Server.logSendMTP("connecting to " + mx + ":25.");
                    transport.connect(mx, 25, null, null);
                    Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                    transport.sendMessage(message, recipientAlone);
                    Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipient + ".");
                    Server.logSendMTP("last response: " + transport.getLastServerResponse());
                    lastException = null;
                    break;
                } catch (MailConnectException ex) {
                    Server.logSendMTP("connection failed.");
                    lastException = ex;
                } catch (SendFailedException ex) {
                    Server.logSendMTP("send failed.");
                    throw ex;
                } catch (MessagingException ex) {
                    if (ex.getMessage().contains(" TLS ")) {
                        Server.logSendMTP("cannot establish TLS connection.");
                        if (transport.isConnected()) {
                            transport.close();
                            Server.logSendMTP("connection closed.");
                        }
                        Server.logInfo("sending e-mail message without TLS.");
                        props.put("mail.smtp.starttls.enable", "false");
                        session = Session.getDefaultInstance(props);
                        transport = (SMTPTransport) session.getTransport("smtp");
                        try {
                            transport.setLocalHost(HOSTNAME);
                            Server.logSendMTP("connecting to " + mx + ":25.");
                            transport.connect(mx, 25, null, null);
                            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + ".");
                            transport.sendMessage(message, recipientAlone);
                            Server.logSendMTP(
                                    "message '" + message.getSubject() + "' sent to " + recipient + ".");
                            Server.logSendMTP("last response: " + transport.getLastServerResponse());
                            lastException = null;
                            break;
                        } catch (SendFailedException ex2) {
                            Server.logSendMTP("send failed.");
                            throw ex2;
                        } catch (Exception ex2) {
                            lastException = ex2;
                        }
                    } else {
                        lastException = ex;
                    }
                } catch (Exception ex) {
                    Server.logError(ex);
                    lastException = ex;
                } finally {
                    if (transport.isConnected()) {
                        transport.close();
                        Server.logSendMTP("connection closed.");
                    }
                }
            }
        }
        if (lastException == null) {
            return true;
        } else {
            throw lastException;
        }
    } else if (hasRelaySMTP()) {
        Server.logInfo("sending e-mail message.");
        Server.logSendMTP("authenticate: " + Boolean.toString(SMTP_IS_AUTH) + ".");
        Server.logSendMTP("start TLS: " + Boolean.toString(SMTP_STARTTLS) + ".");
        Properties props = System.getProperties();
        props.put("mail.smtp.auth", Boolean.toString(SMTP_IS_AUTH));
        props.put("mail.smtp.starttls.enable", Boolean.toString(SMTP_STARTTLS));
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", Short.toString(SMTP_PORT));
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        props.put("mail.smtp.ssl.trust", SMTP_HOST);
        Address[] recipients = message.getAllRecipients();
        TreeSet<String> recipientSet = new TreeSet<String>();
        for (Address recipient : recipients) {
            recipientSet.add(recipient.toString());
        }
        Session session = Session.getDefaultInstance(props);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        try {
            if (HOSTNAME != null) {
                transport.setLocalHost(HOSTNAME);
            }
            Server.logSendMTP("connecting to " + SMTP_HOST + ":" + SMTP_PORT + ".");
            transport.connect(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD);
            Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipientSet + ".");
            transport.sendMessage(message, recipients);
            Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipientSet + ".");
            return true;
        } catch (SendFailedException ex) {
            Server.logSendMTP("send failed.");
            throw ex;
        } catch (AuthenticationFailedException ex) {
            Server.logSendMTP("authentication failed.");
            return false;
        } catch (MailConnectException ex) {
            Server.logSendMTP("connection failed.");
            return false;
        } catch (MessagingException ex) {
            Server.logSendMTP("messaging failed.");
            return false;
        } catch (Exception ex) {
            Server.logError(ex);
            return false;
        } finally {
            if (transport.isConnected()) {
                transport.close();
                Server.logSendMTP("connection closed.");
            }
        }
    } else {
        return false;
    }
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected void putOnTransport(Message msg) throws SenderException {
    // connect to the transport 
    Transport transport = null;//from   w ww  .j  a v a  2 s.  c o m
    try {
        CredentialFactory cf = new CredentialFactory(getSmtpAuthAlias(), getSmtpUserid(), getSmtpPassword());
        transport = session.getTransport("smtp");
        transport.connect(getSmtpHost(), cf.getUsername(), cf.getPassword());
        if (log.isDebugEnabled()) {
            log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName()
                    + "]");
        }
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    } catch (Exception e) {
        throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost ["
                + getSmtpHost() + "]", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e1) {
                log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
            }
        }
    }
}