Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

In this page you can find the example usage for javax.mail MessagingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarLoginHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from  www .j a v  a 2s  . c o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAsteriskSchemaPooledObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "schemaObj");
        }
    }

    ICFAsteriskSchema dbSchema = null;
    try {
        CFSecurityAuthorization auth = schemaObj.getAuthorization();
        if (auth != null) {
            response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");
            return;
        }

        dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();
        ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        String passwordHash = systemUser.getRequiredPasswordHash();
        if ((passwordHash == null) || (passwordHash.length() <= 0) || passwordHash.equals("bootstrap")) {
            response.sendRedirect("CFAsteriskSMWarSetSystemPasswordHtml");
        }

        ICFSecurityClusterObj resolvedCluster;
        ICFSecuritySysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }
        resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }
        String clusterDomainName = resolvedCluster.getRequiredFullDomainName();
        String clusterDescription = resolvedCluster.getRequiredDescription();

        String loginId = (String) request.getParameter("LoginId");
        if ((loginId == null) || (loginId.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAsteriskSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecuritySecUserObj authenticatingUser = schemaObj.getSecUserTableObj()
                .readSecUserByULoginIdx(loginId, true);
        if (authenticatingUser == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAsteriskSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecuritySecDeviceObj defDev = authenticatingUser.getOptionalLookupDefDev(true);

        if (null != authenticatingUser.getOptionalPasswordResetUuid()) {

            sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Password Reset email has been resent.");
            out.println("<p style=\"text-align:center\">");
            out.println(
                    "Please use the links in the password reset email to set a new Password or to cancel the request before trying to log in again.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAsteriskSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String password = (String) request.getParameter("Password");
        if (password == null) {
            password = "";
        }

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes("UTF-8"));
        byte[] hash = msgDigest.digest();
        byte[] encodedHash = Base64.encodeBase64(hash);
        msgDigest.update(encodedHash);
        hash = msgDigest.digest();
        byte encodedDoubleHash[] = Base64.encodeBase64(hash);
        String hashedAndEncodedPassword = new String(encodedDoubleHash);

        if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAsteriskSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        if (null != authenticatingUser.getOptionalEMailConfirmationUuid()) {

            sendConfirmationEMail(defDev, request, authenticatingUser, resolvedCluster);

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("EMail address " + ((defDev != null) ? "security " : "")
                    + " of login id has not been confirmed.  The " + ((defDev != null) ? "encrypted " : "")
                    + "confirmation email has been resent.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAsteriskSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");

            return;
        }

        ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(resolvedCluster.getRequiredId(), "system");
        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(authenticatingUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        auth = new CFSecurityAuthorization();
        auth.setSecCluster(resolvedCluster);
        auth.setSecTenant(systemTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        schemaObj.commit();

        response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");
    } catch (MessagingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught MessagingException -- " + e.getMessage(), e);
    } catch (NamingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NamingException -- " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java

/**
 * ????/*from  w  w  w  .  java  2s  . 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.cubusmail.mail.MessageHandler.java

/**
 * @param session/*from w w w . j  a v  a  2 s  . c o  m*/
 * @param message
 */
private void init(Session session, MimeMessage message) {

    this.session = session;
    this.message = message;
    try {
        this.readBefore = this.message.isSet(Flag.SEEN);
        String contentType = message.getContentType();
        ContentType type = new ContentType(contentType);
        String charset = type.getParameter("charset");
        if (charset != null) {
            this.charset = charset;
        } else {
            // this.message.setHeader( name, value )
        }
    } catch (MessagingException e) {
        log.warn(e.getMessage());
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarLoginHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///from   w ww.j a  va 2s. c o m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAstSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAstSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAstSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "schemaObj");
        }
    }

    ICFAstSchema dbSchema = null;
    try {
        CFAstAuthorization auth = schemaObj.getAuthorization();
        if (auth != null) {
            response.sendRedirect("CFAstSMWarSecurityMainHtml");
            return;
        }

        dbSchema = CFAstSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();
        ICFAstSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        String passwordHash = systemUser.getRequiredPasswordHash();
        if ((passwordHash == null) || (passwordHash.length() <= 0) || passwordHash.equals("bootstrap")) {
            response.sendRedirect("CFAstSMWarSetSystemPasswordHtml");
        }

        ICFAstClusterObj resolvedCluster;
        ICFAstSysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }
        resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }
        String clusterDomainName = resolvedCluster.getRequiredFullDomainName();
        String clusterDescription = resolvedCluster.getRequiredDescription();

        String loginId = (String) request.getParameter("LoginId");
        if ((loginId == null) || (loginId.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAstSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAstSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFAstSecUserObj authenticatingUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx(loginId,
                true);
        if (authenticatingUser == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAstSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAstSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFAstSecDeviceObj defDev = authenticatingUser.getOptionalLookupDefDev(true);

        if (null != authenticatingUser.getOptionalPasswordResetUuid()) {

            sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Password Reset email has been resent.");
            out.println("<p style=\"text-align:center\">");
            out.println(
                    "Please use the links in the password reset email to set a new Password or to cancel the request before trying to log in again.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAstSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAstSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String password = (String) request.getParameter("Password");
        if (password == null) {
            password = "";
        }

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes("UTF-8"));
        byte[] hash = msgDigest.digest();
        byte[] encodedHash = Base64.encodeBase64(hash);
        msgDigest.update(encodedHash);
        hash = msgDigest.digest();
        byte encodedDoubleHash[] = Base64.encodeBase64(hash);
        String hashedAndEncodedPassword = new String(encodedDoubleHash);

        if (!hashedAndEncodedPassword.equals(authenticatingUser.getRequiredPasswordHash())) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id or password is invalid.  Permission denied.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAstSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAstSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        if (null != authenticatingUser.getOptionalEMailConfirmationUuid()) {

            sendConfirmationEMail(defDev, request, authenticatingUser, resolvedCluster);

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarLoginHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("EMail address " + ((defDev != null) ? "security " : "")
                    + " of login id has not been confirmed.  The " + ((defDev != null) ? "encrypted " : "")
                    + "confirmation email has been resent.");
            out.println("<p style=\"text-align:center\">");
            out.println("Please log in or create a new account.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Password:</th><td><input type=\"password\" name=\"Password\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"/CFAstSMWarCreateNewAccountHtml\">Create new account</A></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAstSMWarRequestResetPasswordHtml\">Request an Password Reset</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");

            return;
        }

        ICFAstTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(resolvedCluster.getRequiredId(), "system");
        ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setRequiredContainerSecUser(authenticatingUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        auth = new CFAstAuthorization();
        auth.setSecCluster(resolvedCluster);
        auth.setSecTenant(systemTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        schemaObj.commit();

        response.sendRedirect("CFAstSMWarSecurityMainHtml");
    } catch (MessagingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught MessagingException -- " + e.getMessage(), e);
    } catch (NamingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NamingException -- " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAstSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:com.eurelis.opencms.workflows.functions.EmailNotificationFunction.java

/**
 * Execute this function//w ww  .j  ava  2 s.  co  m
 * 
 * @param transientVars
 *            Variables that will not be persisted. These include inputs given in the {@link Workflow#initialize}
 *            and {@link Workflow#doAction} method calls. There are a number of special variable names:
 *            <ul>
 *            <li><code>entry</code>: (object type: {@link com.opensymphony.workflow.spi.WorkflowEntry}) The
 *            workflow instance
 *            <li><code>context</code>: (object type: {@link com.opensymphony.workflow.WorkflowContext}). The
 *            workflow context.
 *            <li><code>actionId</code>: The Integer ID of the current action that was take (if applicable).
 *            <li><code>currentSteps</code>: A Collection of the current steps in the workflow instance.
 *            <li><code>store</code>: The {@link com.opensymphony.workflow.spi.WorkflowStore}.
 *            <li><code>descriptor</code>: The {@link com.opensymphony.workflow.loader.WorkflowDescriptor}.
 *            </ul>
 *            Also, any variable set as a {@link com.opensymphony.workflow.Register}), will also be available in the
 *            transient map, no matter what. These transient variables only last through the method call that they
 *            were invoked in, such as {@link Workflow#initialize} and {@link Workflow#doAction}.
 * @param args
 *            The properties for this function invocation. Properties are created from arg nested elements within
 *            the xml, an arg element takes in a name attribute which is the properties key, and the CDATA text
 *            contents of the element map to the property value.
 * @param ps
 *            The persistent variables that are associated with the current instance of the workflow. Any change
 *            made to the propertyset are persisted to the propertyset implementation's persistent store.
 * @see com.opensymphony.workflow.FunctionProvider#execute(java.util.Map, java.util.Map,
 *      com.opensymphony.module.propertyset.PropertySet)
 */
public void executeFunction(Map transientVars, Map args, PropertySet ps) throws WorkflowException {

    // Get the workflow object
    WorkflowEntry workflow = (WorkflowEntry) transientVars
            .get(ModuleSharedVariables.FUNCTION_INPUTARGUMENT_ENTRY);

    // get the workflow descriptor
    WorkflowDescriptor descriptor = (WorkflowDescriptor) transientVars
            .get(ModuleSharedVariables.FUNCTION_INPUTARGUMENT_DESCRIPTOR);

    // get the subject and the body of the email
    String entered_body = (String) args.get(PARAM_EMAIL_BODY);
    if (StringChecker.isNotNullOrEmpty(entered_body)) {
        //LOGGER.debug("WF | entered body = " + entered_body);
        _email_body = this.treatEmailBody(entered_body.trim());
    }
    String entered_subject = (String) args.get(PARAM_EMAIL_SUBJECT);
    if (StringChecker.isNotNullOrEmpty(entered_subject)) {
        _email_subject = entered_subject.trim();
    }

    // Get the list of receiver encoded in a String
    String receiverString = ((String) args.get(PARAM_RECEIVERS)).trim();
    if (StringChecker.isNotNullOrEmpty(receiverString)) {
        List<String> receivers = this.extractListOfReceivers(receiverString, _cmsObject, _associatedFiles);

        /*
         * get smtp
         */
        String smtp = ((CmsMailHost) OpenCms.getSystemInfo().getMailSettings().getMailHosts().get(0))
                .getHostname();
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp);

        /*
         * Send emails
         */
        Iterator<String> emailsIterator = receivers.iterator();
        while (emailsIterator.hasNext()) {
            String email = emailsIterator.next();
            try {
                this.sendEmail(props, email, this._email_subject,
                        this.generateEmailText(email, _associatedFiles, workflow, descriptor),
                        MAIL_DEFAULTSENDER);
            } catch (MessagingException e) {
                LOGGER.warn(
                        "The notification message has not be sent to " + email + " (" + e.getMessage() + ")");
            }
        }
    } else {
        LOGGER.warn("The function " + this.getClass().getName() + " doesn't receive a valid parameter "
                + PARAM_RECEIVERS);
    }

}

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 w ww .  j  a va 2 s .co 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:org.rhq.enterprise.server.core.EmailManagerBean.java

/**
 * Send email to the addressses passed in toAddresses with the passed subject and body. Invalid emails will
 * be reported back. This can only catch sender errors up to the first smtp gateway.
 * @param  toAddresses list of email addresses to send to
 * @param  messageSubject subject of the email sent
 * @param  messageBody body of the email to be sent
 *
 * @return list of email receivers for which initial delivery failed.
 *///from w  w w.j  av a2  s. com
public Collection<String> sendEmail(Collection<String> toAddresses, String messageSubject, String messageBody) {

    MimeMessage mimeMessage = new MimeMessage(mailSession);
    try {
        mimeMessage.setSubject(messageSubject);
        mimeMessage.setContent(messageBody, "text/plain");
    } catch (MessagingException e) {
        e.printStackTrace(); // TODO: Customise this generated block
        return toAddresses;
    }

    Exception error = null;
    Collection<String> badAdresses = new ArrayList<String>(toAddresses.size());

    // Send to each recipient individually, do not throw exceptions until we try them all
    for (String toAddress : toAddresses) {
        try {
            LOG.debug("Sending email [" + messageSubject + "] to recipient [" + toAddress + "]");
            InternetAddress recipient = new InternetAddress(toAddress);
            Transport.send(mimeMessage, new InternetAddress[] { recipient });
        } catch (Exception e) {
            LOG.error("Failed to send email [" + messageSubject + "] to recipient [" + toAddress + "]: "
                    + e.getMessage());
            badAdresses.add(toAddress);

            // Remember the first error - in case its due to a session initialization problem,
            // we don't want to lose the first error.
            if (error == null) {
                error = e;
            }
        }
    }

    if (error != null) {
        LOG.error("Sending of emails failed for this reason: " + error.getMessage());
    }

    return badAdresses;
}

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

public void _send(lucee.runtime.config.ConfigWeb config) throws MailException {

    long start = System.nanoTime();
    long _timeout = getTimeout(config, timeout);
    try {//from   ww  w.  ja va  2 s  .com

        Proxy.start(proxyData);
        Log log = ((ConfigImpl) config).getLog("mail");
        // Server
        Server[] servers = config.getMailServers();
        if (host != null) {
            int prt;
            String usr, pwd;
            ServerImpl[] nServers = new ServerImpl[host.length];
            for (int i = 0; i < host.length; i++) {
                usr = null;
                pwd = null;
                prt = ServerImpl.DEFAULT_PORT;

                if (port > 0)
                    prt = port;
                if (!StringUtil.isEmpty(username)) {
                    usr = username;
                    pwd = password;
                }
                nServers[i] = toServerImpl(host[i], prt, usr, pwd, lifeTimespan, idleTimespan);
                if (ssl == SSL_YES)
                    nServers[i].setSSL(true);
                if (tls == TLS_YES)
                    nServers[i].setTLS(true);

            }
            servers = nServers;
        }
        if (servers.length == 0) {
            //return;
            throw new MailException("no SMTP Server defined");
        }

        boolean _ssl, _tls;
        for (int i = 0; i < servers.length; i++) {

            Server server = servers[i];
            String _username = null, _password = "";
            //int _port;

            // username/password

            if (server.hasAuthentication()) {
                _username = server.getUsername();
                _password = server.getPassword();
            }

            // tls
            if (tls != TLS_NONE)
                _tls = tls == TLS_YES;
            else
                _tls = ((ServerImpl) server).isTLS();

            // ssl
            if (ssl != SSL_NONE)
                _ssl = ssl == SSL_YES;
            else
                _ssl = ((ServerImpl) server).isSSL();

            MimeMessageAndSession msgSess;
            boolean recyleConnection = ((ServerImpl) server).reuseConnections();
            {//synchronized(LOCK) { no longer necessary we have a proxy lock now
                try {

                    msgSess = createMimeMessage(config, server.getHostName(), server.getPort(), _username,
                            _password, ((ServerImpl) server).getLifeTimeSpan(),
                            ((ServerImpl) server).getIdleTimeSpan(), _tls, _ssl, !recyleConnection);

                } catch (MessagingException e) {
                    // listener
                    listener(config, server, log, e, System.nanoTime() - start);
                    MailException me = new MailException(e.getMessage());
                    me.setStackTrace(e.getStackTrace());
                    throw me;
                }

                try {
                    SerializableObject lock = new SerializableObject();
                    SMTPSender sender = new SMTPSender(lock, msgSess, server.getHostName(), server.getPort(),
                            _username, _password, recyleConnection);
                    sender.start();
                    SystemUtil.wait(lock, _timeout);

                    if (!sender.isSent()) {
                        Throwable t = sender.getThrowable();
                        if (t != null)
                            throw Caster.toPageException(t);

                        // stop when still running
                        try {
                            if (sender.isAlive())
                                sender.stop();
                        } catch (Throwable t2) {
                        }

                        // after thread is stopped check sent flag again
                        if (!sender.isSent()) {
                            throw new MessagingException("timeout occurred after " + (_timeout / 1000)
                                    + " seconds while sending mail message");
                        }
                    }
                    clean(config, attachmentz);

                    listener(config, server, log, null, System.nanoTime() - start);
                    break;
                } catch (Exception e) {
                    e.printStackTrace();
                    if (i + 1 == servers.length) {

                        listener(config, server, log, e, System.nanoTime() - start);
                        MailException me = new MailException(
                                server.getHostName() + " " + ExceptionUtil.getStacktrace(e, true) + ":" + i);
                        me.setStackTrace(e.getStackTrace());

                        throw me;
                    }
                }
            }
        }
    } finally {
        Proxy.end();
    }
}

From source file:org.dspace.workflowbasic.BasicWorkflowServiceImpl.java

@Override
public void notifyOfCuration(Context c, BasicWorkflowItem wi, List<EPerson> ePeople, String taskName,
        String action, String message) throws SQLException, IOException {
    try {//  www . j  av  a  2  s . c o m
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        for (EPerson epa : ePeople) {
            Locale supportedLocale = I18nUtil.getEPersonLocale(epa);
            Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "flowtask_notify"));
            email.addArgument(title);
            email.addArgument(coll.getName());
            email.addArgument(submitter);
            email.addArgument(taskName);
            email.addArgument(message);
            email.addArgument(action);
            email.addRecipient(epa.getEmail());
            email.send();
        }
    } catch (MessagingException e) {
        log.warn(LogManager.getHeader(c, "notifyOfCuration",
                "cannot email users of workflow_item_id " + wi.getID() + ":  " + e.getMessage()));
    }
}

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

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