Example usage for javax.mail.internet MimeMessage setContent

List of usage examples for javax.mail.internet MimeMessage setContent

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage setContent.

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal)
        throws MessagingException {
    if (appockMail.getBonLivraison() == null) {
        msg.setContent(contenuFinal, "text/html; charset=utf-8");
    } else {//  w  w  w.  j  ava  2  s  .com
        BonLivraison bonLivraison = appockMail.getBonLivraison();
        Multipart multipart = new MimeMultipart();
        BodyPart attachmentBodyPart = new MimeBodyPart();

        File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison());

        ByteArrayDataSource bds = null;
        try {
            bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()),
                    bonLivraison.getMimeType().getLibelle());
        } catch (IOException e) {
            e.printStackTrace();
        }

        attachmentBodyPart.setDataHandler(new DataHandler(bds));
        attachmentBodyPart.setFileName(bonLivraison.getNomFichier());
        multipart.addBodyPart(attachmentBodyPart);

        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8");
        multipart.addBodyPart(htmlBodyPart);
        msg.setContent(multipart);
    }
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public void sendMessage(Address from_addr, Address[] to_addr, Address[] cc_addr, String subject, String content)
        throws MessagingException {
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(from_addr);/*from  www . j av  a 2s. c o m*/
    msg.setRecipients(Message.RecipientType.TO, to_addr);
    if (cc_addr.length > 0)
        msg.setRecipients(Message.RecipientType.CC, cc_addr);
    msg.setSubject(subject, "UTF-8");
    msg.setContent(content, "text/plain");

    transport.sendMessage(msg, ArrayUtils.addAll(to_addr, cc_addr));
}

From source file:mitm.common.mail.repository.hibernate.MailRepositoryImplTest.java

@Test
public void testPerformance() throws Exception {
    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    int messageSize = 50 * SizeUtils.MB;

    byte[] content = new byte[messageSize];

    Arrays.fill(content, (byte) 'A');

    message.setContent(content, "application/octet-stream");
    message.saveChanges();/*w  ww  .ja v a2 s  .  c om*/
    MailUtils.validateMessage(message);

    long start = System.currentTimeMillis();

    int nrOfItems = 10;

    for (int i = 0; i < nrOfItems; i++) {
        proxy.addItem(DEFAULT_REPOSITORY, message,
                InternetAddress.parse("test" + i + "@example.com, other@example.com", false),
                new InternetAddress("sender" + i + "@example.com", false), "127.0.0." + i, null, null);
    }

    double msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / add:" + msec);

    assertTrue("Can fail on slower systems", msec < 10000);

    start = System.currentTimeMillis();

    List<? extends MailRepositoryItem> items = proxy.getItems(DEFAULT_REPOSITORY, 0, Integer.MAX_VALUE);

    for (MailRepositoryItem item : items) {
        System.out.println(item.getID());
    }

    msec = (double) (System.currentTimeMillis() - start) / nrOfItems;

    System.out.println("msec / get:" + msec);

    assertTrue("Can fail on slower systems", msec < 100);
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {//from  www  . jav  a  2 s. c  om
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    msg.setContent("", "text/plain");
    msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset));
    msg.setSentDate(new Date());

    String replyTo = Mailer.descriptor().getReplyToAddress();
    if (StringUtils.isNotBlank(replyTo)) {
        msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) });
    }//from w ww . j  av  a2  s.  c  om

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    String defaultSuffix = Mailer.descriptor().getDefaultSuffix();
    StringTokenizer tokens = new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(),
                    AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address

            // if not a valid address (i.e. no '@'), then try adding suffix
            if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
                address += defaultSuffix;
            }

            try {
                rcp.add(Mailer.StringToAddress(address, charset));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                listener.getLogger().println("Unable to send to address: " + address);
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    for (AbstractProject project : includeUpstreamCommitters) {
        includeCulpritsOf(project, build, listener, rcp);
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }/*from w ww. j  a v  a2s. c om*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:ee.cyber.licensing.service.MailService.java

public void sendExpirationNearingMail(License license) throws IOException, MessagingException {
    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");
    final String mailTo = mailServerProperties.getProperty("mailTo");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }//  ww w .  java  2 s .c om
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "Licensing service"));
    mailMessage.setSubject("License with id " + license.getId() + " is expiring");
    mailMessage.setSentDate(new Date());
    mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
    String emailBody = "This is test<br><br> Regards, <br>Licensing team";
    mailMessage.setContent(emailBody, "text/html");

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);

}

From source file:com.gendevs.bedrock.appengine.integration.mail.Mailer.java

public void sendMail(Mail mail, Map<String, Object> model) throws MessagingException {

    //TODO: Deepak. not the perfect way to pull resources from the below code
    //but accordng to http://velocity.apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders
    //File resource handelers needs more config for which we don't have enough time.
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");

    helper.setSubject(mail.getSubject());
    helper.setFrom(AppConstants.APP_EMAILID);

    for (MailReceiver mailReceiver : mail.getReceivers()) {
        model.put("_receiverFirstName", mailReceiver.firstName);
        model.put("_receiverLastName", mailReceiver.lastName);
        model.put("_receiverEmail", mailReceiver.email);
        model.put("_receiverImageUrl", mailReceiver.imageUrl);

        String mailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                "com/gendevs/bedrock/appengine/integration/mail/templates/" + mail.getTemplateName(), "UTF-8",
                model);//from w w  w.j ava2 s .c  om
        mimeMessage.setContent(mailBody, mail.getContentType());

        helper.setTo(mailReceiver.email);
        mailSender.send(mimeMessage);
    }
}

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

public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name,
        Double discountDouble) {/*from   ww  w . ja  v  a2  s  .  c  o 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:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }/*  w  ww  .j a  v a2s . c  o  m*/

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}