List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { try {/* www . j a va2 s .c o m*/ log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI")); if (session != null && notificationEmailAddress != null) { MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(notificationEmailAddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI"))); //maybe nice to use a template rather then sending raw xml. String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body"); msg_content = String .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName), StringEscapeUtils.escapeHtml(AppConfig.getConfiguration() .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), GetSubscriptionType(body), GetChangeSummary(body)); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()); Transport.send(message); } else { throw new DispositionReportFaultMessage("Session is null!", null); } } catch (Exception e) { log.error(e.getMessage(), e); throw new DispositionReportFaultMessage(e.getMessage(), null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
From source file:contestWebsite.Registration.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity contestInfo = Retrieve.contestInfo(); Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap()); for (Entry<String, String[]> param : params.entrySet()) { if (!"studentData".equals(param.getKey())) { params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) }); }/* ww w . j a va 2s . c om*/ } String registrationType = params.get("registrationType")[0]; String account = "no"; if (params.containsKey("account")) { account = "yes"; } String email = params.containsKey("email") && params.get("email")[0].length() > 0 ? params.get("email")[0].toLowerCase().trim() : null; String schoolLevel = params.get("schoolLevel")[0]; String schoolName = params.get("schoolName")[0].trim(); String name = params.get("name")[0].trim(); String classification = params.containsKey("classification") ? params.get("classification")[0] : ""; String studentData = req.getParameter("studentData"); String password = null; String confPassword = null; UserCookie userCookie = UserCookie.getCookie(req); boolean loggedIn = userCookie != null && userCookie.authenticate(); if ((!loggedIn || !userCookie.isAdmin()) && email == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "E-Mail Address parameter ('email') must be specified"); return; } HttpSession sess = req.getSession(true); sess.setAttribute("registrationType", registrationType); sess.setAttribute("account", account); sess.setAttribute("account", account); sess.setAttribute("name", name); sess.setAttribute("classification", classification); sess.setAttribute("schoolName", schoolName); sess.setAttribute("schoolLevel", schoolLevel); sess.setAttribute("email", email); sess.setAttribute("studentData", studentData); boolean reCaptchaResponse = false; if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); reCaptchaResponse = JSONResponse.getBoolean("success"); } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) { resp.sendRedirect("/registration?captchaError=1"); } else { if (account.equals("yes")) { password = params.get("password")[0]; confPassword = params.get("confPassword")[0]; } Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly(); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) { if (users.size() != 0) { resp.sendRedirect("/registration?userError=1"); } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) { resp.sendRedirect("/registration?passwordError=1"); } else { resp.sendRedirect("/registration?updated=1"); } } else { Entity registration = new Entity("registration"); registration.setProperty("registrationType", registrationType); registration.setProperty("account", account); registration.setProperty("schoolName", schoolName); registration.setProperty("schoolLevel", schoolLevel); registration.setProperty("name", name); registration.setProperty("classification", classification); registration.setProperty("studentData", new Text(studentData)); registration.setProperty("email", email); registration.setProperty("paid", ""); registration.setProperty("timestamp", new Date()); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) contestInfo.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); if (account.equals("yes") && password != null && password.length() > 0 && email != null) { Entity user = new Entity("user"); String hash = Password.getSaltedHash(password); user.setProperty("name", name); user.setProperty("school", schoolName); user.setProperty("schoolLevel", schoolLevel); user.setProperty("user-id", email); user.setProperty("salt", hash.split("\\$")[0]); user.setProperty("hash", hash.split("\\$")[1]); datastore.put(user); } txn.commit(); sess.setAttribute("props", registration.getProperties()); if (email != null) { Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); String url = req.getRequestURL().toString(); url = url.substring(0, url.indexOf("/", 7)); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name)); msg.setSubject("Thank you for your registration!"); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("url", url); context.put("cost", cost); context.put("title", contestInfo.getProperty("title")); context.put("account", account.equals("yes")); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "registrationEmail", ((Text) contestInfo.getProperty("registrationEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } resp.sendRedirect("/registration?updated=1"); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } } }
From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java
@Override public boolean executeAction() { EmailAction emailAction = (EmailAction) getActionDefinition(); String messagePlain = emailAction.getMessagePlain().getStringValue(); String messageHtml = emailAction.getMessageHtml().getStringValue(); String subject = emailAction.getSubject().getStringValue(); String to = emailAction.getTo().getStringValue(); String cc = emailAction.getCc().getStringValue(); String bcc = emailAction.getBcc().getStringValue(); String from = emailAction.getFrom().getStringValue(defaultFrom); if (from.trim().length() == 0) { from = defaultFrom;//from w ww. jav a2 s. com } /* * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter = * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter( * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context, * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if ( * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it = * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if ( * attachData != null ) { attachments.add( attachData ); } } } } * * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" ) * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value } * * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0; * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } } */ if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$ } if ((to == null) || (to.trim().length() == 0)) { // Get the output stream that the feedback is going into OutputStream feedbackStream = getFeedbackOutputStream(); if (feedbackStream != null) { createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$ "", "", true); //$NON-NLS-1$ //$NON-NLS-2$ setFeedbackMimeType("text/html"); //$NON-NLS-1$ return true; } else { return false; } } if (subject == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$ return false; } if ((messagePlain == null) && (messageHtml == null)) { error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$ return false; } if (getRuntimeContext().isPromptPending()) { return true; } try { Properties props = new Properties(); final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession()); props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost()); props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort())); props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol()); props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls())); props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate())); props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl())); props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait())); props.put("mail.from.default", service.getEmailConfig().getDefaultFrom()); String fromName = service.getEmailConfig().getFromName(); if (StringUtils.isEmpty(fromName)) { fromName = Messages.getInstance().getString("schedulerEmailFromName"); } props.put("mail.from.name", fromName); props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug())); Session session; if (service.getEmailConfig().isAuthenticate()) { props.put("mail.userid", service.getEmailConfig().getUserId()); props.put("mail.password", service.getEmailConfig().getPassword()); Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // debugging is on if either component (xaction) or email config debug is on if (service.getEmailConfig().isDebug() || ComponentBase.debug) { session.setDebug(true); } // construct the message MimeMessage msg = new MimeMessage(session); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } EmailAttachment[] emailAttachments = emailAction.getAttachments(); if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) { msg.setText(messagePlain, LocaleHelper.getSystemEncoding()); } else if (emailAttachments.length == 0) { if (messagePlain != null) { msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } if (messageHtml != null) { msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } } else { // need to create a multi-part message... // create the Multipart and add its parts to it Multipart multipart = new MimeMultipart(); // create and fill the first message part if (messageHtml != null) { // create and fill the first message part MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(htmlBodyPart); } if (messagePlain != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } for (EmailAttachment element : emailAttachments) { IPentahoStreamSource source = element.getContent(); if (source == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); String attachmentName = element.getName(); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$ } // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$ dataSource.getName())); } multipart.addBodyPart(attachmentBodyPart); } // add the Multipart to the message msg.setContent(multipart); } msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$ } return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ /* * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof * MessagingException) { sfe = (MessagingException) ne; * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe); * //$NON-NLS-1$ } */ } catch (AuthenticationFailedException e) { error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$ } catch (Throwable e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ } return false; }
From source file:org.apache.synapse.transport.mail.MailTransportSender.java
/** * Populate email with a SOAP formatted message * @param outInfo the out transport information holder * @param msgContext the message context that holds the message to be written * @throws AxisFault on error//from w w w . j a va 2 s . com */ private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new BaseTransportException("Unable to get the message formatter to use"); } WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] { smtpFromAddress }); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // if a custom message id is set, use it if (msgContext.getMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body ByteArrayOutputStream baos = null; String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); DataHandler dataHandler = null; MimeMultipart mimeMultiPart = null; OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement(); if (firstChild != null) { if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) { baos = new ByteArrayOutputStream(); OMNode omNode = firstChild.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { dataHandler = (DataHandler) dh; } } } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) { if (firstChild instanceof OMSourcedElementImpl) { baos = new ByteArrayOutputStream(); try { firstChild.serializeAndConsume(baos); } catch (XMLStreamException e) { handleException("Error serializing 'text' payload from OMSourcedElement", e); } dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), MailConstants.TEXT_PLAIN); } else { dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN); } } else { baos = new ByteArrayOutputStream(); messageFormatter.writeTo(msgContext, format, baos, true); // create the data handler dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), contentType); String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } } } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); } catch (MessagingException e) { handleException("Error creating mail message or sending it to the configured server", e); } finally { try { if (baos != null) { baos.close(); } } catch (IOException ignore) { } } }
From source file:com.cisco.dbds.utils.report.CustomReport.java
/** * Sendmail.//from ww w . j av a 2 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:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments * //from ww w . j a v a 2s .c om * @param mailOptions * @return */ public boolean sendFiles(Map<String, Object> mailOptions) { logger.debug("IN"); try { final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory"; String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); File tempFolder = new File(tempFolderPath); if (!tempFolder.exists() || !tempFolder.isDirectory()) { logger.error("Temp Folder " + tempFolderPath + " does not exist or is not a directory: stop sending mail"); return false; } String smtphost = null; String pass = null; String smtpssl = null; String trustedStorePath = null; String user = null; String from = null; int smtpPort = 25; try { smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpportS == null) || smtpportS.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smtpPort = Integer.parseInt(smtpportS); } from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); } catch (Exception e) { logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e); throw new Exception( "Some E-mail configuration not set in table sbi_config: check you have all settings."); } String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null; Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP) : null; mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null; String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS) : null; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.p ort", Integer.toString(smtpPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null; Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("") ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT) : null; //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null; String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE) : null; String fileExtension = mailOptions.get(FILE_EXTENSION) != null ? (String) mailOptions.get(FILE_EXTENSION) : null; if (reportNameInSubject) { subject += " " + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt); // attach the file to the message boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT) : false; zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (isZipDocument) { logger.debug("Make zip"); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder); mp.addBodyPart(mbp2); } else { logger.debug("Attach single files"); SchedulerDataSource sds = null; MimeBodyPart bodyPart = null; try { String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { logger.debug("Attach file " + entries[i]); File f = new File(tempFolder + File.separator + entries[i]); byte[] content = getBytesFromFile(f); bodyPart = new MimeBodyPart(); sds = new SchedulerDataSource(content, contentType, entries[i]); //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension); bodyPart.setDataHandler(new DataHandler(sds)); bodyPart.setFileName(sds.getName()); mp.addBodyPart(bodyPart); } } catch (Exception e) { logger.error("Error while attaching files", e); } } // add the Multipart to the message msg.setContent(mp); logger.debug("Preparing to send mail"); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { logger.debug("Smtps mode active user " + user); //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smtpPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { logger.debug("Smtp mode"); //Use normal SMTP Transport.send(msg); } // logger.debug("delete tempFolder path "+tempFolder.getPath()); // boolean deleted = tempFolder.delete(); // logger.debug("Temp folder deleted "+deleted); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.project.implementation.ReservationImplementation.java
public ArrayList<HashMap<String, String>> calculateBill(String reservation_token, String user_name, Double discountDouble) {//w w w . ja v a 2 s.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:com.azprogrammer.qgf.controllers.HomeController.java
@RequestMapping(value = "/wbmail") public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) { model.clear();//from www. j av a2 s . c o 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:org.tizzit.util.mail.Mail.java
/** * Sends the message and cleans up all temp files that were created for the attachments. * /*from w w w . j a v a 2 s . c o m*/ * @throws MessagingException */ private void doSend() throws MessagingException { this.message.setSentDate(new Date()); Transport.send(this.message); if (this.attachments.size() > 0) { Enumeration<String> enumeration = this.tempFileNameMappings.keys(); while (enumeration.hasMoreElements()) { File file = new File(enumeration.nextElement()); if (file.exists()) { if (!file.delete()) { log.error("Temp file " + file.getAbsolutePath() + " could not be deleted!"); } } } this.attachments.clear(); this.tempFileNameMappings.clear(); } }
From source file:net.wastl.webmail.plugins.SendMessage.java
public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head) throws WebMailException, ServletException { if (sess1 == null) { throw new WebMailException( "No session was given. If you feel this is incorrect, please contact your system administrator"); }/* w w w . j a va 2s.c o m*/ WebMailSession session = (WebMailSession) sess1; UserData user = session.getUser(); HTMLDocument content; Locale locale = user.getPreferredLocale(); /* Save message in case there is an error */ session.storeMessage(head); if (head.isContentSet("SEND")) { /* The form was submitted, now we will send it ... */ try { MimeMessage msg = new MimeMessage(mailsession); Address from[] = new Address[1]; try { /** * Why we need * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()? * * Because we specify client browser's encoding to UTF-8, IE seems * to send all data encoded in UTF-8. We have to transcode all byte * sequences we received to UTF-8, and next we encode those strings * using MimeUtility.encodeText() depending on user's locale. Since * MimeUtility.encodeText() is used to convert the strings into its * transmission format, finally we can use the strings in the * outgoing e-mail which relies on receiver's email agent to decode * the strings. * * As described in JavaMail document, MimeUtility.encodeText() conforms * to RFC2047 and as a result, we'll get strings like "=?Big5?B......". */ /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()), // MimeUtility.encodeText(session.getUser().getFullName())); from[0] = new InternetAddress( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale), TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null, locale)); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName()); } StringTokenizer t; try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("TO").trim(), ",;"); } /* Check To: field, when empty, throw an exception */ if (t.countTokens() < 1) { throw new MessagingException("The recipient field must not be empty!"); } Address to[] = new Address[t.countTokens()]; int i = 0; while (t.hasMoreTokens()) { to[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("CC").trim(), ",;"); } Address cc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { cc[i] = new InternetAddress(t.nextToken().trim()); i++; } try { /** * Since data in session.getUser() is read from file, the encoding * should be default encoding. */ // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),","); t = new StringTokenizer( TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(), ","); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); t = new StringTokenizer(head.getContent("BCC").trim(), ",;"); } Address bcc[] = new Address[t.countTokens()]; i = 0; while (t.hasMoreTokens()) { bcc[i] = new InternetAddress(t.nextToken().trim()); i++; } session.setSent(false); msg.addFrom(from); if (to.length > 0) { msg.addRecipients(Message.RecipientType.TO, to); } if (cc.length > 0) { msg.addRecipients(Message.RecipientType.CC, cc); } if (bcc.length > 0) { msg.addRecipients(Message.RecipientType.BCC, bcc); } msg.addHeader("X-Mailer", WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion()); String subject = null; if (!head.isContentSet("SUBJECT")) { subject = "no subject"; } else { try { // subject=MimeUtility.encodeText(head.getContent("SUBJECT")); subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1", locale); } catch (UnsupportedEncodingException e) { log.warn("Unsupported Encoding while trying to send message: " + e.getMessage()); subject = head.getContent("SUBJECT"); } } msg.addHeader("Subject", subject); if (head.isContentSet("REPLY-TO")) { // msg.addHeader("Reply-To",head.getContent("REPLY-TO")); msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"), "ISO8859_1", locale)); } msg.setSentDate(new Date(System.currentTimeMillis())); String contnt = head.getContent("BODY"); //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); String charset = "utf-8"; MimeMultipart cont = new MimeMultipart(); MimeBodyPart txt = new MimeBodyPart(); // Transcode to UTF-8 contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8"); // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { txt.setText(contnt, "Big5"); txt.setHeader("Content-Type", "text/plain; charset=\"Big5\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } else { txt.setText(contnt, "utf-8"); txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP? } /* Add an advertisement if the administrator requested to do so */ cont.addBodyPart(txt); if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) { MimeBodyPart adv = new MimeBodyPart(); String file = ""; if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) { file = store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } else { file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator") + store.getConfig("ADVERTISEMENT SIGNATURE PATH"); } String advcont = ""; try { BufferedReader fin = new BufferedReader(new FileReader(file)); String line = fin.readLine(); while (line != null && !line.equals("")) { advcont += line + "\n"; line = fin.readLine(); } fin.close(); } catch (IOException ex) { } /** * Transcode to UTF-8; Since advcont comes from file, we transcode * it from default encoding. */ // Encode text if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) { advcont = new String(advcont.getBytes(), "Big5"); adv.setText(advcont, "Big5"); adv.setHeader("Content-Type", "text/plain; charset=\"Big5\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } else { advcont = new String(advcont.getBytes(), "UTF-8"); adv.setText(advcont, "utf-8"); adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); adv.setHeader("Content-Transfer-Encoding", "quoted-printable"); } cont.addBodyPart(adv); } for (String attachmentKey : session.getAttachments().keySet()) { ByteStore bs = session.getAttachment(attachmentKey); InternetHeaders ih = new InternetHeaders(); ih.addHeader("Content-Transfer-Encoding", "BASE64"); PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); /* This is used to write to the Pipe asynchronously to avoid blocking */ StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000); BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64")); encoder.write(bs.getBytes()); encoder.flush(); encoder.close(); //MimeBodyPart att1=sconn.getResult(); MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes()); if (bs.getDescription() != "") { att1.setDescription(bs.getDescription(), "utf-8"); } /** * As described in FileAttacher.java line #95, now we need to * encode the attachment file name. */ // att1.setFileName(bs.getName()); String fileName = bs.getName(); String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry()); String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null); if (encodedFileName.equals(fileName)) { att1.addHeader("Content-Type", bs.getContentType()); att1.setFileName(fileName); } else { att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset); encodedFileName = encodedFileName.substring(localeCharset.length() + 5, encodedFileName.length() - 2); encodedFileName = encodedFileName.replace('=', '%'); att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''" + encodedFileName); } cont.addBodyPart(att1); } msg.setContent(cont); // } msg.saveChanges(); boolean savesuccess = true; msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid")); if (session.getUser().wantsSaveSent()) { String folderhash = session.getUser().getSentFolder(); try { Folder folder = session.getFolder(folderhash); Message[] m = new Message[1]; m[0] = msg; folder.appendMessages(m); } catch (MessagingException e) { savesuccess = false; } catch (NullPointerException e) { // Invalid folder: savesuccess = false; } } boolean sendsuccess = false; try { Transport.send(msg); Address sent[] = new Address[to.length + cc.length + bcc.length]; int c1 = 0; int c2 = 0; for (c1 = 0; c1 < to.length; c1++) { sent[c1] = to[c1]; } for (c2 = 0; c2 < cc.length; c2++) { sent[c1 + c2] = cc[c2]; } for (int c3 = 0; c3 < bcc.length; c3++) { sent[c1 + c2 + c3] = bcc[c3]; } sendsuccess = true; throw new SendFailedException("success", new Exception("success"), sent, null, null); } catch (SendFailedException e) { session.handleTransportException(e); } //session.clearMessage(); content = new XHTMLDocument(session.getModel(), store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme())); // if(sendsuccess) session.clearWork(); } catch (Exception e) { log.error("Could not send messsage", e); throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")"); } } else if (head.isContentSet("ATTACH")) { /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to have two targets without Javascript) */ content = parent.getURLHandler().handleURL("/compose/attach", session, head); } else { throw new DocumentNotFoundException("Could not send message. (Reason: No content given)"); } return content; }