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: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 {//from   w  w w.j  a va 2  s .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: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 w w  .  j  a va  2 s  . c o m
    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:org.cloudcoder.healthmonitor.HealthMonitor.java

/**
 * Create a mail Session based on information in the
 * given {@link HealthMonitorConfig}.//www  .j  ava  2s. c  o m
 * 
 * @param config the {@link HealthMonitorConfig}
 * @return the mail Session
 */
private Session createMailSession(HealthMonitorConfig config) {
    final PasswordAuthentication passwordAuthentication = new PasswordAuthentication(config.getSmtpUsername(),
            config.getSmtpPassword());

    Properties properties = new Properties();
    properties.putAll(System.getProperties());
    properties.setProperty("mail.smtp.submitter", passwordAuthentication.getUserName());
    properties.setProperty("mail.smtp.auth", "true");
    properties.setProperty("mail.smtp.host", config.getSmtpServer());
    properties.setProperty("mail.smtp.port", String.valueOf(config.getSmtpPort()));
    properties.setProperty("mail.smtp.starttls.enable", String.valueOf(config.isSmtpUseTLS()));

    return Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return passwordAuthentication;
        }
    });
}

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

/**
 * //from  w ww .  j  a v a 2  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();

}

From source file:Model.DAO.java

public void sendEmail(int id, String status) {
    SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
    Properties props = new Properties();
    /** Parmetros de conexo com servidor Gmail */
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("seuemail@gmail.com", "suasenha");
        }//  w  w w.  j a  va 2 s. c o  m
    });

    /** Ativa Debug para sesso */

    try {
        PreparedStatement stmt = this.conn
                .prepareStatement("SELECT * FROM Reservation re WHERE idReservas = ?");
        stmt.setInt(1, id);
        ResultSet rs = stmt.executeQuery();
        rs.next();
        String date = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[0];
        String time = formatDateTime.format(rs.getTimestamp("dateTime")).split("-")[1];
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("pck1993@gmail.com")); //Remetente

        Address[] toUser = InternetAddress //Destinatrio(s)
                .parse(rs.getString("email"));

        message.setRecipients(Message.RecipientType.TO, toUser);
        message.setSubject("Status Reserva");//Assunto
        message.setText("Email de alterao do status da resreva no dia " + date + " s " + time
                + " horas para " + status);
        /**Mtodo para enviar a mensagem criada*/
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (SQLException ex) {
        Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties/*w  w  w .  j  a  va  2  s  .  c om*/
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"),
                    password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth
    return mailSession;
}

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

public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name,
        Double discountDouble) {/*from w ww.j  a va2  s . co m*/

    //check if service agent exist
    List<User> userName = userDAO.verifyUserByUserName(user_name);
    Integer user_id = userName.get(0).getUser_id();
    System.out.println("user_id: " + user_id);
    String userNameString = userName.get(0).getUser_name().toString();
    System.out.println("userNameString: " + userNameString);

    ArrayList<HashMap<String, String>> billList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> billHash = new HashMap<String, String>();

    if (user_name.equals(userNameString)) {
        //fetch reservation id
        List<Reservation> reservRecords = reservationDAO.find(reservation_token);
        Integer reservation_id = reservRecords.get(0).getReservation_id();
        System.out.println("reservation_id: " + reservation_id);
        Integer guest_id = reservRecords.get(0).getGuest_id();
        System.out.println("guest_id:: " + guest_id);
        List<Guest> emailRecord = guestDAO.findGuestEmailId(reservRecords.get(0).getGuest_id());
        String guestEmailID = emailRecord.get(0).getGuest_email();
        String guestName = emailRecord.get(0).getGuest_name();
        System.out.println("emailRecord: " + guestEmailID);
        System.out.println("guestName: " + guestName);
        System.out.println(reservRecords.size());

        System.out.println(reservRecords.get(0).getReservation_id());
        Integer s = reservRecords.get(0).getReservation_id();
        System.out.println("integer value: " + s);
        //Integer reservation_id = reservRecords.get(0).getReservation_id();

        //fetch checkin mapping table data
        ReservationDTO reservDTO = new ReservationDTO();
        reservDTO.setReservation_id(reservRecords.get(0).getReservation_id());
        List<CheckinRoomMapping> checkinMappingRecords = checkinRoomMappingDAO.findMappingForBilling(reservDTO);
        Date checkin_date = checkinMappingRecords.get(0).getCheckin_date();
        Date checkout_date = checkinMappingRecords.get(0).getCheckout_date();

        long daysStay = ((checkout_date.getTime() - checkin_date.getTime()) / MILLISECONDS_IN_DAY) + 1;//
        System.out.println("daysStay: " + daysStay);
        String noOfDaysStayed = String.valueOf(daysStay);//
        System.out.println("noOfDaysStayed: " + noOfDaysStayed);
        Double totalBill = 0.0;
        ArrayList<HashMap<String, String>> mailContent = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < checkinMappingRecords.size(); i++) {
            System.out.println("Room(" + i + ") : " + checkinMappingRecords.get(i).getRoom_no());

            Integer room_no = checkinMappingRecords.get(i).getRoom_no();
            String roomNoInString = String.valueOf(room_no);//
            System.out.println("roomNoInString: " + roomNoInString);
            RoomDTO roomDTO = new RoomDTO();
            roomDTO.setRoom_no(room_no);

            Enum<RoomType> roomType = roomDAO.findRoomType(roomDTO);
            String type = roomType.toString();//
            if (type.equalsIgnoreCase("K"))
                type = "King";
            if (type.equalsIgnoreCase("Q"))
                type = "Queen";
            if (type.equalsIgnoreCase("SK"))
                type = "Smoking - King";
            if (type.equalsIgnoreCase("SQ"))
                type = "Smoking - Queen";
            System.out.println("room type: " + type);

            //Fetch price by room type
            Double roomPrice = roomPriceDAO.getRoomPrice(roomType);//
            System.out.println("roomPrice:::" + roomPrice);
            String roomPriceString = String.valueOf(roomPrice);
            System.out.println("roomPriceString: " + roomPriceString);
            Double billPerRoom = roomPrice * daysStay;//
            String billPerRoomString = String.valueOf(billPerRoom);
            System.out.println("billPerRoomString:" + billPerRoomString);
            totalBill = totalBill + billPerRoom;

            //set hash map
            HashMap<String, String> mailBody = new HashMap<String, String>();
            mailBody.put("Room_Number", roomNoInString);
            mailBody.put("Room_Type", type);
            mailBody.put("Room_Price", roomPriceString);
            mailBody.put("NoOfDays", noOfDaysStayed);
            mailBody.put("BillPerRoom", billPerRoomString);

            mailContent.add(mailBody);
            //end hash map

            System.out.println("-------");
        }
        System.out.println("totalBill::" + totalBill);
        String templateForEmailBody = "";
        for (HashMap<String, String> h : mailContent) {
            System.out.println("room_numer" + h.get("Room_Number"));
            templateForEmailBody = templateForEmailBody + "<tr><td>" + h.get("Room_Number") + "</td><td>"
                    + h.get("Room_Type") + "</td><td>" + h.get("Room_Price") + "</td><td>" + h.get("NoOfDays")
                    + "</td><td>" + h.get("BillPerRoom") + "</td><tr><br>";

        }
        System.out.println("templateForEmailBody" + templateForEmailBody);
        Integer bill_no = guest_id;
        String bill_no_String = String.valueOf(bill_no);
        System.out.println("discount" + discountDouble);
        //String bill_no_String = String.valueOf(discountDouble);

        Double totalDiscount = (discountDouble / 100) * totalBill;
        String totalDiscountString = String.valueOf(totalDiscount);

        Double amountPayable = totalBill - totalDiscount;
        String amountPayableString = String.valueOf(amountPayable);

        //ReservationDTO res = new ReservationDTO();
        BillingDTO billingDTO = new BillingDTO();
        billingDTO.setBill_no(bill_no);
        billingDTO.setReservation_id(reservation_id);
        billingDTO.setUser_id(user_id);
        billingDTO.setDiscount(totalDiscount);
        billingDTO.setAmount(amountPayable);

        Reservation resObj = new Reservation();
        resObj.setReservation_id(reservation_id);

        User userObj = new User();
        userObj.setUser_id(user_id);

        Billing billObject = new Billing();
        billObject.setBill_no(bill_no);
        billObject.setReservation(resObj);
        billObject.setUser(userObj);
        billObject.setDiscount(totalDiscount);
        billObject.setAmount(amountPayable);

        //            try {
        //                org.apache.commons.beanutils.BeanUtils.copyProperties(billObject, billingDTO);
        //            } catch (IllegalAccessException e) {
        //                e.printStackTrace();
        //            } catch (InvocationTargetException e) {
        //                e.printStackTrace();
        //            }

        Integer billID = billingDAO.insertBillData(billObject);
        System.out.println("Bill id after Insert: " + billID);

        if (billID != null) {
            //email

            final String from = "express.minihotel@gmail.com";
            String to = guestEmailID;
            String body = "Hello " + guestName + ",<br><br>You bill details are as follows:<br>"
                    + "<table border='1' style=\"border-collapse: collapse;\"><tr>"
                    + "<td><b>Room Number</b></td>" + "<td><b>Room Type</b></td>"
                    + "<td><b>Price per day ($)</b></td>" + "<td><b>Duration of Stay (days)</b></td>"
                    + "<td><b>Bill for Room ($)</b></td></tr>" + templateForEmailBody
                    + "</table><br>Net Bill: $" + totalBill + "<br><br>" + "Discount: $" + totalDiscountString
                    + "<br></br>" + "<br/><b>Total Bill Paid($): <font color='red'>" + amountPayable
                    + "</font></b><br></br><br></br>Thank You for choosing Express Hotel.<br/><br/><i>--Express Hotel</i>";

            String subject = "Express Hotel - Bill Receipt (Receipt No : " + bill_no_String + ")";
            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
            billHash.put("bill_amount", amountPayableString);
            billHash.put("bill_body", body);
            billList.add(billHash);
            //return billList;
        }
    } else {
        //username doesnot exist
        billHash.put("bill_amount", "User does not exist");
        billList.add(billHash);
        //return billList;
    }

    return billList;

}

From source file:checkwebsite.Mainframe.java

/**
 *
 * @param email/*  w w  w .  j a v a2s. c om*/
 * @param msg
 */
protected void notify(String email, String msg) {
    // Recipient's email ID needs to be mentioned.
    String to = email;//change accordingly

    // go to link below and turn on Access for less secure apps
    //https://www.google.com/settings/security/lesssecureapps
    // Sender's email ID needs to be mentioned
    String from = "";//Enter your email id here
    final String username = "";//Enter your email id here
    final String password = "";//Enter your password here

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

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

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

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

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

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Report of your website : " + wurl);

        //            // Now set the actual message
        //            message.setText("Hello, " + msg + " this is sample for to check send "
        //                    + "email using JavaMailAPI ");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setText("Please! find your website report in attachment");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

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

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "WebsiteReport.txt";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

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

        // Send message
        Transport.send(message);
        lblWarning.setText("report sent...");
        System.out.println("Sent message successfully....");

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

From source file:org.openmrs.api.context.Context.java

/**
 * Gets the mail session required by the mail message service. This function forces
 * authentication via the getAdministrationService() method call
 * //w  w  w  .  j  a  v a  2 s  . c  o m
 * @return a java mail session
 */
private static javax.mail.Session getMailSession() {
    if (mailSession == null) {
        AdministrationService adminService = getAdministrationService();

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", adminService.getGlobalProperty("mail.transport_protocol"));
        props.setProperty("mail.smtp.host", adminService.getGlobalProperty("mail.smtp_host"));
        props.setProperty("mail.smtp.port", adminService.getGlobalProperty("mail.smtp_port"));
        props.setProperty("mail.from", adminService.getGlobalProperty("mail.from"));
        props.setProperty("mail.debug", adminService.getGlobalProperty("mail.debug"));
        props.setProperty("mail.smtp.auth", adminService.getGlobalProperty("mail.smtp_auth"));

        Authenticator auth = new Authenticator() {

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getAdministrationService().getGlobalProperty("mail.user"),
                        getAdministrationService().getGlobalProperty("mail.password"));
            }
        };

        mailSession = Session.getInstance(props, auth);
    }
    return mailSession;
}

From source file:com.emc.kibana.emailer.KibanaEmailer.java

private static void sendFileEmail(String security) {

    final String username = smtpUsername;
    final String password = smtpPassword;

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    if (security.equals(SMTP_SECURITY_TLS)) {
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", smtpHost);
        properties.put("mail.smtp.port", smtpPort);
    } else if (security.equals(SMTP_SECURITY_SSL)) {
        properties.put("mail.smtp.socketFactory.port", smtpPort);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.port", smtpPort);
    }/*w  w w  .j a va 2s .  c  o m*/

    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        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(sourceAddress));

        // Set To: header field of the header.
        for (String destinationAddress : destinationAddressList) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(destinationAddress));
        }

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

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        StringBuffer bodyBuffer = new StringBuffer(mailBody);
        if (!kibanaUrls.isEmpty()) {
            bodyBuffer.append("\n\n");
        }

        // Add urls info to e-mail
        for (Map<String, String> kibanaUrl : kibanaUrls) {
            // Add urls to e-mail
            String urlName = kibanaUrl.get(NAME_KEY);
            String reportUrl = kibanaUrl.get(URL_KEY);
            if (urlName != null && reportUrl != null) {
                bodyBuffer.append("- ").append(urlName).append(": ").append(reportUrl).append("\n\n\n");
            }
        }

        // Fill the message
        messageBodyPart.setText(bodyBuffer.toString());

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

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

        // Part two is attachments
        for (Map<String, String> kibanaScreenCapture : kibanaScreenCaptures) {
            messageBodyPart = new MimeBodyPart();
            String absoluteFilename = kibanaScreenCapture.get(ABSOLUE_FILE_NAME_KEY);
            String filename = kibanaScreenCapture.get(FILE_NAME_KEY);
            DataSource source = new FileDataSource(absoluteFilename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            multipart.addBodyPart(messageBodyPart);
        }

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

        // Send message
        Transport.send(message);
        logger.info("Sent mail message successfully");
    } catch (MessagingException mex) {
        throw new RuntimeException(mex);
    }
}