Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

In this page you can find the example usage for javax.mail Session getInstance.

Prototype

public static Session getInstance(Properties props, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;/*from w  w  w  .  jav  a 2 s .  c o  m*/
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.apache.jmeter.reporters.MailerModel.java

/**
 * Sends a mail with the given parameters using SMTP.
 *
 * @param from//from www. j  a  v  a 2s  .c o  m
 *            the sender of the mail as shown in the mail-client.
 * @param vEmails
 *            all receivers of the mail. The receivers are seperated by
 *            commas.
 * @param subject
 *            the subject of the mail.
 * @param attText
 *            the message-body.
 * @param smtpHost
 *            the smtp-server used to send the mail.
 * @param smtpPort the smtp-server port used to send the mail.
 * @param user the login used to authenticate
 * @param password the password used to authenticate
 * @param mailAuthType {@link MailAuthType} Security policy
 * @param debug Flag whether debug messages for the mail session should be generated
 * @throws AddressException If mail address is wrong
 * @throws MessagingException If building MimeMessage fails
 */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost,
        String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug)
        throws AddressException, MessagingException {

    InternetAddress[] address = new InternetAddress[vEmails.size()];

    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }

    // create some properties and get the default Session
    Properties props = new Properties();

    props.put(MAIL_SMTP_HOST, smtpHost);
    props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch (mailAuthType) {
        case SSL:
            props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
            break;
        case TLS:
            props.put(MAIL_SMTP_STARTTLS, "true");
            break;

        default:
            break;
        }
    }

    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

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

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}

From source file:com.nridge.core.app.mail.MailManager.java

private void initialize() throws IOException, NSException {
    Logger appLogger = mAppMgr.getLogger(this, "initialize");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mMailSession == null) {
        String propertyName = "account_name";
        String mailAccountName = getCfgString(propertyName);
        if (StringUtils.isEmpty(mailAccountName)) {
            String msgStr = String.format("Mail Manager property '%s' is undefined.",
                    mCfgPropertyPrefix + "." + propertyName);
            appLogger.error(msgStr);/* ww w.j ava 2s  .co  m*/
            throw new NSException(msgStr);
        }
        propertyName = "account_password";
        String mailAccountPassword = getCfgString(propertyName);
        if (StringUtils.isEmpty(mailAccountPassword)) {
            String msgStr = String.format("Mail Manager property '%s' is undefined.",
                    mCfgPropertyPrefix + "." + propertyName);
            appLogger.error(msgStr);
            throw new NSException(msgStr);
        }

        MailAuthenticator mailAuthenticator = new MailAuthenticator(mailAccountName, mailAccountPassword);

        propertyName = "smtp_host";
        String smtpHostName = getCfgString(propertyName);
        if (StringUtils.isEmpty(smtpHostName)) {
            String msgStr = String.format("Mail Manager property '%s' is undefined.",
                    mCfgPropertyPrefix + "." + propertyName);
            appLogger.error(msgStr);
            throw new NSException(msgStr);
        }
        propertyName = "smtp_port";
        String smtpPortNumber = getCfgString(propertyName);
        if (StringUtils.isEmpty(smtpHostName)) {
            String msgStr = String.format("Mail Manager property '%s' is undefined.",
                    mCfgPropertyPrefix + "." + propertyName);
            appLogger.error(msgStr);
            throw new NSException(msgStr);
        }

        Properties systemProperties = new Properties();

        systemProperties.setProperty("mail.smtp.submitter", mailAccountName);
        systemProperties.setProperty("mail.smtp.host", smtpHostName);
        systemProperties.setProperty("mail.smtp.port", smtpPortNumber);
        if (isCfgStringTrue("authn_enabled")) {
            systemProperties.setProperty("mail.smtp.auth", "true");
            systemProperties.setProperty("mail.smtp.starttls.enable", "true");
            mMailSession = Session.getInstance(systemProperties, mailAuthenticator);
        } else
            mMailSession = Session.getInstance(systemProperties);

        mConfiguration = new Configuration(Configuration.VERSION_2_3_21);
        String cfgPathName = mAppMgr.getString(mAppMgr.APP_PROPERTY_CFG_PATH);
        File cfgPathFile = new File(cfgPathName);
        try {
            mConfiguration.setDirectoryForTemplateLoading(cfgPathFile);
        } catch (IOException e) {
            appLogger.error(cfgPathName, e);
        }
        mConfiguration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_21));
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.iana.boesc.utility.BOESCUtil.java

public static boolean sendEmailWithAttachments(final String emailFrom, final String subject,
        final InternetAddress[] addressesTo, final String body, final File attachment) {
    try {/* ww  w  .j  a  v a2s.c o m*/
        Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", "");
            }
        });

        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        InternetAddress addressFrom = new InternetAddress(emailFrom);
        message.setFrom(addressFrom);

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, addressesTo);

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part
        BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(body);
        messageBodyPart.setContent(body, "text/html");

        // Create a multi part message
        Multipart multipart = new javax.mail.internet.MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new javax.mail.internet.MimeBodyPart();

        DataSource source = new FileDataSource(attachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(attachment.getName());
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        Transport.send(message);

        return true;
    } catch (Exception ex) {
        ex.getMessage();
        return false;
    }
}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event//from w w w.j ava 2 s.  c o  m
 */
public synchronized void contextInitialized(ServletContextEvent event) {
    context = event.getServletContext();

    // Get the configuration file
    String configPathTemp = (String) context.getInitParameter(INIT_PARAM_CONFIG_PATH);

    // Use the default path if it wasn't specified
    if (StringUtils.isBlank(configPathTemp))
        configPathTemp = DEFAULT_CONFIG_PATH;

    // Finalize the config path (needs to be final for inner-Runnable below)
    final String configPath = configPathTemp;
    context.setAttribute(CONTEXT_ATTR_CONFIG_PATH, configPath);

    try {
        // Load the configuration
        DefaultConfigurationBuilder configBuilder = new DefaultConfigurationBuilder();
        configBuilder.setFileName(configPath);

        final CombinedConfiguration config = configBuilder.getConfiguration(true);

        // Save the config where we can get at it later
        context.setAttribute(CONTEXT_ATTR_CONFIG, config);
        Global.put(CONTEXT_ATTR_CONFIG, config);

        // Determine the localhost
        String localhost = config.getString(PROP_LOCALHOST, "ip");
        if (localhost.equalsIgnoreCase("ip")) {
            try {
                localhost = InetAddress.getLocalHost().getHostAddress();
                log.info("Using localhost: " + localhost);
            } catch (Exception e) {
                log.warn("Error determining localhost", e);
                localhost = "localhost";
            }
        }

        context.setAttribute(CONTEXT_ATTR_LOCALHOST, localhost);
        Global.put(CONTEXT_ATTR_LOCALHOST, localhost);
        loadedConfigPropKeys.add(CONTEXT_ATTR_LOCALHOST);

        // Set application context attributes for all config properties
        String prop, value;
        Iterator itr = config.getKeys();
        while (itr.hasNext()) {
            prop = (String) itr.next();
            value = config.getString(prop);

            // Anything with the value "localhost" will be set to the IP if possible
            value = (value.equals("localhost") ? localhost : value);

            log.debug("Config: " + prop + " = " + value);
            context.setAttribute(prop, value);
            loadedConfigPropKeys.add(prop);
        }

        // Run Mode configuration
        String runMode = config.getString(PROP_RUNMODE);
        try {
            RUN_MODE = RunMode.valueOf(runMode);
        } catch (Exception e) {
            log.warn("Error setting runmode, invalid value: " + runMode);
        }

        context.setAttribute("devMode", RUN_MODE != RunMode.PRODUCTION);
        loadedConfigPropKeys.add("devMode");

        // Fragment Cache Configuration
        if (config.getBoolean(FragmentCache.Properties.ENABLED, false)) {
            log.info("Enabling fragment caching...");
            FragmentCacheTag.enable();

            // This is expected to be in seconds
            long temp = config.getLong(FragmentCache.Properties.REQUEST_TIMEOUT, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag request timeout: " + temp);
                FragmentCacheTag.setRequestTimeout(temp);
            }

            // The property is in seconds, but WARNING_COMPUTE_DURATION does NOT use a TimeUnit, so it's in ms
            temp = config.getLong(FragmentCache.Properties.WARNING_DURATION, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag warning duration: " + temp);
                FragmentCacheTag.setWarningComputeDuration(temp * 1000);
            }

            // Get the fragment cache names
            String[] cacheNames = config.getStringArray(FragmentCache.Properties.ENGINE_NAMES);
            for (String cacheName : cacheNames) {
                String cacheClassName = config
                        .getString(String.format(FragmentCache.Properties.ENGINE_CLASS_TEMPLATE, cacheName));
                try {
                    // Load up the class
                    Class<? extends FragmentCache> cacheClass = (Class<? extends FragmentCache>) Class
                            .forName(cacheClassName);

                    // Look for a constructor that takes a config
                    Constructor<? extends FragmentCache> constructor = null;
                    try {
                        constructor = cacheClass.getConstructor(Configuration.class);
                    } catch (Exception e) {
                    }

                    FragmentCache cache;

                    // If we found the configuration constructor, use it
                    if (constructor != null)
                        cache = constructor.newInstance(config);
                    else {
                        // otherwise use a default no-args constructor
                        log.warn("Could not find a " + cacheClass.getSimpleName()
                                + " constructor that takes a Configuration, defaulting to no-args constructor");
                        cache = cacheClass.newInstance();
                    }

                    // register the cache with the FragmentCacheTag using the config strategy-name, or the engineName
                    // if a strategy-name is not specified
                    log.info("Registering FragmentCache strategy: [name=" + cacheName + ", class="
                            + cacheClass.getName() + "]");
                    FragmentCacheTag.registerStrategy(cacheName, cache);
                } catch (Exception e) {
                    log.error("Error enabling FragmentCache engine: " + cacheName, e);
                }
            }

        } else {
            // Have to call this here, because reconfiguration could turn
            // the cache off after it was previously enabled.
            FragmentCacheTag.disable();
        }

        // For Task execution
        ScheduledExecutorService taskExecutor;

        if (config.getBoolean(PROP_TASK_EXECUTOR_ON, false)) {
            int threads = config.getInt(PROP_TASK_EXECUTOR_THREADS, DEFAULT_TASK_EXECUTOR_THREADS);

            if (threads == 1)
                taskExecutor = Executors.newSingleThreadScheduledExecutor();
            else
                taskExecutor = Executors.newScheduledThreadPool(threads);

            context.setAttribute(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
            loadedConfigPropKeys.add(CONTEXT_ATTR_TASK_MANAGER);

            Global.put(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
        } else {
            // Not allowed to shutdown the taskExecutor if dynamic reconfig is enabled
            if (reconfigTask == null) {
                // Shutdown and remove references to the taskManager previously created
                taskExecutor = (ScheduledExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
                if (taskExecutor != null) {
                    taskExecutor.shutdown(); // will block until all tasks complete
                    taskExecutor = null;
                    Global.remove(CONTEXT_ATTR_TASK_MANAGER);
                }
            } else {
                // We could just log a warning that you can't do this, but the user
                // might not see that, so we're going to refuse to reset a configuration
                // that cannot be loaded in whole successfully.
                throw new ConfigurationException(
                        "Cannot disable task execution service, dynamic reconfiguration is enabled!");
            }
        }

        // Email Service
        if (config.getBoolean(PROP_MAIL_SERVICE_ON, false)) {
            if (!SimpleEmailService.isEnabled()) {
                // Get the SMTP properties
                Properties props = System.getProperties();
                props.put(PROP_SMTP_HOST, config.getString(PROP_SMTP_HOST));
                props.put(PROP_SMTP_PORT, config.getString(PROP_SMTP_PORT));
                props.put(PROP_SMTP_AUTH, config.getString(PROP_SMTP_AUTH));

                Session session;

                if (config.getBoolean(PROP_SMTP_AUTH)) {
                    final String user = config.getString(PROP_SMTP_USER);
                    final String pass = config.getString(PROP_SMTP_PASS);

                    Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    };
                    session = Session.getInstance(props, auth);

                } else {
                    session = Session.getInstance(props);
                }

                // Get the global headers
                Iterator headerNames = config.getKeys(PROP_MAIL_HEADER_PREFIX);
                List<KeyValuePair<String, String>> headers = new LinkedList<KeyValuePair<String, String>>();

                String headerName;
                while (headerNames.hasNext()) {
                    headerName = (String) headerNames.next();
                    headers.add(new KeyValuePair<String, String>(headerName, config.getString(headerName)));
                }

                // Initialize the service
                SimpleEmailService.init(session);
                SimpleEmailService.setGlobalHeaders(headers);

                // Set whether we actually send the e-mails
                SimpleEmailService.setDummyMode(config.getBoolean(PROP_MAIL_DUMMY_MODE, false));

                // Set the failure policy
                String policy = config.getString(PROP_MAIL_ERROR_POLICY);
                if (policy != null) {
                    if (policy.equals(VALUE_MAIL_POLICY_DISCARD)) {
                        SimpleEmailService.setErrorPolicy(new SimpleEmailService.DiscardPolicy());
                    } else if (policy.equals(VALUE_MAIL_POLICY_REQUEUE)) {
                        Priority priority = null;
                        try {
                            priority = Priority.valueOf(config.getString(PROP_MAIL_REQUEUE_PRIORITY));
                        } catch (Exception e) {
                            log.warn("Error reading requeue policy priority: "
                                    + config.getString(PROP_MAIL_REQUEUE_PRIORITY, "") + ", using default");
                        }

                        if (priority == null)
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy());
                        else
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy(priority));
                    }
                }

                // Parse templates
                String emailTemplateDir = config.getString(PROP_MAIL_TEMPLATE_DIR);

                // If the template
                if (StringUtils.isBlank(emailTemplateDir))
                    emailTemplateDir = DEFAULT_EMAIL_TEMPLATE_DIR;

                log.debug("Looking for e-mail templates in: " + emailTemplateDir);
                Set<String> templates = context.getResourcePaths(emailTemplateDir);

                // E-mail templates
                if (templates != null && !templates.isEmpty()) {
                    log.debug("Found " + templates.size() + " templates");

                    String key;
                    String defaultTemplate = config.getString(PROP_MAIL_DEFAULT_TEMPLATE, EMPTY);

                    InputStream in;
                    StringBuilder builder;
                    Scanner scanner;

                    try {
                        Template template;
                        String[] parts;

                        ContentType contentType;

                        for (String path : templates) {
                            path = path.trim();
                            parts = path.split("\\.");

                            contentType = ContentType.valueOfExt(parts[1]);

                            try {
                                in = context.getResourceAsStream(path.trim());

                                if (in != null && in.available() > 0) {
                                    scanner = new Scanner(in);
                                    builder = new StringBuilder();

                                    while (scanner.hasNextLine()) {
                                        builder.append(scanner.nextLine());
                                        if (contentType == ContentType.PLAIN) {
                                            builder.append("\n");
                                        }
                                    }

                                    template = new Template(builder.toString(), contentType);

                                    key = parts[0].replace(emailTemplateDir, EMPTY);
                                    SimpleEmailService.registerTemplate(key, template,
                                            key.equals(defaultTemplate));
                                }
                            } catch (IOException ioe) {
                                log.error("Error loading e-mail template: " + path, ioe);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error loading e-mail templates", e);
                    }
                } else
                    log.debug("No e-mail templates found.");
            }
        } else if (SimpleEmailService.isEnabled()) {
            boolean shutdown = false;
            try {
                shutdown = SimpleEmailService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while shutting down SimpleEmailService");
            }

            if (!shutdown)
                SimpleEmailService.shutdown();
        }

        // QueuedHttpCallService
        if (config.getBoolean(PROP_HTTP_SRVC_ON, false)) {
            if (!SimpleHttpService.isEnabled()) // Don't double init...
            {
                int defaultThreadCount = Runtime.getRuntime().availableProcessors() + 1; // threads to use if unspecified
                SimpleHttpService.init(config.getInt(PROP_HTTP_SRVC_CORE_POOL, defaultThreadCount),
                        config.getInt(PROP_HTTP_SRVC_MAX_POOL, defaultThreadCount),
                        config.getLong(PROP_HTTP_SRVC_POOL_IDLE, DEFAULT_HTTP_SRVC_THREAD_IDLE),
                        config.getInt(PROP_HTTP_SRVC_CONNECT_TOUT, DEFAULT_HTTP_SRVC_CONNECT_TOUT),
                        config.getInt(PROP_HTTP_SRVE_SOCKET_TOUT, DEFAULT_HTTP_SRVE_SOCKET_TOUT));
            }
        } else if (SimpleHttpService.isEnabled()) {
            boolean shutdown = false;
            try {
                // Try to shutdown the service while letting currently waiting tasks complete
                shutdown = SimpleHttpService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while waiting for SimpleHttpService to shutdown");
            }
            if (!shutdown) {
                // But if that doesn't finish in 60 seconds, just cut it off
                int count = SimpleHttpService.shutdown().size();
                log.warn("SimpleHttpService failed to shutdown in 60 seconds, so it was terminated with "
                        + count + " tasks waiting");
            }
        }

        // Spymemcached Client
        if (config.getBoolean(PROP_SPYMEMCACHED_ON, false)) {
            String addresses = config.getString(PROP_SPYMEMCACHED_ADDRESSES);
            if (addresses == null) {
                log.error("Error configuring spymemcached; enabled but no addresses!");
            } else {
                try {
                    // Reflect our way to the constructor, this is all so that the
                    // spymemcached jar does not need to be included in a J2Free app
                    // unless it is actually to be used.
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Constructor constructor = klass.getConstructor(List.class);

                    klass = Class.forName("net.spy.memcached.AddrUtil");
                    Method method = klass.getMethod("getAddresses", String.class);

                    Object client = constructor.newInstance(method.invoke(null, addresses));

                    context.setAttribute(CONTEXT_ATTR_SPYMEMCACHED, client);
                    loadedConfigPropKeys.add(CONTEXT_ATTR_SPYMEMCACHED);

                    Global.put(CONTEXT_ATTR_SPYMEMCACHED, client);

                    log.info("Spymemcached client created, connected to " + addresses);
                } catch (Exception e) {
                    log.error("Error creating memcached client [addresses=" + addresses + "]", e);
                }
            }
        } else {
            // If a spymemcached client was previous created
            Object client = Global.get(CONTEXT_ATTR_SPYMEMCACHED);
            if (client != null) {
                try {
                    // Reflect our way to the shutdown method
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Method method = klass.getMethod("shutdown");

                    method.invoke(null, client); // and shut it down

                    log.info("Spymemcached client shutdown");
                } catch (Exception e) {
                    log.error("Error shutting down spymemcached client", e);
                }

                // Then remove any references
                Global.remove(CONTEXT_ATTR_SPYMEMCACHED);
                client = null;
            }
        }
    } catch (ConfigurationException ce) {
        log.error("Error configuring app", ce);
    }
}

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
 * //  ww w .j a  va2s  . c  o  m
 * @param mailOptions
 * @return
 */

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

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

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

        File tempFolder = new File(tempFolderPath);

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

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

        try {

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

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

            from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
            if ((from == null) || from.trim().equals(""))
                from = "spagobi.scheduler@eng.it";
            user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
            if ((user == null) || user.trim().equals("")) {
                logger.debug("Smtp user not configured");
                user = null;
            }
            //   throw new Exception("Smtp user not configured");
            pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
            if ((pass == null) || pass.trim().equals("")) {
                logger.debug("Smtp password not configured");
            }
            //   throw new Exception("Smtp password not configured");
        } catch (Exception e) {
            logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.",
                    e);
            throw new Exception(
                    "Some E-mail configuration not set in table sbi_config: check you have all settings.");
        }

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

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

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

        // open session
        Session session = null;

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

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

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

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

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

        String subject = mailSubj;

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

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

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

        // attach the file to the message

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

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

        mp.addBodyPart(mbp1);

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

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

                    byte[] content = getBytesFromFile(f);

                    bodyPart = new MimeBodyPart();

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

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

                    mp.addBodyPart(bodyPart);
                }

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

        }

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

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

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

From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java

/**
 * Prepara la Session per l'invio della mail, inoltre effettua l'handshake SSL con l'host di destinazione quando richiesto. 
 * @return La Session pronta per l'uso.//  w  ww .j  a  v a  2  s. c o m
 */
protected Session createSession(boolean sentMail, String username, String password) throws ApsSystemException {
    //Properties properties = System.getProperties();
    Properties properties = new Properties();
    WebMailConfig config = this.getConfig();
    String imapProtocol = config.getImapProtocol();
    String host = config.getImapHost();
    Integer port = config.getImapPort();

    if (null != imapProtocol && imapProtocol.trim().length() > 0) {
        properties.setProperty("mail.store.protocol", imapProtocol);
    } else {
        throw new ApsSystemException("IMAP Protocoll missing");
    }
    if (null != host && host.trim().length() > 0) {
        properties.setProperty("mail.imap.host", host);
    } else {
        throw new ApsSystemException("IMAP host missing");
    }
    if (null != port && port.intValue() > 0) {
        properties.setProperty("mail.imap.port", port.toString());
    } else {
        throw new ApsSystemException("IMAP port missing");
    }
    // analizza il certificato dell'host. Se l'handshake  gi stato effettuato ritorna immediatamente
    this.getCertificateHandler().aquireCertificate(host, port.intValue(), imapProtocol, config);
    // verifica se si possa procedere in sicurezza con la connessione all'host
    if (!this.getCertificateHandler().proceedWithConnection()) {
        _logger.info("Connection to host '" + host + "' not trusted");
        //ApsSystemUtils.getLogger().info("Connection to host '" + host + "' not trusted");
    } else {
        _logger.info("Connection to host '" + host + "' trusted");
        //ApsSystemUtils.getLogger().info("Connection to host '" + host + "' trusted");
    }
    properties.setProperty("mail.imap.timeout", "5000");
    if (imapProtocol.equalsIgnoreCase("imaps")) {
        properties.setProperty("mail.imap.ssl.protocols", "SSL");
        properties.setProperty("mail.imap.starttls.enable", "true");
    }

    if (config.getLocalhost() != null && config.getLocalhost().trim().length() > 0) {
        properties.put("mail.smtp.localhost", config.getLocalhost());
    }

    //SMTP START
    properties.put("mail.smtp.host", config.getSmtpHost());
    Integer smtpPort = config.getSmtpPort();
    if (smtpPort != null && smtpPort.intValue() > 0) {
        properties.put("mail.smtp.port", smtpPort.toString());
    }

    int timeout = DEFAULT_SMTP_TIMEOUT;
    Integer timeoutParam = null;//config.getSmtpTimeout();
    if (null != timeoutParam && timeoutParam.intValue() != 0) {
        timeout = timeoutParam;
    }
    properties.put("mail.smtp.connectiontimeout", timeout);
    properties.put("mail.smtp.timeout", timeout);

    Session session = null;

    if (sentMail) {
        properties.put("mail.smtp.auth", "true");
        switch (config.getSmtpProtocol()) {
        case WebMailConfig.PROTO_SSL:
            properties.put("mail.smtp.socketFactory.port", smtpPort.toString());
            properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.put("mail.transport.protocol", "smtps");
            break;
        case WebMailConfig.PROTO_TLS:
            properties.put("mail.smtp.starttls.enable", "true");
            break;
        case WebMailConfig.PROTO_STD:
            //do nothing just use previous properties WITH the authenticator
            break;
        }
        Authenticator auth = new SMTPAuthenticator(username, password);
        session = Session.getInstance(properties, auth);
    } else {
        session = Session.getDefaultInstance(properties);
    }
    return session;
}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);/*  w  ww . ja  v a 2s.c om*/
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:jp.mamesoft.mailsocketchat.Mail.java

public static void Send(String to, int mode) {
    //mode 0 = ?, 1 = ?, 2 = ?, 3 = ??, 4 = , 5 = 
    System.out.println("???");
    String from = Mailsocketchat.mail_user;
    String host = "smtp.gmail.com";
    String port = "465";
    String text = "";
    String subject = "";
    if (mode == 0) {
        text = logprint(text);//from w w  w .  j  a va  2 s  .  co m
        subject = " - MailSocketChat";
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 1) {
        if (Mailsocketchat.subjectname) {
            subject = Mailsocketchat.logs.get(0).get("name");
        } else {
            subject = "?? - MailSocketChat";
        }
        text = logprint(text);
    }
    if (mode == 8) {
        text = logprint(text);
        subject = "?? - MailSocketChat";
    }
    if (mode == 2) {

        if (!Mailsocketchat.push) {
            subject = "????? - MailSocketChat";
            text = "???????????????????\n\n??????\n";
            text = logprint(text);
        } else {
            subject = "??? - MailSocketChat";
            text = "?????????????????\n(???????????)\n\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 3) {

        if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
            subject = "???? - MailSocketChat";
            text = "????\n\n??????\n";
            text = logprint(text);
        } else {
            subject = "?????? - MailSocketChat";
            text = "?????????????????\n\n";
            if (Mailsocketchat.repeat) {
                text = text + "??????\n";
                text = logprint(text);
            }
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }

    if (mode == 7) {

        if (!Mailsocketchat.repeat) {
            subject = "????? - MailSocketChat";
            text = "?????30????????????\n\n";
            if (!Mailsocketchat.push) {
                text = text + "??????\n";
                text = logprint(text);
            }
        } else {
            subject = "??? - MailSocketChat";
            text = "???\n\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }

    if (mode == 4) {
        subject = " - MailSocketChat";

        int userint = Mailsocketchat.users.size();
        int romint = Mailsocketchat.roms.size();
        text = ": " + userint + " ROM: " + romint + "\n\n\n";

        for (Integer id : Mailsocketchat.users.keySet()) {
            HashMap<String, String> data = Mailsocketchat.users.get(id);
            text = text + data.get("name") + "\n";
            text = text + " (" + data.get("ip") + ")\n";
        }

        text = text + "\n\nROM\n";
        for (Integer id : Mailsocketchat.roms.keySet()) {
            HashMap<String, String> data = Mailsocketchat.roms.get(id);
            text = text + data.get("ip") + "\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 5) {
        subject = " - MailSocketChat";
        if (Mailsocketchat.push) {
            text = "??: \n\n";
        } else if (Mailsocketchat.repeat) {
            text = "??: \n\n";
        } else {
            text = "??: ?\n\n";
        }
        text = text + "?\n";
        text = text + "?(fetch): ?????\n";
        text = text + "(push): ????\n";
        text = text + "(repeat): ????\n";
        text = text + "(list): ???\n";
        text = text + "#: ?????\n";
        text = text + "#hoge: ??hoge????\n";
        text = text + "(help): ?????\n\n";

        text = text + "\nMailSocketChat Ver." + Mailsocketchat.version + "\n";
        if (Mailsocketchat.newver) {
            text = text + "??????????\n";
        }
    }
    if (mode == 6) {
        subject = "????????? - MailSocketChat";
        text = text
                + "MailSocketChat??????????????????\n";
    }

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session sendsession = Session.getInstance(props,
            new PlainAuthenticator(Mailsocketchat.mail_user, Mailsocketchat.mail_pass));

    try {
        // create a message
        MimeMessage msg = new MimeMessage(sendsession);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] sendaddress = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, sendaddress);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(text);

        Transport.send(msg);
        System.out.println("?????");
    } catch (MessagingException mex) {
        System.out.println("??????");
    }
}

From source file:io.starter.datamodel.Sys.java

/**
 * /*from w  ww. j  ava2 s .c o m*/
 * @param params
 * @throws Exception
 * 
 * 
 */
public static void sendEmail(String url, final User from, String toEmail, Map params, SqlSession session,
        CountDownLatch latch) throws Exception {

    final CountDownLatch ltc = latch;

    if (from == null) {
        throw new ServletException("Sys.sendEmail cannot have a null FROM User.");
    }
    String fromEmail = from.getEmail();
    final String fro = fromEmail;
    final String to = toEmail;
    final Map p = params;
    final String u = url;
    final SqlSession sr = session;

    // TODO: check message sender/recipient validity
    if (!checkEmailValidity(fromEmail)) {
        throw new RuntimeException(
                fromEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED");
    }
    // TODO: check mail server if it's a valid message
    if (!checkEmailValidity(toEmail)) {
        throw new RuntimeException(
                toEmail + " is not a valid email address. SENDING MESSAGE TO " + toEmail + " FAILED");
    }

    // message.setSubject("Testing Email From Starter.io");
    // Send the actual HTML message, as big as you like
    // fetch the content
    final String content = getText(u);

    new Thread(new Runnable() {
        @Override
        public void run() {
            // Sender's email ID needs to be mentioned
            // String sendAccount = "$EMAIL_USER_NAME$";

            // final String username = "$EMAIL_USER_NAME$", password =
            // "hum0rm3";

            // Assuming you are sending email from localhost
            // String host = "gator3083.hostgator.com";

            String sendAccount = "$EMAIL_USER_NAME$";
            final String username = "$EMAIL_USER_NAME$", password = "$EMAIL_USER_PASS$";

            // Assuming you are sending email from localhost
            String host = SystemConstants.EMAIL_SERVER;

            // Get system properties
            Properties props = System.getProperties();

            // Setup mail server
            props.setProperty("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.port", "587");

            // Get the default Session object.
            Session session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            try {
                // Create a default MimeMessage object.
                MimeMessage message = new MimeMessage(session);

                // Set From: header field of the header.
                message.setFrom(new InternetAddress(sendAccount));
                // Set To: header field of the header.
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

                message.addRecipient(Message.RecipientType.TO, new InternetAddress(sendAccount));

                // Set Subject: header field
                Object o = p.get("MESSAGE_SUBJECT");
                message.setSubject(o.toString());

                String ctx = new String(content.toString());

                // TODO: String Rep on the params
                ctx = stringRep(ctx, p);

                message.setContent(ctx, "text/html; charset=utf-8");

                // message.setContent(new Multipart());
                // Send message
                Transport.send(message);

                Logger.log("Sending message to:" + to + " SUCCESS");
            } catch (MessagingException mex) {
                // mex.printStackTrace();
                Logger.log("Sending message to:" + to + " FAILED");
                Logger.error("Sys.sendEmail() failed to send message. Messaging Exception: " + mex.toString());
            }
            // log the data
            Syslog logEntry = new Syslog();

            logEntry.setDescription("OK [ email sent from: " + fro + " to: " + to + "]");

            logEntry.setUserId(from.getId());
            logEntry.setEventType(SystemConstants.LOG_EVENT_TYPE_SEND_EMAIL);
            logEntry.setSourceId(from.getId()); // unknown
            logEntry.setSourceType(SystemConstants.TARGET_TYPE_USER);

            logEntry.setTimestamp(new java.util.Date(System.currentTimeMillis()));
            SqlSessionFactory sqlSessionFactory = MyBatisConnectionFactory.getSqlSessionFactory();
            SqlSession sesh = sqlSessionFactory.openSession(true);

            sesh.insert("io.starter.dao.SyslogMapper.insert", logEntry);
            sesh.commit();
            if (ltc != null)
                ltc.countDown(); // release the latch
        }
    }).start();

}