List of usage examples for org.apache.commons.mail ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(final String data, final String aType) throws IOException
From source file:immf.ImodeForwardMail.java
private void attacheFile() throws EmailException { try {/*from w w w . jav a 2 s .c o m*/ List<AttachedFile> files = this.imm.getAttachFileList(); for (AttachedFile f : files) { BodyPart part = createBodyPart(); part.setDataHandler(new DataHandler(new ByteArrayDataSource(f.getData(), f.getContentType()))); Util.setFileName(part, f.getFilename(), this.charset, null); part.setDisposition(BodyPart.ATTACHMENT); getContainer().addBodyPart(part); } } catch (Exception e) { throw new EmailException(e); } }
From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties; String responseData = null;/*from w w w. j a va2 s . c om*/ String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo() + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":" + smtpDispatcherProperties.getSmtpPort(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING, info)); try { Email email = null; if (smtpDispatcherProperties.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charsetEncoding); email.setHostName(smtpDispatcherProperties.getSmtpHost()); try { email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort())); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout()); email.setSocketTimeout(timeout); email.setSocketConnectionTimeout(timeout); } catch (NumberFormatException e) { // Don't set if the value is invalid } // This has to be set before the authenticator because a session shouldn't be created yet configuration.configureEncryption(connectorProperties, email); if (smtpDispatcherProperties.isAuthentication()) { email.setAuthentication(smtpDispatcherProperties.getUsername(), smtpDispatcherProperties.getPassword()); } Properties mailProperties = email.getMailSession().getProperties(); // These have to be set after the authenticator, so that a new mail session isn't created configuration.configureMailProperties(mailProperties); if (smtpDispatcherProperties.isOverrideLocalBinding()) { mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress()); mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort()); } /* * NOTE: There seems to be a bug when calling setTo with a List (throws a * java.lang.ArrayStoreException), so we are using addTo instead. */ for (String to : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) { email.addTo(to); } // Currently unused for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) { email.addCc(cc); } // Currently unused for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) { email.addBcc(bcc); } // Currently unused for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) { email.addReplyTo(replyTo); } for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } email.setFrom(smtpDispatcherProperties.getFrom()); email.setSubject(smtpDispatcherProperties.getSubject()); AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider(); String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(), connectorMessage); if (StringUtils.isNotEmpty(body)) { if (smtpDispatcherProperties.isHtml()) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } } /* * If the MIME type for the attachment is missing, we display a warning and set the * content anyway. If the MIME type is of type "text" or "application/xml", then we add * the content. If it is anything else, we assume it should be Base64 decoded first. */ for (Attachment attachment : smtpDispatcherProperties.getAttachments()) { String name = attachment.getName(); String mimeType = attachment.getMimeType(); String content = attachment.getContent(); byte[] bytes; if (StringUtils.indexOf(mimeType, "/") < 0) { logger.warn("valid MIME type is missing for email attachment: \"" + name + "\", using default of text/plain"); attachment.setMimeType("text/plain"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ responseData = email.send(); responseStatus = Status.SENT; responseStatusMessage = "Email sent successfully."; } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error sending email message", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error sending email message", e); // TODO: Exception handling // connector.handleException(new Exception(e)); } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } return new Response(responseStatus, responseData, responseStatusMessage, responseError); }
From source file:immf.ImodeForwardMail.java
private void attacheInline() throws EmailException { try {/* ww w . j a v a 2 s .c om*/ List<AttachedFile> files = this.imm.getInlineFileList(); for (AttachedFile f : files) { this.embed(new ByteArrayDataSource(f.getData(), f.getContentType()), f.getFilename(), this.charset, f.getId()); } } catch (Exception e) { throw new EmailException(e); } }
From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java
public boolean emailAttachment(String from, String recipient, String subject, String body, byte[] attachData, String attachDataType, String attachFileName, String attachDesc) throws Exception { MultiPartEmail email = new MultiPartEmail(); email.attach(new ByteArrayDataSource(attachData, attachDataType), attachFileName, attachDesc, EmailAttachment.ATTACHMENT); log.debug("Email host: " + host); log.debug("Email port: " + port); log.debug("Email username: " + username); log.debug("Email from: " + from); log.debug("Email to: " + recipient); log.debug("Email Subject is: " + subject); log.debug("Email Body is: " + body); email.setHostName(host);/*from ww w .ja v a2s . c o m*/ email.setSmtpPort(Integer.parseInt(port)); email.setAuthenticator(new DefaultAuthenticator(username, password)); // the method setSSL is deprecated on the newer versions of commons // email... email.setSSL("true".equalsIgnoreCase(ssl)); email.setTLS("true".equalsIgnoreCase(tls)); email.setFrom(from); email.setSubject(subject); email.setMsg(body); if (recipient.indexOf(",") >= 0) { String[] recs = recipient.split(","); for (String rec : recs) { email.addTo(rec); } } else { email.addTo(recipient); } email.send(); return true; }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends the attachment of an email./*from ww w . j av a 2s .c o m*/ */ public static boolean sendEmailAttachment(String from, String to_adrList, String cc_adrList, String subject, String txt, byte[] att_data, String att_name, String att_type) { boolean result = true; try { // Create the email message MultiPartEmail email = new MultiPartEmail(); email.setCharset("UTF-8"); email.setHostName(getSmtpMailRelayHostname()); email.setFrom(from); email.setSubject(subject); email.setMsg(txt); // bounces and reply forwarded to assistance@agnitas.de email.addReplyTo("assistance@agnitas.de"); email.setBounceAddress("assistance@agnitas.de"); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { for (InternetAddress singleAdr : toAddresses) { email.addTo(singleAdr.getAddress()); } } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { for (InternetAddress singleAdr : ccAddresses) { email.addCc(singleAdr.getAddress()); } } // Create and add the attachment ByteArrayDataSource attachment = new ByteArrayDataSource(att_data, att_type); email.attach(attachment, att_name, "EMM-Report"); // send the email email.send(); } catch (Exception e) { logger.error("sendEmailAttachment: " + e.getMessage(), e); result = false; } return result; }
From source file:org.agnitas.util.ImportUtils.java
public static boolean sendEmailWithAttachments(String from, String fromName, String to, String subject, String message, EmailAttachment[] attachments) { boolean result = true; try {// www . j a v a 2s . c om // Create the email message MultiPartEmail email = new MultiPartEmail(); email.setCharset("UTF-8"); email.setHostName(AgnUtils.getDefaultValue("system.mail.host")); email.addTo(to); if (fromName == null || fromName.equals("")) email.setFrom(from); else email.setFrom(from, fromName); email.setSubject(subject); email.setMsg(message); //bounces and reply forwarded to support@agnitas.de String replyName = AgnUtils.getDefaultValue("import.report.replyTo.name"); if (replyName == null || replyName.equals("")) email.addReplyTo(AgnUtils.getDefaultValue("import.report.replyTo.address")); else email.addReplyTo(AgnUtils.getDefaultValue("import.report.replyTo.address"), replyName); email.setBounceAddress(AgnUtils.getDefaultValue("import.report.bounce")); // Create and attach attachments for (EmailAttachment attachment : attachments) { ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getType()); email.attach(dataSource, attachment.getName(), attachment.getDescription()); } // send the email email.send(); } catch (Exception e) { AgnUtils.logger().error("sendEmailAttachment: " + e.getMessage()); result = false; } return result; }
From source file:org.cobbzilla.mail.sender.SmtpMailSender.java
private Email constructEmail(SimpleEmailMessage message) throws EmailException { final Email email; if (message instanceof ICalEvent) { final MultiPartEmail multiPartEmail = new MultiPartEmail(); ICalEvent iCalEvent = (ICalEvent) message; // Calendar iCalendar = new Calendar(); Calendar iCalendar = ICalUtil.newCalendarEvent(iCalEvent.getProdId(), iCalEvent); byte[] attachmentData = ICalUtil.toBytes(iCalendar); String icsName = iCalEvent.getIcsName() + ".ics"; String contentType = "text/calendar; icsName=\"" + icsName + "\""; try {//www . ja v a 2s . com multiPartEmail.attach(new ByteArrayDataSource(attachmentData, contentType), icsName, "", EmailAttachment.ATTACHMENT); } catch (IOException e) { throw new EmailException("constructEmail: couldn't attach: " + e, e); } email = multiPartEmail; } else if (message.getHasHtmlMessage()) { final HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setTextMsg(message.getMessage()); htmlEmail.setHtmlMsg(message.getHtmlMessage()); email = htmlEmail; } else { email = new SimpleEmail(); email.setMsg(message.getMessage()); } return email; }
From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java
public Document createDocument(Ticket ticket, DocumentProperties docProperties) throws RepositoryException, SecurityException { try {// ww w . j ava 2 s . co m call.removeAllParameters(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName("createDocument"); call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("docProperties", XMLType.XSD_ANY, ParameterMode.IN); call.setReturnType(XMLType.XSD_ANY); // Change the binary property for an attachment byte[] content = (byte[]) docProperties.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue(); if (content != null) { docProperties.setProperty(DocumentProperties.DOCUMENT_CONTENT, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream")); call.addAttachmentPart(handler); } Document document = (Document) call.invoke(new Object[] { ticket, docProperties }); return document; } catch (Exception e) { // I don't know if there is a better way to do this AxisFault fault = (AxisFault) e; if (fault.getFaultString().indexOf("SecurityException") != -1) { throw new SecurityException(fault.getFaultString()); } else { throw new RepositoryException(fault.getFaultString()); } } }
From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java
public List createDocuments(Ticket ticket, List properties) throws RepositoryException, SecurityException { try {//from w w w. j ava 2 s.c o m call.removeAllParameters(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName("createDocuments"); call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("properties", XMLType.XSD_ANY, ParameterMode.IN); call.setReturnType(XMLType.XSD_ANY); // TODO: Add N attachments Iterator it = properties.iterator(); while (it.hasNext()) { DocumentProperties props = (DocumentProperties) it.next(); byte[] content = (byte[]) props.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue(); if (content != null) { props.setProperty(DocumentProperties.DOCUMENT_CONTENT, null); DataHandler handler = new DataHandler( new ByteArrayDataSource(content, "application/octet-stream")); call.addAttachmentPart(handler); } } Object[] o = (Object[]) call.invoke(new Object[] { ticket, properties }); ArrayList list = new ArrayList(); CollectionUtils.addAll(list, o); return list; } catch (Exception e) { // I don't know if there is a better way to do this AxisFault fault = (AxisFault) e; if (fault.getFaultString().indexOf("SecurityException") != -1) { throw new SecurityException(fault.getFaultString()); } else { throw new RepositoryException(fault.getFaultString()); } } }
From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java
public Document updateDocument(Ticket ticket, DocumentProperties docProperties) throws RepositoryException, SecurityException, ResourceLockedException { //DefaultRepositoryServiceImpl.getInstance().updateDocument(properties,docId,docProperties); try {/* w w w . ja v a 2 s . c om*/ call.removeAllParameters(); call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName("updateDocument"); call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN); call.addParameter("docProperties", XMLType.XSD_ANY, ParameterMode.IN); call.setReturnType(XMLType.XSD_ANY); // Change the binary property for an attachment byte[] content = (byte[]) docProperties.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue(); if (content != null) { docProperties.setProperty(DocumentProperties.DOCUMENT_CONTENT, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream")); call.addAttachmentPart(handler); } return (Document) call.invoke(new Object[] { ticket, docProperties }); } catch (Exception e) { // I don't know if there is a better way to do this AxisFault fault = (AxisFault) e; if (fault.getFaultString().indexOf("SecurityException") != -1) { throw new SecurityException(fault.getFaultString()); } else if (fault.getFaultString().indexOf("ResourceLockedException") != -1) { // Create a virtual lock for info String docId = docProperties.getProperty(DocumentProperties.DOCUMENT_ID).getValue().toString(); Lock lock = lookForLock(ticket, docId); throw new ResourceLockedException(lock); } else { throw new RepositoryException(fault.getFaultString()); } } }