List of usage examples for javax.mail.internet MimeMultipart addBodyPart
@Override public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
private void addMtomPart(MimeMultipart mp, RequestableHttpVariable variable, Object httpVariableValue) throws IOException, MessagingException { String stringValue = ParameterUtils.toString(httpVariableValue); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName());/*from w w w.j a v a2 s .c o m*/ String cid = variable.getMtomCid(stringValue); Engine.logBeans.debug("(HttpConnector) Prepare the MTOM attachment with cid: " + cid + ". Converting the path '" + stringValue + "' to '" + filepath + "'"); MimeBodyPart bp = new MimeBodyPart(); bp.attachFile(filepath); bp.setContentID(cid); mp.addBodyPart(bp); }
From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java
public void addAttachement(final NodeRef nodeRef, MimeMultipart content, final Boolean convert) throws MessagingException { MappedByteBuffer buf;/*w ww. ja va 2s. com*/ byte[] array = new byte[0]; ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT); String fileName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME); String type = reader.getMimetype().split("/")[0]; if (!type.equalsIgnoreCase("image") && !reader.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF) && convert) { ContentWriter writer = contentService.getTempWriter(); writer.setMimetype(MimetypeMap.MIMETYPE_PDF); String srcMimeType = reader.getMimetype(); //String srcMimeType = ((ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT)).getMimetype(); //String srcMimeType = this.getMimeTypeForFileName(fileName); ContentTransformer transformer = contentService.getTransformer(srcMimeType, MimetypeMap.MIMETYPE_PDF); if (transformer != null) { try { transformer.transform(reader, writer); reader = writer.getReader(); fileName = fileName.substring(0, fileName.lastIndexOf('.')); fileName += ".pdf"; } catch (ContentIOException ex) { logger.warn("could not transform content"); logger.warn(ex); //need to refresh reader as the transformer failing closes the reader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT); } } } try { buf = reader.getFileChannel().map(FileChannel.MapMode.READ_ONLY, 0, reader.getSize()); if (reader.getSize() <= Integer.MAX_VALUE) { array = new byte[(int) reader.getSize()]; buf.get(array); } } catch (IOException ex) { logger.error("There was an error reading file into memory."); logger.error(ex); array = new byte[0]; } ByteArrayDataSource ds = new ByteArrayDataSource(array, reader.getMimetype()); MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(fileName); attachment.setDataHandler(new DataHandler(ds)); content.addBodyPart(attachment); }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;/*from w ww.j a va 2 s. c o m*/ try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java
public static boolean prepareMessagePart(WsdlAttachmentContainer container, MimeMultipart mp, MessageXmlPart messagePart, StringToStringMap contentIds) throws Exception, MessagingException { boolean isXop = false; XmlObjectTreeModel treeModel = null; XmlCursor cursor = messagePart.newCursor(); XmlObject rootXmlObject = cursor.getObject(); try {/* w ww.j a v a 2 s . com*/ while (!cursor.isEnddoc()) { if (cursor.isContainer()) { // could be an attachment part (as of "old" SwA specs which // specify a content // element referring to the attachment) if (messagePart.isAttachmentPart()) { String href = cursor.getAttributeText(XOP_HREF_QNAME); if (href != null && href.length() > 0) { contentIds.put(messagePart.getPart().getName(), href); } break; } XmlObject xmlObj = cursor.getObject(); SchemaType schemaType = xmlObj.schemaType(); if (schemaType.isNoType()) { if (treeModel == null) { treeModel = new XmlObjectTreeModel(messagePart.getSchemaType().getTypeSystem(), rootXmlObject); } XmlTreeNode tn = treeModel.getXmlTreeNode(xmlObj); if (tn != null) schemaType = tn.getSchemaType(); } if (AttachmentUtils.isSwaRefType(schemaType)) { String textContent = XmlUtils.getNodeValue(cursor.getDomNode()); if (StringUtils.hasContent(textContent) && textContent.startsWith("cid:")) { textContent = textContent.substring(4); try { // is the textcontent already a URI? new URI(textContent); contentIds.put(textContent, textContent); } catch (RuntimeException e) { // not a URI.. try to create one.. String contentId = textContent + "@soapui.org"; cursor.setTextValue("cid:" + contentId); contentIds.put(textContent, contentId); } } } else if (AttachmentUtils.isXopInclude(schemaType)) { String contentId = cursor.getAttributeText(new QName("href")); if (contentId != null && contentId.length() > 0) { contentIds.put(contentId, contentId); isXop = true; Attachment[] attachments = container.getAttachmentsForPart(contentId); if (attachments.length == 1) { XmlCursor cur = cursor.newCursor(); if (cur.toParent()) { String contentType = getXmlMimeContentType(cur); if (contentType != null && contentType.length() > 0) attachments[0].setContentType(contentType); } cur.dispose(); } } } else { // extract contentId String textContent = XmlUtils.getNodeValue(cursor.getDomNode()); if (StringUtils.hasContent(textContent)) { Attachment attachment = null; boolean isXopAttachment = false; // is content a reference to a file? if (container.isInlineFilesEnabled() && textContent.startsWith("file:")) { String filename = textContent.substring(5); if (container.isMtomEnabled()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); String xmimeContentType = getXmlMimeContentType(cursor); if (StringUtils.isNullOrEmpty(xmimeContentType)) xmimeContentType = ContentTypeHandler.getContentTypeFromFilename(filename); part.setDataHandler(new DataHandler(new XOPPartDataSource(new File(filename), xmimeContentType, schemaType))); part.setContentID("<" + filename + ">"); mp.addBodyPart(part); isXopAttachment = true; } else { if (new File(filename).exists()) { inlineData(cursor, schemaType, new FileInputStream(filename)); } else { Attachment att = getAttachmentForFilename(container, filename); if (att != null) inlineData(cursor, schemaType, att.getInputStream()); } } } else { Attachment[] attachmentsForPart = container.getAttachmentsForPart(textContent); if (textContent.startsWith("cid:")) { textContent = textContent.substring(4); attachmentsForPart = container.getAttachmentsForPart(textContent); Attachment[] attachments = attachmentsForPart; if (attachments.length == 1) { attachment = attachments[0]; } else if (attachments.length > 1) { attachment = buildMulitpartAttachment(attachments); } isXopAttachment = container.isMtomEnabled(); contentIds.put(textContent, textContent); } // content should be binary data; is this an XOP element // which should be serialized with MTOM? else if (container.isMtomEnabled() && (SchemaUtils.isBinaryType(schemaType) || SchemaUtils.isAnyType(schemaType))) { if ("true".equals(System.getProperty("soapui.mtom.strict"))) { if (SchemaUtils.isAnyType(schemaType)) { textContent = null; } else { for (int c = 0; c < textContent.length(); c++) { if (Character.isWhitespace(textContent.charAt(c))) { textContent = null; break; } } } } if (textContent != null) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); String xmimeContentType = getXmlMimeContentType(cursor); part.setDataHandler(new DataHandler( new XOPPartDataSource(textContent, xmimeContentType, schemaType))); textContent = "http://www.soapui.org/" + System.nanoTime(); part.setContentID("<" + textContent + ">"); mp.addBodyPart(part); isXopAttachment = true; } } else if (container.isInlineFilesEnabled() && attachmentsForPart != null && attachmentsForPart.length > 0) { attachment = attachmentsForPart[0]; } } // add XOP include? if (isXopAttachment && container.isMtomEnabled()) { buildXopInclude(cursor, textContent); isXop = true; } // inline? else if (attachment != null) { inlineAttachment(cursor, schemaType, attachment); } } } } cursor.toNextToken(); } } finally { cursor.dispose(); } return isXop; }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java
@SuppressWarnings("deprecation") @Override//from www .j a va2s . c o m public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); String path = PropertyExpander.expandProperties(context, request.getPath()); StringBuffer query = new StringBuffer(); String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding())); StringToStringMap responseProperties = (StringToStringMap) context .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType()) && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null; RestParamsPropertyHolder params = request.getParams(); for (int c = 0; c < params.getPropertyCount(); c++) { RestParamProperty param = params.getPropertyAt(c); String value = PropertyExpander.expandProperties(context, param.getValue()); responseProperties.put(param.getName(), value); List<String> valueParts = sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired()) ? RestUtils.splitMultipleParametersEmptyIncluded(value, request.getMultiValueDelimiter()) : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter()); // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by // the URI handling further down) if (value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) { try { if (StringUtils.hasContent(encoding)) { value = URLEncoder.encode(value, encoding); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding)); } else { value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } } catch (UnsupportedEncodingException e1) { SoapUI.logError(e1); value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } // URLEncoder replaces space with "+", but we want "%20". value = value.replaceAll("\\+", "%20"); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20")); } if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) { if (!StringUtils.hasContent(value) && !param.getRequired()) continue; } switch (param.getStyle()) { case HEADER: for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart); break; case QUERY: if (formMp == null || !request.isPostQueryString()) { for (String valuePart : valueParts) { if (query.length() > 0) query.append('&'); query.append(URLEncoder.encode(param.getName())); query.append('='); if (StringUtils.hasContent(valuePart)) query.append(valuePart); } } else { try { addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName())); } catch (MessagingException e) { SoapUI.logError(e); } } break; case TEMPLATE: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } break; case MATRIX: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } if (param.getType().equals(XmlBoolean.type.getName())) { if (value.toUpperCase().equals("TRUE") || value.equals("1")) { path += ";" + param.getName(); } } else { path += ";" + param.getName(); if (StringUtils.hasContent(value)) { path += "=" + value; } } case PLAIN: break; } } if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES)) path = PathUtils.fixForwardSlashesInPath(path); if (PathUtils.isHttpPath(path)) { try { // URI(String) automatically URLencodes the input, so we need to // decode it first... URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri); java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(), oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } else if (StringUtils.hasContent(path)) { try { java.net.URI oldUri = httpMethod.getURI(); String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath()) ? oldUri.getRawPath() + path : path; java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), pathToSet, oldUri.getQuery(), oldUri.getFragment()); httpMethod.setURI(newUri); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS))); } catch (Exception e) { SoapUI.logError(e); } } if (query.length() > 0 && !request.isPostQueryString()) { try { java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), query.toString(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } if (request instanceof RestRequest) { String acceptEncoding = ((RestRequest) request).getAccept(); if (StringUtils.hasContent(acceptEncoding)) { httpMethod.setHeader("Accept", acceptEncoding); } } if (formMp != null) { // create request message try { if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); if (StringUtils.hasContent(requestContent)) { initRootPart(request, requestContent, formMp); } } for (Attachment attachment : request.getAttachments()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); if (attachment instanceof FileAttachment<?>) { String name = attachment.getName(); if (StringUtils.hasContent(attachment.getContentID()) && !name.equals(attachment.getContentID())) name = attachment.getContentID(); part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\""); } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\""); part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment))); formMp.addBodyPart(part); } MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(formMp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue()); httpMethod.setHeader("MIME-Version", "1.0"); } catch (Throwable e) { SoapUI.logError(e); } } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { if (StringUtils.hasContent(request.getMediaType())) httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); if (request.isPostQueryString()) { try { ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString())); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } } else { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); List<Attachment> attachments = new ArrayList<Attachment>(); for (Attachment attachment : request.getAttachments()) { if (attachment.getContentType().equals(request.getMediaType())) { attachments.add(attachment); } } if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) { try { byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding); ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content)); } catch (UnsupportedEncodingException e) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new ByteArrayEntity(requestContent.getBytes())); } } else if (attachments.size() > 0) { try { MimeMultipart mp = null; if (StringUtils.hasContent(requestContent)) { mp = new MimeMultipart(); initRootPart(request, requestContent, mp); } else if (attachments.size() == 1) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1)); httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); } if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) { if (mp == null) mp = new MimeMultipart(); // init mimeparts AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap()); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding)); httpMethod.setHeader("MIME-Version", "1.0"); } } catch (Exception e) { SoapUI.logError(e); } } } } }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null;//from w w w .j ava 2 s . co m boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null; //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }
From source file:de.innovationgate.wgpublisher.WGACore.java
public void send(WGAMailNotification notification) { WGAMailConfiguration config = getMailConfig(); if (config != null && config.isEnableAdminNotifications()) { try {//from www . j a v a 2 s .c om Message msg = new MimeMessage(config.createMailSession()); // set recipient and from address String toAddress = config.getToAddress(); if (toAddress == null) { getLog().error( "Unable to send wga admin notification because no recipient address is configured"); return; } msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); InternetAddress[] fromAddr = new InternetAddress[1]; fromAddr[0] = new InternetAddress(config.getFromAddress()); msg.addFrom(fromAddr); msg.setSentDate(new Date()); InetAddress localMachine = InetAddress.getLocalHost(); String hostname = localMachine.getHostName(); String serverName = getWgaConfiguration().getServerName(); if (serverName == null) { serverName = hostname; } msg.setSubject(notification.getSubject()); msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType()); MimeMultipart content = new MimeMultipart(); MimeBodyPart body = new MimeBodyPart(); StringBuffer strBody = new StringBuffer(); strBody.append("<html><head></head><body style=\"color:#808080\">"); strBody.append(notification.getMessage()); String rootURL = getWgaConfiguration().getRootURL(); if (rootURL != null) { //strBody.append("<br><br>"); strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName() + " admin client ...</a></p>"); } // append footer strBody.append("<br><br><b>System information:</b><br><br>"); strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>"); strBody.append("<b>Host:</b> " + hostname + "<br>"); strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>"); strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version " + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor") + ")"); strBody.append("</body></html>"); body.setText(strBody.toString()); body.setHeader("MIME-Version", "1.0"); body.setHeader("Content-Type", "text/html"); content.addBodyPart(body); AppLog appLog = WGA.get(this).service(AppLog.class); if (notification.isAttachLogfile()) { MimeBodyPart attachmentBody = new MimeBodyPart(); StringWriter applog = new StringWriter(); int applogSize = appLog.getLinesCount(); int offset = applogSize - notification.getLogfileLines(); if (offset < 0) { offset = 1; } appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false); attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain")); attachmentBody.setFileName("wga.log"); content.addBodyPart(attachmentBody); } msg.setContent(content); // Send mail Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender"); mailThread.start(); } catch (Exception e) { getLog().error("Unable to send wga admin notification.", e); } } }
From source file:net.sourceforge.subsonic.backend.service.EmailSession.java
public void sendHtmlMessage(String from, List<String> to, List<String> cc, List<String> bcc, List<String> replyTo, String subject, String html, String plain) throws MessagingException { MimeMessage message = createMessage(from, to, cc, bcc, replyTo, subject); MimeBodyPart plainPart = new MimeBodyPart(); plainPart.setText(plain);//from ww w . j ava2s .c o m MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setText(html, "utf-8", "html"); MimeMultipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainPart); multipart.addBodyPart(htmlPart); message.setContent(multipart); sendMessage(message); }
From source file:net.spfbl.http.ServerHTTP.java
private static boolean enviarDesbloqueioDNSBL(Locale locale, String url, String ip, String email) throws MessagingException { if (url == null) { return false; } else if (!Core.hasOutputSMTP()) { return false; } else if (!Core.hasAdminEmail()) { return false; } else if (!Domain.isEmail(email)) { return false; } else if (NoReply.contains(email, true)) { return false; } else {//w w w .j a v a2 s . c om try { Server.logDebug("sending unblock by e-mail."); User user = User.get(email); InternetAddress[] recipients; if (user == null) { recipients = InternetAddress.parse(email); } else { recipients = new InternetAddress[1]; recipients[0] = user.getInternetAddress(); } Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); message.setHeader("Date", Core.getEmailDate()); message.setFrom(Core.getAdminInternetAddress()); message.addRecipients(Message.RecipientType.TO, recipients); String subject; if (locale.getLanguage().toLowerCase().equals("pt")) { subject = "Chave de desbloqueio SPFBL"; } else { subject = "Unblocking key SPFBL"; } message.setSubject(subject); // Corpo da mensagem. StringBuilder builder = new StringBuilder(); builder.append("<!DOCTYPE html>\n"); builder.append("<html lang=\""); builder.append(locale.getLanguage()); builder.append("\">\n"); builder.append(" <head>\n"); builder.append(" <meta charset=\"UTF-8\">\n"); builder.append(" <title>"); builder.append(subject); builder.append("</title>\n"); loadStyleCSS(builder); if (locale.getLanguage().toLowerCase().equals("pt")) { buildConfirmAction(builder, "Desbloquear IP", url, "Confirme o desbloqueio para o IP " + ip + " na DNSBL", "SPFBL.net", "http://spfbl.net/"); } else { buildConfirmAction(builder, "Delist IP", url, "Confirm the delist of IP " + ip + " at DNSBL", "SPFBL.net", "http://spfbl.net/en/"); } builder.append(" </head>\n"); builder.append(" <body>\n"); builder.append(" <div id=\"container\">\n"); builder.append(" <div id=\"divlogo\">\n"); builder.append(" <img src=\"cid:logo\">\n"); builder.append(" </div>\n"); if (locale.getLanguage().toLowerCase().equals("pt")) { buildMessage(builder, "Desbloqueio do IP " + ip + " na DNSBL"); buildText(builder, "Se voc o administrador deste IP, e fez esta solicitao, acesse esta URL e resolva o reCAPTCHA para finalizar o procedimento:"); } else { buildMessage(builder, "Unblock of IP " + ip + " at DNSBL"); buildText(builder, "If you are the administrator of this IP and made this request, go to this URL and solve the reCAPTCHA to finish the procedure:"); } buildText(builder, "<a href=\"" + url + "\">" + url + "</a>"); buildFooter(builder, locale); builder.append(" </div>\n"); builder.append(" </body>\n"); builder.append("</html>\n"); // Making HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(builder.toString(), "text/html;charset=UTF-8"); // Making logo part. MimeBodyPart logoPart = new MimeBodyPart(); File logoFile = getWebFile("logo.png"); logoPart.attachFile(logoFile); logoPart.setContentID("<logo>"); logoPart.addHeader("Content-Type", "image/png"); logoPart.setDisposition(MimeBodyPart.INLINE); // Join both parts. MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlPart); content.addBodyPart(logoPart); // Set multiplart content. message.setContent(content); message.saveChanges(); // Enviar mensagem. return Core.sendMessage(message, 30000); } catch (MailConnectException ex) { throw ex; } catch (SendFailedException ex) { throw ex; } catch (MessagingException ex) { throw ex; } catch (Exception ex) { Server.logError(ex); return false; } } }