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:mupomat.view.PodrskaLozinka.java

private void posaljiEmail() {

    final String username = "mupomat@gmail.com";
    final String password = "lesnibokysr187";

    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() {
        @Override/*from w  w  w.ja v a2 s .  c  om*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("mupomat@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(txtEmail.getText().trim()));
        message.setSubject("MUPomat podrka");

        message.setText("Nova lozinka: " + generiranaLozinka
                + "\nMolimo Vas da nakon prijave promjenite lozinku radi sigurnosti.\nHvala.");

        Transport.send(message);
        this.dispose();
        JOptionPane.showMessageDialog(rootPane, "Lozinka je uspjeno poslana na Vau e-mail adresu!",
                "MUPomat: Podrka", JOptionPane.INFORMATION_MESSAGE);

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

}

From source file:com.mylab.mail.OpenCmsMailService.java

private Session getSession() {
    final CmsMailHost host = OpenCms.getSystemInfo().getMailSettings().getDefaultMailHost();
    Properties props = new Properties();
    props.put("mail.transport.protocol", host.getProtocol());
    props.put("mail.smtp.host", host.getHostname());
    props.put("mail.smtp.auth", host.isAuthenticating());

    Authenticator authenticator = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(host.getUsername(), host.getPassword());
        }/*from  w  w w .  j a va  2s  .  c  om*/
    };

    return Session.getInstance(props, authenticator);
}

From source file:com.project.implementation.ReservationImplementation.java

public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date,
        Date checkout_date) {/*w w  w  .  j  av a 2 s .  c  om*/
    Integer guestID = 0, guestCount;
    String room_selected = guestDTO.getRoom_no_selected();
    Guest guestObject = new Guest();

    try {
        org.apache.commons.beanutils.BeanUtils.copyProperties(guestObject, guestDTO);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    //check email id if exist
    guestID = guestDAO.checkGuestExist(guestDTO.getGuest_email(), guestDTO.getLicense_no());
    System.out.println("guestID: " + guestID);
    //if email id, license exist
    if (!(guestID == 0)) {
        System.out.println("value = ");
        //update details
        guestCount = guestDAO.updateUserDetails(guestID, guestDTO.getGuest_name(), guestDTO.getStreet(),
                guestDTO.getCity(), guestDTO.getState(), guestDTO.getZip());
        if (guestCount != 0)
            guestObject = guestDAO.getGuestRecord(guestID);
    } else {
        guestObject = guestDAO.save(guestObject);
    }

    String randomDate = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis());

    UUID id = UUID.randomUUID();
    String token_no = String.valueOf(id);
    //System.out.println(sensor_id);

    // String token_no = guestObject.getLicense_no() + guestObject.getGuest_id()+randomDate;

    java.util.Date todayUtilDate = Calendar.getInstance().getTime();//2015-12-05
    java.sql.Date todaySqlDate = new java.sql.Date(todayUtilDate.getTime());

    Reservation reservationObject = new Reservation();
    //        reservationObject.setReservation_id(0);
    reservationObject.setGuest_id(guestObject.getGuest_id());
    reservationObject.setReservation_token(token_no);
    reservationObject.setReservation_date(todaySqlDate);
    reservationObject.setReservation_status(ReservationStatus.R);
    reservationObject = reservationDAO.save(reservationObject);
    // Integer reservation_id = reservationObject.getReservation_id();

    String[] resultStringArray = guestDTO.getRoom_no_selected().split(",");
    ArrayList<Integer> arrRooms = new ArrayList<Integer>();
    for (String str : resultStringArray) {
        arrRooms.add(Integer.parseInt(str));
        CheckinRoomMapping checkinRoomMappingObject = new CheckinRoomMapping();
        checkinRoomMappingObject.setReservation(reservationObject);
        checkinRoomMappingObject.setRoom_no(Integer.parseInt(str));
        checkinRoomMappingObject.setCheckin_date(checkin_date);
        checkinRoomMappingObject.setCheckout_date(checkout_date);
        checkinRoomMappingObject.setGuest_count(0);
        checkinRoomMappingObject.setMappingId(0);
        checkinRoomMappingDAO.save(checkinRoomMappingObject);
    }
    //add email code start here

    final String from = "express.minihotel@gmail.com";
    String to = guestObject.getGuest_email();
    String body = "Hello " + guestObject.getGuest_name()
            + ", <br/><br></br>Your reservation has been confirmed.Your reservation ID is <font color='red'><b>"
            + token_no
            + "</b></font>.</br>Please bring the Driving License for verification at the time of Check In.</br><br></br>"
            + "<b>Note:</b>If you want to cancel the reservation, "
            + "please <a href=\'http://52.53.255.195:8080/CmpE275Team07Fall2015TermProject/v1/cancelReservation?reservation_token="
            + token_no + "\'>Click Here</a><br></br>--<i>Express Hotel</i>";
    String subject = "Express Hotel Reservation Confirmation <" + token_no + ">";

    final String password = "Minihotel@2015";
    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(from, password);
        }
    });
    try {
        MimeMessage email = new MimeMessage(session);
        email.setFrom(new InternetAddress(from));
        email.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
        email.setSubject(subject);
        email.setContent(body, "text/html");
        Transport.send(email);

    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //email code end here

    return token_no;
}

From source file:webreader.WebReader.java

private void sendEmail(String inputMessage) {
    //---User login information
    final String username = email;
    final String password = emailPassword;

    //---Sets server for gmail
    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");

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

        }//w w  w. java 2s . c om

    });
    //---Try catch loop for sending an email
    //---Sends error email to the sender if catch is engaged.
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject("Your grades have been updated");
        message.setText(inputMessage);
        Transport.send(message);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        emailSent = "E-mail was sent: " + dateFormat.format(date);
        System.out.println(emailSent);
    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //---Used code from https://www.youtube.com/watch?v=sHC8YgW21ho
    //---for the above method
}

From source file:de.micromata.genome.util.runtime.config.MailSessionLocalSettingsConfigModel.java

public Session createMailSession(Properties addProperties) {
    Properties msprops = new Properties();

    msprops.put("mail.debug", Boolean.toString(smptDebug));
    msprops.put("mail.smtp.host", this.emailHost);
    msprops.put("mail.smtp.port", this.emailPort);
    //    msprops.put("mail.smtp.ssl.enable", "true");
    //msprops.put("mail.smtp.starttls.enable", "true");
    Encryption encr = Encryption.fromString(encryption);
    if (encr == Encryption.StartTLS) {
        msprops.put("mail.smtp.starttls.enable", "true");
    } else if (encr == Encryption.SSL) {
        msprops.put("mail.smtp.ssl.enable", "true");
        //      msprops.put("mail.smtp.socketFactory.port", emailPort);
        //      msprops.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }/* w  w  w.j  ava  2s. c om*/
    javax.mail.Session mailSession;
    msprops.put("mail.smtp.auth", Boolean.toString(isEmailAuthEnabled()));

    if (addProperties != null) {
        msprops.putAll(addProperties);
    }

    if (isEmailAuthEnabled() == true) {
        mailSession = Session.getInstance(msprops, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailAuthUser, emailAuthPass);
            }
        });
    } else {
        mailSession = Session.getInstance(msprops);
    }
    return mailSession;
}

From source file:org.entermedia.email.PostMail.java

public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject,
        String inHtml, String inText, String from, List inAttachments, Map inProperties)
        throws MessagingException {
    // Set the host smtp address
    Properties props = new Properties();
    // create some properties and get the default Session
    props.put("mail.smtp.host", fieldSmtpServer);
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString());
    if (isSslEnabled()) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }//from  w w  w . j av a  2 s  . co  m
    Session session = null;
    if (isEnableTls()) {
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword());
            }
        });
    } else if (fieldSmtpSecured) {
        SmtpAuthenticator auth = new SmtpAuthenticator();
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }
    // session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);
    MimeMultipart mp = null;
    // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message,
    // "text/html")));

    if (inAttachments != null && inAttachments.size() == 0) {
        inAttachments = null;
    }

    if (inText != null && inHtml != null || inAttachments != null) {
        // Create an "Alternative" Multipart message
        mp = new MimeMultipart("mixed");

        if (inText != null) {
            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(inText, "text/plain");
            mp.addBodyPart(messageBodyPart);
        }
        if (inHtml != null) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(inHtml, "text/html");
            mp.addBodyPart(messageBodyPart);
        }
        if (inAttachments != null) {
            for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) {
                String filename = (String) iterator.next();

                File file = new File(filename);

                if (file.exists() && !file.isDirectory()) {
                    // create the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));

                    mbp.setFileName(fds.getName());

                    mp.addBodyPart(mbp);
                }
            }
        }

        msg.setContent(mp);

    } else if (inHtml != null) {
        msg.setContent(inHtml, "text/html");
    } else {
        msg.setContent(inText, "text/plain");
    }
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    //msg.setRecipient(RecipientType.BCC, addressFrom);
    msg.setSentDate(new Date());
    if (recipients == null || recipients.isEmpty()) {
        throw new MessagingException("No recipients specified");
    }
    InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]);

    msg.setRecipients(Message.RecipientType.TO, addressTo);

    //add bcc
    if (blindrecipients != null && !blindrecipients.isEmpty()) {
        InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]);
        msg.setRecipients(Message.RecipientType.BCC, addressBcc);
    }

    // Optional : You can also set your custom headers in the Email if you
    // Want
    // msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);

    // Transport tr = session.getTransport("smtp");
    // tr.connect(serverandport[0], null, null);
    // msg.saveChanges(); // don't forget this
    // tr.sendMessage(msg, msg.getAllRecipients());
    // tr.close();
    // msg.setContent(msg, "text/plain");

    Transport.send(msg);
    log.info("sent email " + subject);
}

From source file:com.smartitengineering.emailq.binder.guice.EmailModule.java

private void configureJavaMailSession() {
    Properties properties = new Properties();
    properties.setProperty(JAVAMAIL_SMTP_HOST, smtpHost);
    properties.setProperty(JAVAMAIL_SMTP_PORT, String.valueOf(smtpPort));
    if (sslEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_CLASS,
                JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_CLASS_VAL);
        properties.setProperty(JAVAMAIL_SMTP_SSL_SOCKET_FACTORY_PORT, String.valueOf(smtpPort));
    } else if (tlsEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_TLS, String.valueOf(tlsEnabled));
    }/* ww  w. j  a  v a  2 s  .  co  m*/
    if (authEnabled) {
        properties.setProperty(JAVAMAIL_SMTP_USER, smtpUser);
        properties.setProperty(JAVAMAIL_SMTP_AUTH, String.valueOf(authEnabled));
        bind(Session.class).toInstance(Session.getInstance(properties, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUser, smtpPassword);
            }
        }));
    } else {
        bind(Session.class).toInstance(Session.getInstance(properties));
    }
}

From source file:com.waveerp.sendMail.java

public void sendMsgTLS(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }//  ww  w.j  av a 2 s . c o  m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

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

    log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass);

    //Email email = new SimpleEmail();
    //email.setHostName(strHost);
    //email.setSmtpPort( Integer.parseInt(strPort) );
    //email.setAuthenticator(new DefaultAuthenticator(strUser, strPass01));
    //email.setTLS(true);
    //email.setFrom(strSource, strSourceDesc);
    //email.setSubject(strSubject);
    //email.setMsg(strMsg);

    //email.addTo(strDestination, strDestDesc);
    //email.send();

}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

/**
 * Se encarga de enviar el mensaje de correo electronico *
 *//*  w  w  w  .ja va2s.  com*/
public static Boolean sendEmail(final EmailMessage emdto) throws BusinessException {
    try {
        Session session;
        Properties properties = System.getProperties();
        properties.put("mail.host", emdto.getHost());
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.port", emdto.getPort());
        properties.put("mail.smtp.starttls.enable", emdto.getStarttls());
        if (emdto.getUser() != null && emdto.getPassword() != null) {
            properties.put("mail.smtp.auth", "true");
            session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emdto.getUser(), emdto.getPassword());
                }
            });
        } else {
            properties.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(properties);
        }

        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emdto.getFrom(), emdto.getMask()));
        message.setSubject(emdto.getSubject());

        for (String to : emdto.getToList()) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        }
        if (emdto.getCcList() != null) {
            for (String cc : emdto.getCcList()) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }
        if (emdto.getCcoList() != null) {
            for (String cco : emdto.getCcoList()) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(cco));
            }
        }

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(emdto.getBodyMessage(), emdto.getMimeTypeMessage());
        multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (emdto.getFilePaths() != null) {
            for (String filePath : emdto.getFilePaths()) {
                File file = new File(filePath);
                if (file.exists()) {
                    dataSource = new FileDataSource(file);
                    bodyPart = new MimeBodyPart();
                    bodyPart.setDataHandler(new DataHandler(dataSource));
                    bodyPart.setFileName(file.getName());
                    multipart.addBodyPart(bodyPart);
                }
            }
        }

        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.sendEmail Exception",
                ex);
        throw new BusinessException(ex);
    }
    return Boolean.TRUE;
}

From source file:ftpclient.FTPManager.java

public boolean sendUserMail(String uploadedFileName) {
    if (settings != null) {
        try {//from  www. j  a  va  2 s. co  m
            String userEmail = db.getUserEmail(uid);
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", settings.getSenderEmailHost());
            props.setProperty("mail.smtp.auth", "true");
            //            props.put("mail.smtp.starttls.enable", "true");
            //            props.put("mail.smtp.port", "587");
            Session s = Session.getDefaultInstance(props, new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getSenderLogin(),
                            new String(settings.getSenderPassword()));
                }
            });
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(settings.getSenderEmail());
            msg.addRecipients(Message.RecipientType.TO, userEmail);
            msg.setSubject("FTP action");
            msg.setText("You have succesfully uploaded file " + uploadedFileName);
            Transport.send(msg);
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}