List of usage examples for javax.mail.internet MimeUtility encodeText
public static String encodeText(String text, String charset, String encoding) throws UnsupportedEncodingException
From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java
private void setMailMessageHeaders(Email email, MailMessageHeaders headers) throws EmailException { email.setFrom(headers.getFrom());//from ww w .j a v a 2 s. c o m try { email.setSubject(MimeUtility.encodeText(headers.getSubject(), headers.getCharset(), null)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } for (String to : headers.getTo()) { email.addTo(to); } for (String cc : headers.getCc()) { email.addCc(cc); } for (String bcc : headers.getBcc()) { email.addBcc(bcc); } }
From source file:org.dspace.app.webui.util.UIUtil.java
/** * Evaluate filename and client and encode appropriate disposition * * @param filename//from www .ja v a 2 s . co m * @param request * @param response * @throws UnsupportedEncodingException */ public static void setBitstreamDisposition(String filename, HttpServletRequest request, HttpServletResponse response) { String name = filename; Matcher m = p.matcher(name); if (m.find() && !m.group().equals("")) { name = m.group(); } try { String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } finally { response.setHeader("Content-Disposition", "attachment;filename=" + name); } }
From source file:org.dspace.app.xmlui.cocoon.BitstreamReader.java
/** * Write the actual data out to the response. * * Some implementation notes:/*from w w w .j a v a 2 s. c o m*/ * * 1) We set a short expiration time just in the hopes of preventing someone * from overloading the server by clicking reload a bunch of times. I * Realize that this is nowhere near 100% effective but it may help in some * cases and shouldn't hurt anything. * * 2) We accept partial downloads, thus if you lose a connection halfway * through most web browser will enable you to resume downloading the * bitstream. */ public void generate() throws IOException, SAXException, ProcessingException { if (this.bitstreamInputStream == null) { return; } // Only allow If-Modified-Since protocol if request is from a spider // since response headers would encourage a browser to cache results // that might change with different authentication. if (isSpider) { // Check for if-modified-since header -- ONLY if not authenticated long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item != null && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not been, either; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } // Only set Last-Modified: header for spiders or anonymous // access, since it might encourage browse to cache the result // which might leave a result only available to authenticated // users in the cache for a response later to anonymous user. try { if (item != null && (isSpider || ContextUtil.obtainContext(request).getCurrentUser() == null)) { // TODO: Currently just borrow the date of the item, since // we don't have last-mod dates for Bitstreams response.setDateHeader("Last-Modified", item.getLastModified().getTime()); } } catch (SQLException e) { throw new ProcessingException(e); } byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; // Only encourage caching if this is not a restricted resource, i.e. // if it is accessed anonymously or is readable by Anonymous: if (isAnonymouslyReadable) { response.setDateHeader("Expires", System.currentTimeMillis() + expires); } // If this is a large bitstream then tell the browser it should treat it as a download. int threshold = ConfigurationManager.getIntProperty("xmlui.content_disposition_threshold"); if (bitstreamSize > threshold && threshold != 0) { String name = bitstreamName; // Try and make the download file name formatted for each browser. try { String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.contains("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (agent != null && agent.contains("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException see) { // do nothing } response.setHeader("Content-Disposition", "attachment;filename=" + '"' + name + '"'); } ByteRange byteRange = null; // Turn off partial downloads, they cause problems // and are only rarely used. Specifically some windows pdf // viewers are incapable of handling this request. You can // uncomment the following lines to turn this feature back on. // response.setHeader("Accept-Ranges", "bytes"); // String ranges = request.getHeader("Range"); // if (ranges != null) // { // try // { // ranges = ranges.substring(ranges.indexOf('=') + 1); // byteRange = new ByteRange(ranges); // } // catch (NumberFormatException e) // { // byteRange = null; // if (response instanceof HttpResponse) // { // // Respond with status 416 (Request range not // // satisfiable) // response.setStatus(416); // } // } // } try { if (byteRange != null) { String entityLength; String entityRange; if (this.bitstreamSize != -1) { entityLength = "" + this.bitstreamSize; entityRange = byteRange.intersection(new ByteRange(0, this.bitstreamSize)).toString(); } else { entityLength = "*"; entityRange = byteRange.toString(); } response.setHeader("Content-Range", entityRange + "/" + entityLength); if (response instanceof HttpResponse) { // Response with status 206 (Partial content) response.setStatus(206); } int pos = 0; int posEnd; while ((length = this.bitstreamInputStream.read(buffer)) > -1) { posEnd = pos + length - 1; ByteRange intersection = byteRange.intersection(new ByteRange(pos, posEnd)); if (intersection != null) { out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length()); } pos += length; } } else { response.setHeader("Content-Length", String.valueOf(this.bitstreamSize)); while ((length = this.bitstreamInputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } finally { try { // Close the bitstream input stream so that we don't leak a file descriptor this.bitstreamInputStream.close(); // Close the output stream as per Cocoon docs: http://cocoon.apache.org/2.2/core-modules/core/2.2/681_1_1.html out.close(); } catch (IOException ioe) { // Closing the stream threw an IOException but do we want this to propagate up to Cocoon? // No point since the user has already got the bitstream contents. log.warn("Caught IO exception when closing a stream: " + ioe.getMessage()); } } }
From source file:org.dspace.app.xmlui.cocoon.StatsBitstreamReader.java
/** * Write the actual data out to the response. * * Some implementation notes:// w w w. j a v a 2s. c o m * * 1) We set a short expiration time just in the hopes of preventing someone * from overloading the server by clicking reload a bunch of times. I * Realize that this is nowhere near 100% effective but it may help in some * cases and shouldn't hurt anything. * * 2) We accept partial downloads, thus if you lose a connection half way * through most web browser will enable you to resume downloading the * bitstream. */ public void generate() throws IOException, SAXException, ProcessingException { if (this.bitstreamInputStream == null) { return; } // Only allow If-Modified-Since protocol if request is from a spider // since response headers would encourage a browser to cache results // that might change with different authentication. if (isSpider) { // Check for if-modified-since header -- ONLY if not authenticated long modSince = request.getDateHeader("If-Modified-Since"); if (modSince != -1 && item != null && item.getLastModified().getTime() < modSince) { // Item has not been modified since requested date, // hence bitstream has not been, either; return 304 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } // Only set Last-Modified: header for spiders or anonymous // access, since it might encourage browse to cache the result // which might leave a result only available to authenticated // users in the cache for a response later to anonymous user. try { if (item != null && (isSpider || ContextUtil.obtainContext(request).getCurrentUser() == null)) { // TODO: Currently just borrow the date of the item, since // we don't have last-mod dates for Bitstreams response.setDateHeader("Last-Modified", item.getLastModified().getTime()); } } catch (SQLException e) { throw new ProcessingException(e); } byte[] buffer = new byte[BUFFER_SIZE]; int length = -1; // Only encourage caching if this is not a restricted resource, i.e. // if it is accessed anonymously or is readable by Anonymous: if (isAnonymouslyReadable) { response.setDateHeader("Expires", System.currentTimeMillis() + expires); } // If this is a large bitstream then tell the browser it should treat it as a download. int threshold = ConfigurationManager.getIntProperty("xmlui.content_disposition_threshold"); if (bitstreamSize > threshold && threshold != 0) { String name = bitstreamName; // Try and make the download file name formatted for each browser. try { String agent = request.getHeader("USER-AGENT"); if (agent != null && agent.contains("MSIE")) { name = URLEncoder.encode(name, "UTF8"); } else if (agent != null && agent.contains("Mozilla")) { name = MimeUtility.encodeText(name, "UTF8", "B"); } } catch (UnsupportedEncodingException see) { // do nothing } response.setHeader("Content-Disposition", "attachment;filename=" + '"' + name + '"'); } ByteRange byteRange = null; // Turn off partial downloads, they cause problems // and are only rarely used. Specifically some windows pdf // viewers are incapable of handling this request. You can // uncomment the following lines to turn this feature back on. // response.setHeader("Accept-Ranges", "bytes"); // String ranges = request.getHeader("Range"); // if (ranges != null) // { // try // { // ranges = ranges.substring(ranges.indexOf('=') + 1); // byteRange = new ByteRange(ranges); // } // catch (NumberFormatException e) // { // byteRange = null; // if (response instanceof HttpResponse) // { // // Respond with status 416 (Request range not // // satisfiable) // response.setStatus(416); // } // } // } try { if (byteRange != null) { String entityLength; String entityRange; if (this.bitstreamSize != -1) { entityLength = "" + this.bitstreamSize; entityRange = byteRange.intersection(new ByteRange(0, this.bitstreamSize)).toString(); } else { entityLength = "*"; entityRange = byteRange.toString(); } response.setHeader("Content-Range", entityRange + "/" + entityLength); if (response instanceof HttpResponse) { // Response with status 206 (Partial content) response.setStatus(206); } int pos = 0; int posEnd; while ((length = this.bitstreamInputStream.read(buffer)) > -1) { posEnd = pos + length - 1; ByteRange intersection = byteRange.intersection(new ByteRange(pos, posEnd)); if (intersection != null) { out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length()); } pos += length; } } else { response.setHeader("Content-Length", String.valueOf(this.bitstreamSize)); while ((length = this.bitstreamInputStream.read(buffer)) > -1) { out.write(buffer, 0, length); } out.flush(); } } finally { try { // Close the bitstream input stream so that we don't leak a file descriptor this.bitstreamInputStream.close(); // Close the output stream as per Cocoon docs: http://cocoon.apache.org/2.2/core-modules/core/2.2/681_1_1.html out.close(); } catch (IOException ioe) { // Closing the stream threw an IOException but do we want this to propagate up to Cocoon? // No point since the user has already got the bitstream contents. log.warn("Caught IO exception when closing a stream: " + ioe.getMessage()); } } }
From source file:org.liveSense.service.email.EmailServiceImpl.java
private InternetAddress[] convertToInternetAddress(Object address) throws AddressException, UnsupportedEncodingException { if (address == null) return new InternetAddress[] {}; if (address instanceof InternetAddress) return new InternetAddress[] { (InternetAddress) address }; else if (address instanceof String) { return new InternetAddress[] { new InternetAddress( MimeUtility.encodeText((String) address, configurator.getEncoding(), "Q")) }; } else if (address instanceof InternetAddress[]) { return (InternetAddress[]) address; } else if (address instanceof List<?>) { return convertToInternetAddress(((List) address).toArray()); } else if (address instanceof Object[]) { List<InternetAddress> list = new ArrayList<InternetAddress>(); for (Object o : (Object[]) address) { for (InternetAddress addr : convertToInternetAddress(o)) { list.add(addr);//from w w w .j a v a 2s. com } return list.toArray(new InternetAddress[list.size()]); } } return new InternetAddress[] { new InternetAddress(MimeUtility.encodeText(address.toString(), configurator.getEncoding(), "Q")) }; }
From source file:org.liveSense.service.email.EmailServiceImpl.java
private MimeMessage prepareMimeMessage(MimeMessage mimeMessage, Node node, String template, String subject, Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc, HashMap<String, Object> variables) throws AddressException, MessagingException, ValueFormatException, PathNotFoundException, RepositoryException, UnsupportedEncodingException { if (replyTo != null) { mimeMessage.setReplyTo(convertToInternetAddress(replyTo)); } else {//from ww w . j a v a 2 s .c om if (node != null && node.hasProperty("replyTo")) { mimeMessage.setReplyTo(convertToInternetAddress(node.getProperty("replyTo").getString())); } else if (variables != null && variables.containsKey("replyTo")) { mimeMessage.setReplyTo(convertToInternetAddress(variables.get("replyTo"))); } } if (date == null) { if (node != null && node.hasProperty("mailDate")) { mimeMessage.setSentDate(node.getProperty("mailDate").getDate().getTime()); } else if (variables != null && variables.containsKey("mailDate")) { mimeMessage.setSentDate((Date) variables.get("mailDate")); } else { mimeMessage.setSentDate(new Date()); } } else { mimeMessage.setSentDate(date); } if (subject != null) { mimeMessage.setSubject(MimeUtility.encodeText(subject, configurator.getEncoding(), "Q")); } else { if (node != null && node.hasProperty("subject")) { mimeMessage.setSubject(MimeUtility.encodeText(node.getProperty("subject").getString(), configurator.getEncoding(), "Q")); } else if (variables != null && variables.containsKey("subject")) { mimeMessage.setSubject( MimeUtility.encodeText((String) variables.get("subject"), configurator.getEncoding(), "Q")); } } if (from != null) { mimeMessage.setFrom(convertToInternetAddress(from)[0]); } else { if (node != null && node.hasProperty("from")) { mimeMessage.setFrom(convertToInternetAddress(node.getProperty("from").getString())[0]); } else if (variables != null && variables.containsKey("from")) { mimeMessage.setFrom(convertToInternetAddress(variables.get("from"))[0]); } } if (to != null) { mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(to)); } else { if (node != null && node.hasProperty("to")) { if (node.getProperty("to").isMultiple()) { Value[] values = node.getProperty("to").getValues(); for (int i = 0; i < values.length; i++) { mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(values[i].getString())); } } else { mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(node.getProperty("to").getString())); } } else if (variables != null && variables.containsKey("to")) { mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(variables.get("to"))); } } if (cc != null) { mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(cc)); } else { if (node != null && node.hasProperty("cc")) { if (node.getProperty("cc").isMultiple()) { Value[] values = node.getProperty("cc").getValues(); for (int i = 0; i < values.length; i++) { mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(values[i].getString())); } } else { mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(node.getProperty("cc").getString())); } } else if (variables != null && variables.containsKey("cc")) { mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(variables.get("cc"))); } } if (bcc != null) { mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(bcc)); } else { if (node != null && node.hasProperty("bcc")) { if (node.getProperty("bcc").isMultiple()) { Value[] values = node.getProperty("bcc").getValues(); for (int i = 0; i < values.length; i++) { mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(values[i].getString())); } } else { mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(node.getProperty("bcc").getString())); } } else if (variables != null && variables.containsKey("bcc")) { mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(variables.get("bcc"))); } } return mimeMessage; }
From source file:org.orbeon.oxf.processor.EmailProcessor.java
public void start(PipelineContext pipelineContext) { try {// w ww . j av a2s .co m final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA); final Element messageElement = dataDocument.getRootElement(); // Get system id (will likely be null if document is generated dynamically) final LocationData locationData = (LocationData) messageElement.getData(); final String dataInputSystemId = locationData.getSystemID(); // Set SMTP host final Properties properties = new Properties(); final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST); if (testSmtpHostProperty != null) { // Test SMTP Host from properties overrides the local configuration properties.setProperty("mail.smtp.host", testSmtpHostProperty); } else { // Try regular config parameter and property String host = messageElement.element("smtp-host").getTextTrim(); if (host != null && !host.equals("")) { // Precedence goes to the local config parameter properties.setProperty("mail.smtp.host", host); } else { // Otherwise try to use a property host = getPropertySet().getString(EMAIL_SMTP_HOST); if (host == null) host = getPropertySet().getString(EMAIL_HOST_DEPRECATED); if (host == null) throw new OXFException("Could not find SMTP host in configuration or in properties"); properties.setProperty("mail.smtp.host", host); } } // Create session final Session session; { // Get credentials final String usernameTrimmed; final String passwordTrimmed; { final Element credentials = messageElement.element("credentials"); if (credentials != null) { final Element usernameElement = credentials.element("username"); final Element passwordElement = credentials.element("password"); usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim() : null; passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : ""; } else { usernameTrimmed = null; passwordTrimmed = null; } } // Check if credentials are supplied if (StringUtils.isNotEmpty(usernameTrimmed)) { // NOTE: A blank username doesn't trigger authentication if (logger.isInfoEnabled()) logger.info("Authentication"); // Set the auth property to true properties.setProperty("mail.smtp.auth", "true"); if (logger.isInfoEnabled()) logger.info("Username: " + usernameTrimmed); // Create an authenticator final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed); // Create session with authenticator session = Session.getInstance(properties, authenticator); } else { if (logger.isInfoEnabled()) logger.info("No Authentication"); session = Session.getInstance(properties); } } // Create message final Message message = new MimeMessage(session); // Set From message.addFrom(createAddresses(messageElement.element("from"))); // Set To String testToProperty = getPropertySet().getString(EMAIL_TEST_TO); if (testToProperty == null) testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED); if (testToProperty != null) { // Test To from properties overrides local configuration message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty)); } else { // Regular list of To elements for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) { final InternetAddress[] addresses = createAddresses(toElement); message.addRecipients(Message.RecipientType.TO, addresses); } } // Set Cc for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) { final InternetAddress[] addresses = createAddresses(ccElement); message.addRecipients(Message.RecipientType.CC, addresses); } // Set Bcc for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) { final InternetAddress[] addresses = createAddresses(bccElement); message.addRecipients(Message.RecipientType.BCC, addresses); } // Set headers if any for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) { final String headerName = headerElement.element("name").getTextTrim(); final String headerValue = headerElement.element("value").getTextTrim(); // NOTE: Use encodeText() in case there are non-ASCII characters message.addHeader(headerName, MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null)); } // Set the email subject // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode. // The result is pure ASCII so that setSubject() will not attempt to re-encode it. message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(), DEFAULT_CHARACTER_ENCODING, null)); // Handle body final Element textElement = messageElement.element("text"); final Element bodyElement = messageElement.element("body"); if (textElement != null) { // Old deprecated mechanism (simple text body) message.setText(textElement.getStringValue()); } else if (bodyElement != null) { // New mechanism with body and parts handleBody(pipelineContext, dataInputSystemId, message, bodyElement); } else { throw new OXFException("Main text or body element not found");// TODO: location info } // Send message final Transport transport = session.getTransport("smtp"); Transport.send(message); transport.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:org.pentaho.platform.scheduler2.email.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {//from w w w . ja v a 2s . co m // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("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()); } if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*from www . ja v a2 s.c o m*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("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()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:ru.runa.common.web.HTMLUtils.java
public static String encodeFileName(HttpServletRequest request, String fileName) { try {//from w w w. jav a 2 s . com String userAgent = request.getHeader("User-Agent"); if (userAgent != null) { if (userAgent.indexOf("MSIE") != -1 || userAgent.indexOf("Trident") != -1 || userAgent.indexOf("Edge") != -1) { // IE fileName = URLEncoder.encode(fileName, Charsets.UTF_8.name()); fileName = fileName.replaceAll("\\+", " "); } else { fileName = MimeUtility.encodeText(fileName, Charsets.UTF_8.name(), "B"); } } } catch (UnsupportedEncodingException e) { throw Throwables.propagate(e); } return fileName; }