Example usage for javax.mail PasswordAuthentication PasswordAuthentication

List of usage examples for javax.mail PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, String password) 

Source Link

Document

Initialize a new PasswordAuthentication

Usage

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param host/* w w w  .ja v a  2 s .  c om*/
 * @param port
 * @param alias
 * @param keypass
 * @return
 */
private Session createSession(String host, String port, final String alias, final String keypass) {

    Properties props = setProperties(host, port);

    /*
     * Authenticator & Session
     */
    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(alias, keypass);
        }
    });

    return session;

}

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

private Authenticator getAuthenticator(final PasswordAuthentication authInfo) {
    if (authInfo != null)
        return new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return authInfo;
            }//w w  w  .j  a va  2  s. c o m
        };

    if (loginName != null && loginName.length() > 0 && password != null && password.length() > 0) {
        return new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(loginName, password);
            }
        };
    }

    return null;
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }/* w  w w . j av  a2 s.com*/
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:org.nuxeo.ecm.automation.core.mail.Mailer.java

/**
 * Set SMTP credential//from w w w  .  j a v a 2 s. co  m
 *
 * @param user
 * @param pass
 */
public void setCredentials(final String user, final String pass) {
    config.setProperty("mail.smtp.auth", "true");
    auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, pass);
        }
    };
    session = null;
}

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

/**
 * Initialize the Mail sender and be ready to send messages
 * @param cfgCtx the axis2 configuration context
 * @param transportOut the transport-out description
 * @throws org.apache.axis2.AxisFault on error
 *///from  w w  w  . j a va  2 s .  co m
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    super.init(cfgCtx, transportOut);

    // initialize SMTP session
    Properties props = new Properties();
    List<Parameter> params = transportOut.getParameters();
    for (Parameter p : params) {
        props.put(p.getName(), p.getValue());
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_FROM)) {
        try {
            smtpFromAddress = new InternetAddress((String) props.get(MailConstants.MAIL_SMTP_FROM));
        } catch (AddressException e) {
            handleException("Invalid default 'From' address : " + props.get(MailConstants.MAIL_SMTP_FROM), e);
        }
    }

    if (props.containsKey(MailConstants.MAIL_SMTP_BCC)) {
        try {
            smtpBccAddresses = InternetAddress.parse((String) props.get(MailConstants.MAIL_SMTP_BCC));
        } catch (AddressException e) {
            handleException("Invalid default 'Bcc' address : " + props.get(MailConstants.MAIL_SMTP_BCC), e);
        }
    }

    if (props.containsKey(MailConstants.TRANSPORT_MAIL_FORMAT)) {
        defaultMailFormat = (String) props.get(MailConstants.TRANSPORT_MAIL_FORMAT);
    }

    smtpUsername = (String) props.get(MailConstants.MAIL_SMTP_USERNAME);
    smtpPassword = (String) props.get(MailConstants.MAIL_SMTP_PASSWORD);

    if (smtpUsername != null && smtpPassword != null) {
        session = Session.getInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
            }
        });
    } else {
        session = Session.getInstance(props, null);
    }

    MailUtils.setupLogging(session, log, transportOut);

    // set the synchronise callback table
    if (cfgCtx.getProperty(BaseConstants.CALLBACK_TABLE) == null) {
        cfgCtx.setProperty(BaseConstants.CALLBACK_TABLE, new ConcurrentHashMap());
    }
}

From source file:org.libreplan.importers.notifications.ComposeMessage.java

public boolean composeMessageForUser(EmailNotification notification) {
    // Gather data about EmailTemplate needs to be used
    Resource resource = notification.getResource();
    EmailTemplateEnum type = notification.getType();
    Locale locale;//from w ww .ja  v  a  2s.  c o  m
    Worker currentWorker = getCurrentWorker(resource.getId());

    UserRole currentUserRole = getCurrentUserRole(notification.getType());

    if (currentWorker != null && currentWorker.getUser().isInRole(currentUserRole)) {
        if (currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE)) {
            locale = new Locale(System.getProperty("user.language"));
        } else {
            locale = new Locale(currentWorker.getUser().getApplicationLanguage().getLocale().getLanguage());
        }

        EmailTemplate currentEmailTemplate = findCurrentEmailTemplate(type, locale);

        if (currentEmailTemplate == null) {
            LOG.error("Email template is null");
            return false;
        }

        // Modify text that will be composed
        String text = currentEmailTemplate.getContent();
        text = replaceKeywords(text, currentWorker, notification);

        String receiver = currentWorker.getUser().getEmail();

        setupConnectionProperties();

        final String username = usrnme;
        final String password = psswrd;

        // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
        Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Send message
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

            String subject = currentEmailTemplate.getSubject();
            message.setSubject(subject);

            message.setText(text);

            Transport.send(message);

            return true;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            if (receiver == null) {
                Messagebox.show(
                        _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
                        _("Error"), Messagebox.OK, Messagebox.ERROR);
            }
        }
    }
    return false;
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 * session is created only once//from ww w. jav a2 s .co  m
 *
 * @return
 */
private Session createSession() {

    if (session != null && false) {
        return session;
    }
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.mail.yahoo.com");
    props.put("mail.stmp.user", USERNAME);
    //To use TLS
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.password", PASSWORD);
    session = Session.getDefaultInstance(props, new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USERNAME, PASSWORD);
        }
    });
    return session;
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    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(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*from  w  w w.j  a v a2s  . co  m*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

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

From source file:SimpleAuthenticator.java

protected PasswordAuthentication getPasswordAuthentication() {

    // given a prompt?
    String prompt = getRequestingPrompt();
    if (prompt == null)
        prompt = "Please login...";

    // protocol//from   w w w .j  a v a2s.co  m
    String protocol = getRequestingProtocol();
    if (protocol == null)
        protocol = "Unknown protocol";

    // get the host
    String host = null;
    InetAddress inet = getRequestingSite();
    if (inet != null)
        host = inet.getHostName();
    if (host == null)
        host = "Unknown host";

    // port
    String port = "";
    int portnum = getRequestingPort();
    if (portnum != -1)
        port = ", port " + portnum + " ";

    // Build the info string
    String info = "Connecting to " + protocol + " mail service on host " + host + port;

    //JPanel d = new JPanel();
    // XXX - for some reason using a JPanel here causes JOptionPane
    // to display incorrectly, so we workaround the problem using
    // an anonymous JComponent.
    JComponent d = new JComponent() {
    };

    GridBagLayout gb = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    d.setLayout(gb);
    c.insets = new Insets(2, 2, 2, 2);

    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 0.0;
    d.add(constrain(new JLabel(info), gb, c));
    d.add(constrain(new JLabel(prompt), gb, c));

    c.gridwidth = 1;
    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.0;
    d.add(constrain(new JLabel("Username:"), gb, c));

    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    String user = getDefaultUserName();
    JTextField username = new JTextField(user, 20);
    d.add(constrain(username, gb, c));

    c.gridwidth = 1;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.EAST;
    c.weightx = 0.0;
    d.add(constrain(new JLabel("Password:"), gb, c));

    c.anchor = GridBagConstraints.EAST;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = GridBagConstraints.REMAINDER;
    c.weightx = 1.0;
    JPasswordField password = new JPasswordField("", 20);
    d.add(constrain(password, gb, c));
    // XXX - following doesn't work
    if (user != null && user.length() > 0)
        password.requestFocus();
    else
        username.requestFocus();

    int result = JOptionPane.showConfirmDialog(frame, d, "Login", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (result == JOptionPane.OK_OPTION)
        return new PasswordAuthentication(username.getText(), password.getText());
    else
        return null;
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

@Override
protected void onStart() throws InterruptedException {
    freemarkerConfig = new Configuration();
    freemarkerConfig.setTemplateLoader(new SmartTemplateLoader(baseDirectory));
    freemarkerConfig.setDefaultEncoding("UTF-8");
    freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    freemarkerConfig.setIncompatibleImprovements(new Version(2, 3, 20));

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", mailHost);
    properties.setProperty("mail.smtp.port", Integer.toString(port));
    properties.setProperty("mail.smtp.auth", authenticated.toString());
    properties.setProperty("mail.smtp.starttls.enable", useStartTLS.toString());

    if (authenticated) {
        mailSession = Session.getInstance(properties, new Authenticator() {
            @Override//from ww w.j a  v  a  2  s.c om
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        mailSession = Session.getInstance(properties);
    }
}