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:nl.nn.adapterframework.senders.MailSender.java

protected Session getSession() {
    if (session == null) {
        session = Session.getInstance(properties, null);
        session.setDebug(log.isDebugEnabled());
        //         log.debug("MailSender [" + getName() + "] got session to [" + properties + "]");
    }//from   w  w  w  . ja v  a2  s .c  o m
    return session;
}

From source file:org.snopoke.util.Emailer.java

/**
 * Create the mail session with authentication and properties for SSL/TLS
 * etc.//from ww w.  j  av a 2  s .com
 * 
 * @return configured mail session
 */
private Session getSession() {

    Properties properties = new Properties();

    Authenticator authenticator = new Authenticator();
    if (username != null && password != null) {
        properties.put("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
        properties.put("mail.smtp.auth", "true");
    }

    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.socketFactory.port", port);
    properties.put("mail.smtp.socketFactory.fallback", "false");
    if (useSSL)
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    if (useTLS)
        properties.put("mail.smtp.starttls.enable", "true");

    if (debug) {
        properties.put("mail.smtp.ssl.checkserveridentity", "false");
        properties.put("mail.smtp.ssl.trust", "*");
        properties.put("mail.debug", "true");
    }

    return Session.getInstance(properties, authenticator);
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * ????//from  w w w. j ava 2s . c o m
 *
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
public void execute() throws UnsupportedEncodingException, MessagingException {
    final Session session = useDefaultSession
            ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator())
            : Session.getInstance(properties.getProperties(), properties.getAuthenticator());
    session.setDebug(isDebug);

    final MimeMessage message = new MimeMessage(session);

    message.setFrom(fromAddress.toInternetAddress(charset));
    message.setReplyTo(toInternetAddresses(replyToAddressList));
    message.addRecipients(Message.RecipientType.TO, toInternetAddresses(toAddressList));
    message.addRecipients(Message.RecipientType.CC, toInternetAddresses(ccAddressList));
    message.addRecipients(Message.RecipientType.BCC, toInternetAddresses(bccAddressList));
    message.setSubject(subject, charset);

    setContent(message);

    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

/**
 * Create some properties and get the default Session
 *//*from   ww  w  . j av  a2s .c o  m*/
private Session getMailSession() {

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", smtpPort + "");

    if (needsAuth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    // create some properties and get the default Session
    Session session = Session.getInstance(props, null);
    if (logger.isDebugEnabled()) {
        session.setDebug(true);
    } else {
        session.setDebug(false);
    }

    return session;
}

From source file:bioLockJ.module.agent.MailAgent.java

private Session getSession() {
    final Properties props = new Properties();
    props.put(EMAIL_SMTP_AUTH, emailSmtpAuth);
    props.put(EMAIL_START_TLS_ENABLE, emailTls);
    props.put(EMAIL_HOST, emailHost);/* ww w. j  a v  a2 s.  c o m*/
    props.put(EMAIL_PORT, emailPort);

    final Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailFrom, decrypt(emailEncryptedPassword));
        }
    });

    return session;
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }//  www  .  ja  v  a2  s.c o m

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

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

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

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

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;/*from ww w  .j a  v  a2 s. c  o m*/
    String contentType;
    String fileExtension;
    IDataStore emailDispatchDataStore;
    String nameSuffix;
    String descriptionSuffix;
    String containedFileName;
    String zipFileName;
    boolean reportNameInSubject;

    logger.debug("IN");
    try {
        parametersMap = dispatchContext.getParametersMap();
        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
        nameSuffix = dispatchContext.getNameSuffix();
        descriptionSuffix = dispatchContext.getDescriptionSuffix();
        containedFileName = dispatchContext.getContainedFileName() != null
                && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName()
                        : document.getName();
        zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("")
                ? dispatchContext.getZipMailName()
                : document.getName();
        reportNameInSubject = dispatchContext.isReportNameInSubject();

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        int smptPort = 25;

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

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = dispatchContext.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = dispatchContext.getMailTxt();

        String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return false;
        }

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

        // open session
        Session session = null;

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

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

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

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

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

        String subject = mailSubj;

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

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + descriptionSuffix);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = null;
        //if zip requested
        if (dispatchContext.isZipMailDocument()) {
            mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
        }
        //else 
        else {
            sds = new SchedulerDataSource(executionOutput, contentType,
                    containedFileName + nameSuffix + fileExtension);
            mbp2.setDataHandler(new DataHandler(sds));
            mbp2.setFileName(sds.getName());
        }

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

From source file:io.mapzone.arena.share.app.EMailSharelet.java

private Session mailSession() throws Exception {
    if (session == null) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "192.168.122.183"); //ArenaConfigMBean.SMTP_HOST );
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.auth", "true");
        // TODO uncomment if the mail server contains a correct SSL certificate
        // props.put( "mail.smtp.starttls.enable", "true" ); // enable STARTTLS

        // create Authenticator object to pass in Session.getInstance argument
        Authenticator auth = new Authenticator() {
            @Override/*from   w  w w  .ja v a  2 s.com*/
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("support@mapzone.io", "690332"); // FIXME !!!
            }
        };
        session = Session.getInstance(props, auth);
    }
    return session;
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private Session openMailSession(MailStoreConfiguration config, Authenticator auth) {

    // Assertions.
    if (config == null) {
        String msg = "Argument 'config' cannot be null";
        throw new IllegalArgumentException(msg);
    }/*w  w  w.  j  a  v  a2s.  c o  m*/
    if (auth == null) {
        String msg = "Argument 'auth' cannot be null";
        throw new IllegalArgumentException(msg);
    }

    // Initialize connection properties
    Properties mailProperties = new Properties();
    mailProperties.put("mail.store.protocol", config.getProtocol());
    mailProperties.put("mail.host", config.getHost());
    mailProperties.put("mail.port", config.getPort());
    mailProperties.put("mail.debug", debug ? "true" : "false");

    String protocolPropertyPrefix = "mail." + config.getProtocol() + ".";

    // Set connection timeout property
    int connectionTimeout = config.getConnectionTimeout();
    if (connectionTimeout >= 0) {
        mailProperties.put(protocolPropertyPrefix + "connectiontimeout", connectionTimeout);
    }

    // Set timeout property
    int timeout = config.getTimeout();
    if (timeout >= 0) {
        mailProperties.put(protocolPropertyPrefix + "timeout", timeout);
    }

    // add each additional property
    for (Map.Entry<String, String> property : config.getJavaMailProperties().entrySet()) {
        mailProperties.put(property.getKey(), property.getValue());
    }

    // Connect/authenticate to the configured store
    return Session.getInstance(mailProperties, auth);

}

From source file:org.apache.hupa.server.InMemoryIMAPStoreCache.java

private Session createSession(final User user) {
    Properties props = new Properties();
    Settings settings = user.getSettings();

    props.setProperty("mail.mime.decodetext.strict", "false");
    if (settings.getImapSecure()) {
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.connectionpoolsize", connectionPoolSize + "");
        props.setProperty("mail.imaps.connectionpooltimeout", timeout + "");
        if (trustSSL) {
            props.setProperty("mail.imaps.ssl.trust", settings.getImapServer());
        }/*ww w  .  j  a  va2  s  .c  o m*/
    } else {
        props.setProperty("mail.imap.connectionpoolsize", connectionPoolSize + "");
        props.setProperty("mail.imap.connectionpooltimeout", timeout + "");
    }

    if (settings.getSmtpSecure()) {
        if (settings.getSmtpPort() == 587) {
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.transport.protocol.rfc822", "smtp");
        } else {
            props.setProperty("mail.transport.protocol.rfc822", "smtps");
            props.setProperty("mail.smtps.ssl.enable", "true");
            if (trustSSL) {
                props.setProperty("mail.smtps.ssl.trust", settings.getSmtpServer());
            }
        }
    } else {
        props.setProperty("mail.transport.protocol.rfc822", "smtp");
    }

    props.setProperty("mail.smtp.host", settings.getSmtpServer());
    props.setProperty("mail.smtps.host", settings.getSmtpServer());
    props.setProperty("mail.smtp.port", settings.getSmtpPort() + "");
    props.setProperty("mail.smtps.port", settings.getSmtpPort() + "");

    Authenticator auth = null;
    if (settings.getSmtpAuth() && user.getPassword() != null && user.getName() != null) {
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtps.auth", "true");
        auth = new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userId = user.getId();
                StackTraceElement[] sElms = Thread.currentThread().getStackTrace();
                for (StackTraceElement e : sElms) {
                    if (e.getClassName().equals(InMemoryIMAPStoreCache.class.getName())
                            && e.getMethodName().equals("get")) {
                        // We try with the id part the second time (unix imap/smtp auth compatible)
                        if (userId.matches(".*@.*")) {
                            userId = userId.replaceFirst("@.*", "");
                            user.setId(userId);
                            break;
                        } else {
                            return null;
                        }
                    }
                }
                return new PasswordAuthentication(userId, user.getPassword());
            }
        };
    }

    Session ses = Session.getInstance(props, auth);
    ses.setDebug(debug && logger.isDebugEnabled());
    logger.debug("Created session " + user.getName() + "\n" + settings + "\n"
            + props.toString().replaceAll(",", ",\n "));
    return ses;
}