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:net.ymate.module.mailsender.MailSendServerCfgMeta.java

public Session createIfNeed() {
    if (__mailSession == null) {
        synchronized (this) {
            if (__mailSession == null) {
                Properties _props = new Properties();
                _props.put("mail.smtp.host", smtpHost);
                _props.put("mail.smtp.auth", needAuth);
                _props.put("mail.transport.protocol", "smtp");
                if (tlsEnabled) {
                    _props.put("mail.smtp.starttls.enable", true);
                    _props.put("mail.smtp.socketFactory.port", smtpPort);
                    _props.put("mail.smtp.socketFactory.class", StringUtils
                            .defaultIfBlank(socketFactoryClassName, "javax.net.ssl.SSLSocketFactory"));
                    _props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
                } else {
                    _props.put("mail.smtp.port", smtpPort);
                }//from   w  w  w  .j ava 2  s.  co  m
                //
                __mailSession = Session.getInstance(_props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(smtpUsername, smtpPassword);
                    }
                });
                __mailSession.setDebug(debugEnabled);
            }
        }
    }
    return __mailSession;
}

From source file:org.restcomm.connect.email.EmailService.java

public EmailService(final Configuration config) {
    this.observers = new ArrayList<ActorRef>();
    configuration = config;/*from   w w  w.j a v a 2  s .  c  o  m*/
    this.host = configuration.getString("host");
    this.port = configuration.getString("port");
    this.user = configuration.getString("user");
    this.password = configuration.getString("password");
    if ((user != null && !user.isEmpty()) || (password != null && !password.isEmpty())
            || (port != null && !port.isEmpty()) || (host != null && !host.isEmpty())) {
        //allow smtp over ssl if port is set to 465
        if ("465".equals(port)) {
            this.isSslEnabled = true;
            useSSLSmtp();
        } else {
            //TLS uses port 587
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.user", user);
            properties.setProperty("mail.smtp.password", password);
            properties.setProperty("mail.smtp.port", port);
        }
        properties.setProperty("mail.smtp.starttls.enable", "true");
        properties.setProperty("mail.transport.protocol", "smtps");
        // properties.setProperty("mail.smtp.ssl.enable", "true");
        properties.setProperty("mail.smtp.auth", "true");
        session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });
    }
}

From source file:rapture.mail.Mailer.java

public static Session getSession(final SMTPConfig config) {
    // Create some properties and get the default Session.
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", config.isAuthentication());
    props.put("mail.smtp.starttls.enable", config.isTlsenable());
    props.put("mail.smtp.starttls.required", config.isTlsrequired());
    props.put("mail.smtp.host", config.getHost());
    props.put("mail.smtp.port", config.getPort());
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override/*from  www .  java 2s.  co  m*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(config.getUsername(), config.getPassword());
        }
    });
    return session;
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

public void send() throws AxisFault {

    try {/*  w w w  . j  av  a  2  s.c om*/

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.openmrs.module.sync.SyncMailUtil.java

public static Session createSession(Map<String, String> settings) {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", settings.get(MAIL_TRANSPORT_PROTOCOL));
    props.setProperty("mail.smtp.host", settings.get(MAIL_SMTP_HOST));
    props.setProperty("mail.smtp.port", settings.get(MAIL_SMTP_PORT));
    props.setProperty("mail.smtp.auth", settings.get(MAIL_SMTP_AUTH));
    props.setProperty("mail.smtp.starttls.enable", settings.get(MAIL_SMTP_STARTTLS_ENABLE));
    props.setProperty("mail.from", settings.get(MAIL_FROM));
    props.setProperty("mail.debug", settings.get(MAIL_DEBUG));

    final String mailUser = settings.get(MAIL_USER);
    final String mailPw = settings.get(MAIL_PASSWORD);

    Authenticator auth = new Authenticator() {
        @Override/*ww  w .  j a  v a 2  s  .c om*/
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUser, mailPw);
        }
    };
    return Session.getInstance(props, auth);
}

From source file:com.ayu.filter.RegularService.java

@Async
public void sendSSLMail(String text, String toMail) {

    final String username = "clouddefenceids";
    final String password = "";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }// ww  w . j a v  a 2 s. co m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
        message.setSubject("Forgot Password");
        message.setText(text);

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.axis2.transport.mail.server.SMTPWorker.java

private String processInput(String input) {
    if (input == null) {
        return Constants.COMMAND_UNKNOWN;
    }//  w w  w  .j  a va  2 s . co  m

    if ((mail != null) && transmitionEnd) {
        return Constants.COMMAND_TRANSMISSION_END;
    }

    if (input.startsWith("MAIL")) {
        mail = new MimeMessage(Session.getInstance(new Properties(), new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return null;
            }
        }));

        int start = input.indexOf("<") + 1;
        int end;

        if (start <= 0) {
            start = input.indexOf("FROM:") + 5;
            end = input.length();
        } else {
            end = input.indexOf(">");
        }

        String from = input.substring(start, end);

        if ((from != null) && from.trim().length() != 0) {

            // TODO this is an ugly hack to get the from address in. There
            // should be a better way to do this.
            MailAddress mailFrom[] = new MailAddress[1];

            mailFrom[0] = new MailAddress(from);

            try {
                mail.addFrom(mailFrom);
            } catch (MessagingException e) {
                log.info(e.getMessage());
            }
        }

        return Constants.MAIL_OK;
    }

    if (input.startsWith("HELO")) {
        return Constants.HELO_REPLY;
    } else if (input.startsWith("RCPT")) {

        int start = input.indexOf("<") + 1;
        int end;

        if (start <= 0) {
            start = input.indexOf("TO:") + 3;
            /*
             * if(!input.endsWith(domain)){ System.out.println("ERROR: wrong
             * donmain name"); return Constants.RCPT_ERROR; }
             */
        } else {

            /*
             * if(!input.endsWith(domain + ">")){ System.out.println("ERROR:
             * wrong donmain name"); return Constants.RCPT_ERROR; }
             */
        }

        end = input.indexOf(">");

        String toStr = input.substring(start, end);

        try {
            mail.addRecipient(Message.RecipientType.TO, new MailAddress(toStr));
            receivers.add(toStr);
        } catch (MessagingException e) {
            log.info(e.getMessage());
        }

        return Constants.RCPT_OK;
    } else if (input.equalsIgnoreCase("DATA")) {
        dataWriting = true;

        return Constants.DATA_START_SUCCESS;
    } else if (input.equalsIgnoreCase("QUIT")) {
        dataWriting = true;
        transmitionEnd = true;

        return Constants.COMMAND_TRANSMISSION_END;
    } else if (input.equals(".")) {
        dataWriting = false;

        return Constants.DATA_END_SUCCESS;
    } else if (input.length() == 0 && !bodyData) {
        bodyData = true;

        return null;
    } else if ((mail != null) && dataWriting) {
        try {
            if (bodyData) {
                temp += input;
                mail.setContent(temp, "text/xml"); //Since this is for axis2 :-)
            } else {
                mail.addHeaderLine(input);
            }
        } catch (MessagingException e) {
            log.info(e.getMessage());
        }

        return null;
    } else {
        return Constants.COMMAND_UNKNOWN;
    }
}

From source file:org.wso2.carbon.registry.eventing.MimeEmailMessageHandler.java

/**
 *
 * @param configContext ConfigurationContext
 * @param message Mail body//w  w  w. j  a v  a  2 s. c  o m
 * @param subject Mail Subject
 * @param toAddress email to address
 * @throws RegistryException Registry exception
 */
public void sendMimeMessage(ConfigurationContext configContext, String message, String subject,
        String toAddress) throws RegistryException {
    Properties props = new Properties();
    if (configContext != null && configContext.getAxisConfiguration().getTransportOut("mailto") != null) {
        List<Parameter> params = configContext.getAxisConfiguration().getTransportOut("mailto").getParameters();
        for (Parameter parm : params) {
            props.put(parm.getName(), parm.getValue());
        }
    }
    if (threadPoolExecutor == null) {
        threadPoolExecutor = new ThreadPoolExecutor(MIN_THREAD, MAX_THREAD, DEFAULT_KEEP_ALIVE_TIME,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1000));
    }
    String smtpFrom = props.getProperty(MailConstants.MAIL_SMTP_FROM);

    try {
        smtpFromAddress = new InternetAddress(smtpFrom);
    } catch (AddressException e) {
        log.error("Error in retrieving smtp address");
        throw new RegistryException("Error in transforming smtp address");
    }
    final String smtpUsername = props.getProperty(MailConstants.MAIL_SMTP_USERNAME);
    final String smtpPassword = props.getProperty(MailConstants.MAIL_SMTP_PASSWORD);
    if (smtpUsername != null && smtpPassword != null) {
        MimeEmailMessageHandler.session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        MimeEmailMessageHandler.session = Session.getInstance(props);
    }
    threadPoolExecutor.submit(new EmailSender(toAddress, subject, message.toString(), "text/html"));
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

private Session getSession() {
    Authenticator authenticator = new Authenticator();

    Properties sessionProps = new Properties();
    sessionProps.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
    sessionProps.setProperty("mail.smtp.auth", "true");
    sessionProps.put("mail.smtp.starttls.enable", "true");
    sessionProps.setProperty("mail.smtp.host", properties.getProperty("smtp.host"));
    sessionProps.setProperty("mail.smtp.port", properties.getProperty("smtp.port"));

    return Session.getInstance(sessionProps, authenticator);
}

From source file:com.krawler.notify.email.SimpleEmailSender.java

public synchronized Session createSession(EmailNotification notification) {
    Properties props = new Properties(defaults);
    Map<String, Object> customProps = notification.getCustomSetting();
    if (customProps != null) {
        props.putAll(customProps);//from www. j  a va2s  .  c  o m
    }

    return Session.getInstance(props, getAuthenticator(notification.getPasswordAuthentication()));
}