List of usage examples for javax.activation FileDataSource FileDataSource
public FileDataSource(String name)
From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public void addAttachement(File file) { try {//from ww w . j a v a 2 s .com /* 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.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 {/*from w w w . j a v a 2 s . c om*/ // 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:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2, String grupSephora, String subject, String filename) throws FileNotFoundException, IOException { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); }// w w w . j a v a 2 s. c o m }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); //send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:org.wso2.carbon.repomanager.axis2.Axis2RepoManager.java
/** * Downloads the relevant artifacts from the repository * @param filePath path to the artifacts that should be downloaded, relative to the tenants repository * @return the datahandler corresponding to the artifact that should be downloaded *//*from w w w.ja v a2 s.c o m*/ public DataHandler downloadArtifact(String filePath) { String resourcePath = getAxisConfig().getRepository().getPath() + filePath; FileDataSource datasource = new FileDataSource(new File(resourcePath)); DataHandler handler = new DataHandler(datasource); return handler; }
From source file:com.clustercontrol.infra.util.InfraEndpointWrapper.java
public void modifyInfraFile(InfraFileInfo info, String filePath) throws HinemosUnknown_Exception, InfraFileTooLarge_Exception, InvalidRole_Exception, InvalidUserPass_Exception { WebServiceException wse = null; for (EndpointSetting<InfraEndpoint> endpointSetting : getInfraEndpoint(endpointUnit)) { try {/*from w w w .j a v a 2 s. c o m*/ InfraEndpoint endpoint = endpointSetting.getEndpoint(); if (filePath != null) { endpoint.modifyInfraFile(info, new DataHandler(new FileDataSource(filePath))); } else { endpoint.modifyInfraFile(info, null); } return; } catch (WebServiceException e) { wse = e; m_log.warn("modifyInfraFile(), " + e.getMessage()); endpointUnit.changeEndpoint(); } } throw wse; }
From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java
/** * Sends email with attachments/*from www . jav a2s .c o m*/ * * @param from * The address this message is to be listed as coming from. * @param to * The address(es) this message should be sent to. * @param subject * The subject of this message. * @param content * The body of the message. * @param headerToStr * If specified, this is placed into the message header, but "to" is used for the recipients. * @param replyTo * If specified, this is the reply to header address(es). * @param additionalHeaders * Additional email headers to send (List of String). For example, content type or forwarded headers (may be null) * @param messageAttachments * Message attachments */ protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject, String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<EmailAttachment> emailAttachments) { if (testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments); return; } if (smtp == null || smtp.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMailWithAttachments: smtp not set"); } return; } if (from == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: from is needed to send email"); } return; } if (to == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: to is needed to send email"); } return; } if (content == null) { if (logger.isWarnEnabled()) { logger.warn("sendMail: content is needed to send email"); } return; } if (emailAttachments == null || emailAttachments.size() == 0) { if (logger.isWarnEnabled()) { logger.warn("sendMail: emailAttachments are needed to send email with attachments"); } return; } try { if (session == null) { if (logger.isWarnEnabled()) { logger.warn("mail session is null"); } return; } MimeMessage message = new MimeMessage(session); // default charset String charset = "UTF-8"; message.setSentDate(new Date()); message.setFrom(from); message.setSubject(subject, charset); MimeBodyPart messageBodyPart = new MimeBodyPart(); // Content-Type: text/plain; text/html; String contentType = null, contentTypeValue = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith("content-type:")) { contentType = header; contentTypeValue = contentType.substring( contentType.indexOf("content-type:") + "content-type:".length(), contentType.length()); break; } } } // message String messagetype = ""; if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(content, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(content, messagetype); } //messageBodyPart.setContent(content, "text/html; charset="+ charset); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); String jforumAttachmentStoreDir = serverConfigurationService() .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR); if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) { if (logger.isWarnEnabled()) { logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR + ") property is not set in sakai.properties "); } } else { // attachments for (EmailAttachment emailAttachment : emailAttachments) { String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(emailAttachment.getRealFileName()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("Error while attaching attachments: " + e, e); } } } } message.setContent(multipart); Transport.send(message, to); } catch (MessagingException e) { if (logger.isWarnEnabled()) { logger.warn("sendMail: Error in sending email: " + e, e); } } }
From source file:org.openehealth.ipf.platform.camel.lbs.http.process.AbstractLbsHttpTest.java
@Test public void testMultipartSendOnly() throws Exception { Exchange sendExchange = new DefaultExchange(camelContext); FileDataSource dataSource1 = new FileDataSource(file); InputStream inputStream = dataSource1.getInputStream(); ResourceDataSource resource1 = factory.createResource("test", "text/plain", "text", "first", inputStream); inputStream.close();/* ww w . j av a 2s .co m*/ ByteArrayDataSource dataSource2 = new ByteArrayDataSource("testdata".getBytes(), "text/plain"); inputStream = dataSource2.getInputStream(); ResourceDataSource resource2 = factory.createResource("test", "text/plain", "text", "second", dataSource2.getInputStream()); inputStream.close(); ResourceList resources = new ResourceList(); resources.add(resource1); resources.add(resource2); sendExchange.getIn().setBody(resources); sendExchange.setPattern(ExchangePattern.InOut); mock.expectedMessageCount(1); mock.whenAnyExchangeReceived(outputGenerator); Exchange output = producerTemplate.send(ENDPOINT_SEND_ONLY, sendExchange); mock.assertIsSatisfied(); assertEquals("testoutput", output.getOut().getBody(String.class)); Map<String, String> receivedContent = outputGenerator.getReceivedContent(); assertEquals(2, receivedContent.size()); assertEquals("blu bla", receivedContent.get("first")); assertEquals("testdata", receivedContent.get("second")); }
From source file:org.kalypso.services.observation.server.ObservationServiceDelegate.java
@Override public final DataBean readData(final String href) throws SensorException { init();/*from w w w . j a va 2 s. c o m*/ final String hereHref = ObservationServiceUtils.removeServerSideId(href); final String obsId = org.kalypso.ogc.sensor.zml.ZmlURL.getIdentifierPart(hereHref); final ObservationBean obean = new ObservationBean(obsId); // request part specified? IRequest request = null; Request requestType = null; try { requestType = RequestFactory.parseRequest(hereHref); if (requestType != null) { request = ObservationRequest.createWith(requestType); m_logger.info("Reading data for observation: " + obean.getId() + " Request: " + request); //$NON-NLS-1$ //$NON-NLS-2$ } else m_logger.info("Reading data for observation: " + obean.getId()); //$NON-NLS-1$ } catch (final SensorException e) { m_logger.warning("Invalid Href: " + href); //$NON-NLS-1$ m_logger.throwing(getClass().getName(), "readData", e); //$NON-NLS-1$ // this is a fatal error (software programming error on the client-side) // so break processing now! throw e; } // fetch observation from repository IObservation obs = null; try { final IRepositoryItem item = itemFromBean(obean); obs = (IObservation) item.getAdapter(IObservation.class); } catch (final Exception e) { m_logger.info("Could not find an observation for " + obean.getId() + ". Reason is:\n" //$NON-NLS-1$//$NON-NLS-2$ + e.getLocalizedMessage()); // this is not a fatal error, repository might be temporarely unavailable } if (obs == null) { // obs could not be created, use the request now m_logger.info("Creating request-based observation for " + obean.getId()); //$NON-NLS-1$ obs = RequestFactory.createDefaultObservation(requestType); } try { // tricky: maybe make a filtered observation out of this one obs = FilterFactory.createFilterFrom(hereHref, obs, null); // name of the temp file must be valid against OS-rules for naming files // so remove any special characters final String tempFileName = FileUtilities.validateName("___" + obs.getName(), "-"); //$NON-NLS-1$ //$NON-NLS-2$ // create temp file m_tmpDir.mkdirs(); // additionally create the parent dir if not already exists final File f = File.createTempFile(tempFileName, ".zml", m_tmpDir); //$NON-NLS-1$ // we say delete on exit even if we allow the client to delete the file // explicitely in the clearTempData() service call. This allows us to // clear temp files on shutdown in the case the client forgets it. f.deleteOnExit(); ZmlFactory.writeToFile(obs, f, request); final DataBean data = new DataBean(f.toString(), new DataHandler(new FileDataSource(f))); m_mapDataId2File.put(data.getId(), f); return data; } catch (final IOException e) // generic exception used for simplicity { m_logger.throwing(getClass().getName(), "readData", e); //$NON-NLS-1$ throw new SensorException(e.getLocalizedMessage(), e); } }
From source file:org.etudes.jforum.util.mail.Spammer.java
/** * prepare attachment message// w ww. j a v a2s. c o m * @param addresses Addresses * @param params Message params * @param subject Message subject * @param messageFile Message file * @param attachments Attachments * @throws EmailException */ protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject, String messageFile, List attachments) throws EmailException { if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments entering....."); this.message = new MimeMessage(session); try { InternetAddress[] recipients = new InternetAddress[addresses.size()]; String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET); this.message.setSentDate(new Date()); // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER))); String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; this.message.setFrom(new InternetAddress(from)); this.message.setSubject(subject, charset); this.messageText = this.getMessageText(params, messageFile); MimeBodyPart messageBodyPart = new MimeBodyPart(); String messagetype = ""; // message if (messageFormat == MESSAGE_HTML) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachments Attachment attachment = null; Iterator iterAttach = attachments.iterator(); while (iterAttach.hasNext()) { attachment = (Attachment) iterAttach.next(); // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getInfo().getRealFilename()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e); } } message.setContent(multipart); int i = 0; for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) { recipients[i] = new InternetAddress((String) iter.next()); } this.message.setRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { logger.warn(e); throw new EmailException(e); } if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments exiting....."); }
From source file:com.iana.boesc.utility.BOESCUtil.java
public static boolean sendEmailWithAttachments(final String emailFrom, final String subject, final InternetAddress[] addressesTo, final String body, final File attachment) { try {// w w w.ja v a 2 s . co m Session session = Session.getInstance(GlobalVariables.EMAIL_PROPS, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("", ""); } }); MimeMessage message = new MimeMessage(session); // Set From: header field of the header. InternetAddress addressFrom = new InternetAddress(emailFrom); message.setFrom(addressFrom); // Set To: header field of the header. message.addRecipients(Message.RecipientType.TO, addressesTo); // Set Subject: header field message.setSubject(subject); // Create the message part BodyPart messageBodyPart = new javax.mail.internet.MimeBodyPart(); // Fill the message messageBodyPart.setText(body); messageBodyPart.setContent(body, "text/html"); // Create a multi part message Multipart multipart = new javax.mail.internet.MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new javax.mail.internet.MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); return true; } catch (Exception ex) { ex.getMessage(); return false; } }