List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart HTML message with the attachements associated to the * message and attached files. FIXME: use prepareMessage method * * @param strRecipientsTo/*from w w w. ja v a 2 s . c om*/ * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param urlAttachements * The List of UrlAttachement Object, containing the URL of * attachments associated with their content-location. * @param fileAttachements * The list of files attached * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty())) ? new MimeMultipart(MULTIPART_RELATED) : new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); if (urlAttachements != null) { ByteArrayDataSource urlByteArrayDataSource; for (UrlAttachment urlAttachement : urlAttachements) { urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement); if (urlByteArrayDataSource != null) { msgBodyPart = new MimeBodyPart(); // Fill this part, then add it to the root part with the // good headers msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource)); msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation()); multipart.addBodyPart(msgBodyPart); } } } // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }
From source file:com.clustercontrol.infra.util.InfraEndpointWrapper.java
public void addInfraFile(InfraFileInfo info, String filePath) throws HinemosUnknown_Exception, InfraFileTooLarge_Exception, InvalidRole_Exception, InvalidUserPass_Exception, InfraManagementDuplicate_Exception { WebServiceException wse = null; for (EndpointSetting<InfraEndpoint> endpointSetting : getInfraEndpoint(endpointUnit)) { try {/* ww w .j a v a 2s .co m*/ InfraEndpoint endpoint = endpointSetting.getEndpoint(); endpoint.addInfraFile(info, new DataHandler(new FileDataSource(filePath))); return; } catch (WebServiceException e) { wse = e; m_log.warn("addInfraFile(), " + e.getMessage()); endpointUnit.changeEndpoint(); } } throw wse; }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java
@SuppressWarnings("deprecation") @Override/*from w w w .j a v a 2 s . 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.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public void addAttachement(File file) { try {// www. j a va 2 s .c o m /* Check if email has already some contents. */ Object content; try { content = this.source.getContent(); } catch (IOException e) { /* If no content, then content is null.*/ content = null; log.warn("Email content is empty.", e); } if (content != null) { if (content instanceof String) { /* This message is not multipart yet. Change it to multipart. */ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText((String) this.source.getContent()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); this.source.setContent(multipart); } } else { /* No content, then create initial multipart content. */ Multipart multipart = new MimeMultipart(); this.source.setContent(multipart); } /* Get current content. */ Multipart multipart = (Multipart) this.source.getContent(); /* add attachment as a new part. */ MimeBodyPart attachementPart = new MimeBodyPart(); DataSource fileSource = new FileDataSource(file); DataHandler fileDataHandler = new DataHandler(fileSource); attachementPart.setDataHandler(fileDataHandler); attachementPart.setFileName(file.getName()); multipart.addBodyPart(attachementPart); } catch (Exception e) { throw new GmailException("Failed to add attachement", e); } }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Add attachments to a multipart message * /* w w w . j a v a2s .c o m*/ * @param multipart Multipart message * @param attachments List of attachments */ public MimeBodyPart createAttachmentBodyPart(Attachment attachment, XWikiContext context) throws XWikiException, IOException, MessagingException { String name = attachment.getFilename(); byte[] stream = attachment.getContent(); File temp = File.createTempFile("tmpfile", ".tmp"); FileOutputStream fos = new FileOutputStream(temp); fos.write(stream); fos.close(); DataSource source = new FileDataSource(temp); MimeBodyPart part = new MimeBodyPart(); String mimeType = MimeTypesUtil.getMimeTypeFromFilename(name); part.setDataHandler(new DataHandler(source)); part.setHeader("Content-Type", mimeType); part.setFileName(name); part.setContentID("<" + name + ">"); part.setDisposition("inline"); temp.deleteOnExit(); return part; }
From source file:com.zimbra.cs.mime.Mime.java
/** * Some devices send wide base64 encoded message body i.e. without line folding. * As per RFC https://www.ietf.org/rfc/rfc2045.txt see 6.8. Base64 Content-Transfer-Encoding * "The encoded output stream must be represented in lines of no more than 76 characters each." * /*from ww w . java2s . c om*/ * To fix the issue here, re-writing the same content to message part. * @param mm * @throws MessagingException * @throws IOException */ public static void fixBase64MimePartLineFolding(MimeMessage mm) throws MessagingException, IOException { List<MPartInfo> mList = Mime.getParts(mm); for (MPartInfo mPartInfo : mList) { String ct = mPartInfo.getMimePart().getHeader("Content-Transfer-Encoding", ":"); if (MimeConstants.ET_BASE64.equalsIgnoreCase(ct)) { InputStream io = mPartInfo.getMimePart().getInputStream(); String ctype = mPartInfo.getMimePart().getContentType(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(io, bos); DataSource ds = new ByteArrayDataSource(bos.toByteArray(), ctype); DataHandler dh = new DataHandler(ds); mPartInfo.getMimePart().setDataHandler(dh); mPartInfo.getMimePart().setHeader("Content-Transfer-Encoding", ct); mPartInfo.getMimePart().setHeader("Content-Type", ctype); } } }
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Helper method to create a MimeBodyPart from a binary file. * * @param pathToFile The complete path to the file - including file name. * @param contentType The Mime content type of the file. * @param fileName The name of the file - as it will appear for the mail recipient. * @return The resulting MimeBodyPart./* w w w. java2s . c o m*/ * @throws SystemException if the MimeBodyPart can't be created. */ public static MimeBodyPart createMimeBodyPartFromBinaryFile(final String pathToFile, final String contentType, String fileName) throws SystemException { try { MimeBodyPart attachmentPart1 = new MimeBodyPart(); FileDataSource fileDataSource1 = new FileDataSource(pathToFile) { @Override public String getContentType() { return contentType; } }; attachmentPart1.setDataHandler(new DataHandler(fileDataSource1)); attachmentPart1.setFileName(fileName); return attachmentPart1; } catch (MessagingException e) { throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e); } }
From source file:com.ilopez.jasperemail.JasperEmail.java
public void emailReport(String emailHost, final String emailUser, final String emailPass, Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames, Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException { Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport); Properties props = new Properties(); // Setup Email Settings props.setProperty("mail.smtp.host", emailHost); props.setProperty("mail.smtp.port", smtpport.toString()); props.setProperty("mail.smtp.auth", smtpauth.toString()); if (smtpenc == OptionValues.SMTPType.SSL) { // SSL settings props.put("mail.smtp.socketFactory.port", smtpport.toString()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); } else if (smtpenc == OptionValues.SMTPType.TLS) { // TLS Settings props.put("mail.smtp.starttls.enable", "true"); } else {//w ww .j a va 2 s. co m // Plain } // Setup and Apply the Email Authentication Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailUser, emailPass); } }); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailSubject); for (String emailRecipient : emailRecipients) { Address toAddress = new InternetAddress(emailRecipient); message.addRecipient(Message.RecipientType.TO, toAddress); } Address fromAddress = new InternetAddress(emailSender); message.setFrom(fromAddress); // Message text Multipart multipart = new MimeMultipart(); BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("Database report attached\n\n"); multipart.addBodyPart(textBodyPart); // Attachments for (String attachmentFileName : attachmentFileNames) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFileName); attachmentBodyPart.setDataHandler(new DataHandler(source)); String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", ""); fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", ""); attachmentBodyPart.setFileName(fileNameWithoutPath); multipart.addBodyPart(attachmentBodyPart); } // add parts to message message.setContent(multipart); // send via SMTP Transport transport = mailSession.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }
From source file:org.apache.axis2.rpc.complex.ComplexDataTypesComplexDataTypesSOAP11Test.java
/** * Auto generated test method/*from w w w . j a va 2s . c o m*/ */ public void testretByteArray() throws java.lang.Exception { byte[] input = new byte[] { (byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF }; DataHandler ret = stub.retByteArray(new DataHandler(new ByteArrayDataSource(input))); byte[] bytes = IOUtils.toByteArray(ret.getInputStream()); assertTrue(Arrays.equals(bytes, input)); }
From source file:com.smartitengineering.emailq.service.impl.EmailServiceImpl.java
private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setFileName(attachment.getName()); if (StringUtils.isNotBlank(attachment.getDescription())) { attachmentPart.setDescription(attachment.getDescription()); }/*from www. j a v a2s .c om*/ if (StringUtils.isNotBlank(attachment.getDisposition())) { attachmentPart.setDisposition(attachment.getDisposition()); } DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType()); attachmentPart.setDataHandler(new DataHandler(source)); multipart.addBodyPart(attachmentPart); }