List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. 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 w w w .ja v a 2s . c om 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:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. */// w w w . j a v a 2s .c o m protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:com.cisco.dbds.utils.report.CustomReport.java
/** * Sendmail./*from w ww.j a v a2 s . c o m*/ * * @param msg the msg * @throws AddressException the address exception * @throws IOException Signals that an I/O exception has occurred. */ public static void sendmail(String msg) throws AddressException, IOException { //Properties CustomReport_CONFIG = new Properties(); //FileInputStream fn = new FileInputStream(System.getProperty("user.dir")+ "/src/it/resources/config.properties"); //CustomReport_CONFIG.load(fn); String from = "automationreportmailer@cisco.com"; // String from = "sitaut@cisco.com"; //String host = System.getProperty("MAIL.SMTP.HOST"); String host = "outbound.cisco.com"; // Mail to details Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); // String ecsip = CustomReport_CONFIG.getProperty("ecsip"); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // compose the message try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from // )); , "Automation Report Mailer")); //message.addRecipients(Message.RecipientType.TO, System.getProperty("MAIL.TO")); //message.setSubject(System.getProperty("mail.subject")); message.addRecipients(Message.RecipientType.TO, "maparame@cisco.com"); message.setSubject("VCS consle report"); Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(msg, "text/html"); mp.addBodyPart(htmlPart); message.setContent(mp); Transport.send(message); System.out.println(msg); System.out.println("message sent successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } catch (Exception e) { System.out.println("\tException in sending mail to configured mailers list"); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object/* w w w . j a v a 2 s . c om*/ */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();/*w ww . j av a 2 s. c o m*/ boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
From source file:com.azprogrammer.qgf.controllers.HomeController.java
@RequestMapping(value = "/wbmail") public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) { model.clear();//from ww w.java 2 s . co m try { WBEmail email = new WBEmail(); HttpSession session = req.getSession(); String userName = session.getAttribute("userName").toString(); String toAddress = req.getParameter("email"); if (!WebUtil.isValidEmail(toAddress)) { throw new Exception("invalid email"); } //TODO validate message contents email.setFromUser(userName); email.setToAddress(toAddress); WhiteBoard wb = getWhiteBoard(req); if (wb == null) { throw new Exception("Invalid White Board"); } email.setWbKey(wb.getKey()); email.setCreationTime(System.currentTimeMillis()); Properties props = new Properties(); Session mailsession = Session.getDefaultInstance(props, null); String emailError = null; try { MimeMessage msg = new MimeMessage(mailsession); msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); msg.setSubject("Please join the whiteboard session on " + req.getServerName()); String msgBody = "To join " + userName + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "</a>"; msg.setText(msgBody, "UTF-8", "html"); Transport.send(msg); } catch (AddressException e) { emailError = e.getMessage(); } catch (MessagingException e) { emailError = e.getMessage(); } if (emailError == null) { email.setStatus(WBEmail.STATUS_SENT); } else { email.setStatus(WBEmail.STATUS_ERROR); } getPM().makePersistent(email); if (email.getStatus() == WBEmail.STATUS_ERROR) { throw new Exception(emailError); } model.put("status", "ok"); } catch (Exception e) { model.put("error", e.getMessage()); } return doJSON(model); }
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 v a 2s .c om //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//from ww w .j ava 2 s . c o m * @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:isl.FIMS.utils.Utils.java
public static boolean sendEmail(String to, String subject, String context) { boolean isSend = false; try {//from w w w .j a v a 2 s . co m String host = "smtp.gmail.com"; String user = emailAdress; String password = emailPass; String port = "587"; String from = "no-reply-" + systemName + "@gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); // props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); // props.put("mail.smtp.socketFactory.port", port); // props.put("mail.smtp.socketFactory.class", // "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.port", "465"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); // To get the array of addresses message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject, "UTF-8"); message.setContent(context, "text/html; charset=UTF-8"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } isSend = true; } catch (MessagingException ex) { ex.printStackTrace(); } return isSend; }
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this * method will deliver the subject and message via an email * transport (e.g. SMTP).//from ww w .j av a 2 s. com * * @param aSubject Message subject. * @param aMessage Message content. * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aSubject, String aMessage) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); String propertyName = "address_to"; Message mimeMessage = new MimeMessage(mMailSession); if (mAppMgr.isPropertyMultiValue(getCfgString(propertyName))) { String[] addressToArray = mAppMgr.getStringArray(getCfgString(propertyName)); for (String mailAddressTo : addressToArray) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } } else { String mailAddressTo = getCfgString(propertyName); if (StringUtils.isEmpty(mailAddressTo)) { String msgStr = String.format("Mail Manager property '%s' is undefined.", mCfgPropertyPrefix + "." + propertyName); appLogger.error(msgStr); throw new NSException(msgStr); } internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } propertyName = "address_from"; String mailAddressFrom = getCfgString(propertyName); if (StringUtils.isEmpty(mailAddressFrom)) { String msgStr = String.format("Mail Manager property '%s' is undefined.", mCfgPropertyPrefix + "." + propertyName); appLogger.error(msgStr); throw new NSException(msgStr); } internetAddressFrom = new InternetAddress(mailAddressFrom); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); mimeMessage.setSubject(aSubject); mimeMessage.setContent(aMessage, "text/plain"); appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); Transport.send(mimeMessage); } else throw new NSException("Subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }