List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:be.fedict.eid.dss.model.bean.TaskMDB.java
private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype, byte[] attachment) { LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\""); String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class); if (null == smtpServer || smtpServer.trim().isEmpty()) { LOG.warn("no SMTP server configured"); return;/*from www. j a va 2 s.c om*/ } String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class); if (null == mailFrom || mailFrom.trim().isEmpty()) { LOG.warn("no mail from address configured"); return; } LOG.debug("mail from: " + mailFrom); Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); props.put("mail.from", mailFrom); String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class); if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) { subject = "[" + mailPrefix.trim() + "] " + subject; } Session session = Session.getInstance(props, null); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(); mimeMessage.setRecipients(RecipientType.TO, mailTo); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setText(messageBody); Multipart multipart = new MimeMultipart(); // first part is body multipart.addBodyPart(mimeBodyPart); // second part is attachment if (null != attachment) { MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype); attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource)); multipart.addBodyPart(attachmentMimeBodyPart); } mimeMessage.setContent(multipart); Transport.send(mimeMessage); } catch (MessagingException e) { throw new RuntimeException("send failed, exception: " + e.getMessage(), e); } }
From source file:de.kp.ames.web.function.bulletin.PostingLCM.java
/** * Submit comment for a certain posting// w ww . j a v a 2 s . co m * * @param posting * @param data * @return * @throws Exception */ public String submitComment(String posting, String data) throws Exception { /* * Create or retrieve registry package that is * responsible for managing comments */ RegistryPackageImpl container = null; JaxrDQM dqm = new JaxrDQM(jaxrHandle); List<RegistryPackageImpl> list = dqm.getRegistryPackage_ByClasNode(ClassificationConstants.FNC_ID_Comment); if (list.size() == 0) { /* * Create container */ container = createCommentPackage(); } else { /* * Retrieve container */ container = list.get(0); } /* * A comment is a certain extrinsic object that holds all relevant * and related information in a single JSON repository item */ ExtrinsicObjectImpl eo = null; JaxrTransaction transaction = new JaxrTransaction(); // create extrinsic object that serves as a container for // the respective comment eo = createExtrinsicObject(); if (eo == null) throw new JAXRException(); /* * Identifier */ String eid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.COMMENT_PRE); /* * Name & description using default locale */ JSONObject jPosting = new JSONObject(data); String name = "[COMMENT] " + jPosting.getString(JaxrConstants.RIM_NAME); String desc = "[SUBJ] " + jPosting.getString(JaxrConstants.RIM_SUBJECT); /* * Home url */ String home = jaxrHandle.getEndpoint().replace("/saml", ""); /* * Set properties */ setProperties(eo, eid, name, desc, home); /* * Mime type & handler */ String mimetype = GlobalConstants.MT_JSON; eo.setMimeType(mimetype); byte[] bytes = data.getBytes(GlobalConstants.UTF_8); DataHandler handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, mimetype)); eo.setRepositoryItem(handler); /* * Create classification */ ClassificationImpl c = createClassification(ClassificationConstants.FNC_ID_Comment); c.setName(createInternationalString(Locale.US, "Comment Classification")); /* * Associate classification and posting container */ eo.addClassification(c); /* * Add extrinsic object to container */ container.addRegistryObject(eo); /* * Create association */ String aid = JaxrIdentity.getInstance().getPrefixUID(FncConstants.COMMENT_PRE); AssociationImpl a = this.createAssociation_RelatedTo(eo); /* * Set properties */ setProperties(a, aid, "Posting Link", "This is a directed association between a posting and the respective comment.", home); /* * Source object */ ExtrinsicObjectImpl so = (ExtrinsicObjectImpl) jaxrHandle.getDQM().getRegistryObject(posting); so.addAssociation(a); /* * Add association to container */ container.addRegistryObject(a); /* * Save objects */ confirmAssociation(a); transaction.addObjectToSave(container); saveObjects(transaction.getObjectsToSave(), false, false); /* * Supply reactor */ ReactorParams reactorParams = new ReactorParams(jaxrHandle, eo, ClassificationConstants.FNC_ID_Comment, RAction.C_INDEX); ReactorImpl.onSubmit(reactorParams); /* * Retrieve response message */ JSONObject jResponse = transaction.getJResponse(eid, FncMessages.COMMENT_CREATED); return jResponse.toString(); }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }//from www . jav a2 s . com String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.PresentationWSDaoImplTestBase.java
private BlackboardPresentationResponse createRepoPresentation() throws Exception { InputStream is = new ByteArrayInputStream("fdsdfsfsdadsfasfda".getBytes()); ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg"); DataHandler dataHandler = new DataHandler(rawData); BlackboardPresentationResponse presenetation = dao.uploadPresentation(user.getUniqueId(), "test.elp", "aliens", dataHandler); presentations.put(presenetation.getPresentationId(), presenetation); return presenetation; }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException { Transport t = null;/*w w w .j a va 2 s .c o m*/ try { MimeMessage message = new MimeMessage(session); t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { for (InputStream attachment : attachments.keySet()) { messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val } } catch (IOException e) { throw new MessagingException("cannot add an attachment to mail", e); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); } finally { if (t != null) { t.close(); } } }
From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java
/** * Returns a data-handler for this part// ww w . j a v a 2 s .c om * @return a data-handler for this part */ public DataHandler getDataHandler(Cache<URL, CachedUrlData> cache) throws MessagingException { if (file != null) { return new DataHandler(new FileDataSource(file)); } else if (url != null) { return new DataHandler(new CachedUrlDataSource(url, cache)); } else { return new DataHandler(new ByteArrayDataSource(content, contentType)); } }
From source file:mitm.application.djigzo.ws.impl.BackupWSImpl.java
@Override @StartTransaction//from www . j ava 2s. c o m public BinaryDTO backupDirect(String password) throws WebServiceCheckedException { try { /* * The backup will be store in memory. If we store the backup in a file we need to create a * temp file to support concurrent access. The problem with this is that we can only delete * the file when it has been received by the end party but then we already lost control. * Storing the backup in memory can take some memory so we will add a max backup size. * If we need to support much larger backup sizes we can always resort to a file cache * which will periodically delete stale files. */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream output = new SizeLimitedOutputStream(bos, maxBackupSize, true); BackupDriver backupDriver = new OutputStreamBackupDriver(output); String identifier = backupMaker.backup(backupDriver, password); DataSource source = new ByteArrayDataSource(bos.toByteArray(), "application/octet-stream"); DataHandler dataHandler = new DataHandler(source); return new BinaryDTO(dataHandler, identifier); } catch (BackupException e) { logger.error("restore failed.", e); throw new WebServiceCheckedException(ExceptionUtils.getRootCauseMessage(e)); } catch (RuntimeException e) { logger.error("restore failed.", e); throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e)); } }
From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java
protected void send(String subject, String content, String contentType) throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", getHost()); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false);/*from ww w . ja v a 2s . co m*/ Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr")); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "utf-8"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); List<String> fileNames = getAtchFileIds(); for (Iterator<String> it = fileNames.iterator(); it.hasNext();) { MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(it.next()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : mp.addBodyPart(mbp2); } // add the Multipart to the message message.setContent(mp); for (Iterator<String> it = getReceivers().iterator(); it.hasNext();) message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next())); transport.connect(getHost(), getPort(), getUsername(), getPassword()); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
From source file:de.drv.dsrv.spoc.web.manager.impl.SpocNutzdatenManagerImpl.java
@Override public void processResponseNutzdaten(final TransportResponseType transportResponseType) throws SpocNutzdatenManagerException { try {/*w w w .j av a2 s . com*/ // Lese evtl. vorhandene MTOM-Data-ID aus der eXTra-Response final Integer mtomDataId = ExtraHelper.getMtomDataIdFromResponse(transportResponseType); if (mtomDataId != null) { if (LOG.isInfoEnabled()) { LOG.info("Lese Nutzdaten mit der ID " + mtomDataId + " aus der Datenbank."); } // Lade Nutzdaten aus der Datenbank final MtomData mtomData = this.mtomDataDao.get(mtomDataId); if ((mtomData != null) && (mtomData.getNutzdaten() != null)) { // Entferne AnyXML transportResponseType.getTransportBody().getData().setAnyXML(null); // Erstelle neue Base64CharSequence mit DataHandler final Base64CharSequenceType base64CharSequenceType = new Base64CharSequenceType(); base64CharSequenceType .setValue(new DataHandler(new InputStreamDataSource(mtomData.getNutzdaten()))); transportResponseType.getTransportBody().getData() .setBase64CharSequence(base64CharSequenceType); } else { throw new SpocNutzdatenManagerException( "Fehler beim Verarbeiten der eXTra-Response-Nutzdaten; kein Nutzdaten-Eintrag mit der ID " + mtomDataId + " vorhanden."); } } } catch (final Exception e) { if (e instanceof SpocNutzdatenManagerException) { throw (SpocNutzdatenManagerException) e; } else { throw new SpocNutzdatenManagerException("Fehler beim Verarbeiten der eXTra-Response-Nutzdaten.", e); } } }
From source file:com.medsavant.mailer.Mail.java
public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) { try {//from w w w . j a va 2s . co m if (src == null || pw == null || host == null || port == -1) { return false; } if (to.isEmpty()) { return false; } LOG.info("Sending email to " + to + " with subject " + subject); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.user", src); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.auth", auth); props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", fallback); Session session = Session.getInstance(props, null); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(src, srcName)); InternetAddress[] address = InternetAddress.parse(to); msg.setRecipients(Message.RecipientType.BCC, address); msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(text, "text/html"); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (attachment != null) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); mp.addBodyPart(mbp2); } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // send the message Transport transport = session.getTransport("smtp"); transport.connect(host, src, pw); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); LOG.info("Mail sent"); return true; } catch (Exception ex) { ex.printStackTrace(); LOG.error(ex); return false; } }