List of usage examples for org.apache.commons.mail ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(final String data, final String aType) throws IOException
From source file:com.jk.mail.MailInfo.java
/** * Fill email./*ww w. ja v a2s .c o m*/ * * @param email * the email * @throws EmailException * the email exception * @throws IOException * Signals that an I/O exception has occurred. */ public void fillEmail(final MultiPartEmail email) throws EmailException, IOException { email.setHostName(getHost()); email.setSmtpPort(getSmtpPort()); email.addTo(getTo()); email.setFrom(getFrom()); email.setSubject(getSubject()); email.setMsg(getMsg()); email.setSSLOnConnect(isSecured()); if (isRequiresAuthentication()) { email.setAuthentication(getUsername(), getPassword()); } for (int i = 0; i < this.attachements.size(); i++) { final Attachment attachment = this.attachements.get(i); final ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType()); email.attach(ds, attachment.getName(), attachment.getDescription()); } }
From source file:com.itcs.commons.email.impl.RunnableSendHTMLEmail.java
private void addAttachments(MultiPartEmail email, List<EmailAttachment> attachments) throws EmailException { if (attachments != null && attachments.size() > 0) { String maxStringValue = getSession().getProperty(MAX_ATTACHMENTS_SIZE_PROP_NAME); // System.out.println("maxStringValue= " + maxStringValue); long maxAttachmentSize = DISABLE_MAX_ATTACHMENTS_SIZE; try {//w w w .j ava 2s. co m maxAttachmentSize = Long.parseLong(maxStringValue); } catch (NumberFormatException e) { Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.WARNING, "DISABLE_MAX_ATTACHMENTS_SIZE MailSession does not have property " + MAX_ATTACHMENTS_SIZE_PROP_NAME); } long size = 0; for (EmailAttachment attach : attachments) { if (maxAttachmentSize != EmailClient.DISABLE_MAX_ATTACHMENTS_SIZE) { size += attach.getSize(); if (size > maxAttachmentSize) { throw new EmailException( "Adjuntos exceden el tamao maximo permitido (" + maxAttachmentSize + ")," + " pruebe enviando menos archivos adjuntos, o de menor tamao."); } } if (attach.getData() != null) { try { email.attach(new ByteArrayDataSource(attach.getData(), attach.getMimeType()), attach.getName(), attach.getMimeType()); } catch (IOException e) { throw new EmailException("IOException Attachment has errors," + e.getMessage()); } catch (EmailException e) { throw new EmailException("EmailException Attachment has errors," + e.getMessage()); } } else { email.attach(attach); } } } }
From source file:com.webbfontaine.valuewebb.irms.action.mail.MailActionHandler.java
private static ByteArrayDataSource dataSource(InputStream inputStream, String contentType) throws IOException { return new ByteArrayDataSource(inputStream, contentType); }
From source file:com.mirth.connect.connectors.smtp.SmtpMessageDispatcher.java
@Override public void doDispatch(UMOEvent event) throws Exception { monitoringController.updateStatus(connector, connectorType, Event.BUSY); MessageObject mo = messageObjectController.getMessageObjectFromEvent(event); if (mo == null) { return;/*from w ww. j a va 2s.c o m*/ } try { Email email = null; if (connector.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(connector.getCharsetEncoding()); email.setHostName(replacer.replaceValues(connector.getSmtpHost(), mo)); try { email.setSmtpPort(Integer.parseInt(replacer.replaceValues(connector.getSmtpPort(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { email.setSocketConnectionTimeout( Integer.parseInt(replacer.replaceValues(connector.getTimeout(), mo))); } catch (NumberFormatException e) { // Don't set if the value is invalid } if ("SSL".equalsIgnoreCase(connector.getEncryption())) { email.setSSL(true); } else if ("TLS".equalsIgnoreCase(connector.getEncryption())) { email.setTLS(true); } if (connector.isAuthentication()) { email.setAuthentication(replacer.replaceValues(connector.getUsername(), mo), replacer.replaceValues(connector.getPassword(), mo)); } /* * 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 : replaceValuesAndSplit(connector.getTo(), mo)) { email.addTo(to); } // Currently unused for (String cc : replaceValuesAndSplit(connector.cc(), mo)) { email.addCc(cc); } // Currently unused for (String bcc : replaceValuesAndSplit(connector.getBcc(), mo)) { email.addBcc(bcc); } // Currently unused for (String replyTo : replaceValuesAndSplit(connector.getReplyTo(), mo)) { email.addReplyTo(replyTo); } for (Entry<String, String> header : connector.getHeaders().entrySet()) { email.addHeader(replacer.replaceValues(header.getKey(), mo), replacer.replaceValues(header.getValue(), mo)); } email.setFrom(replacer.replaceValues(connector.getFrom(), mo)); email.setSubject(replacer.replaceValues(connector.getSubject(), mo)); String body = replacer.replaceValues(connector.getBody(), mo); if (connector.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 : connector.getAttachments()) { String name = replacer.replaceValues(attachment.getName(), mo); String mimeType = replacer.replaceValues(attachment.getMimeType(), mo); String content = replacer.replaceValues(attachment.getContent(), mo); 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 = content.getBytes(); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = content.getBytes(); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = Base64.decodeBase64(content); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ String response = email.send(); messageObjectController.setSuccess(mo, response, null); } catch (EmailException e) { alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_402, "Error sending email message.", e); messageObjectController.setError(mo, Constants.ERROR_402, "Error sending email message.", e, null); connector.handleException(new Exception(e)); } finally { monitoringController.updateStatus(connector, connectorType, Event.DONE); } }
From source file:annis.gui.ReportBugWindow.java
private boolean sendBugReport(String bugEMailAddress, byte[] screenImage, String imageMimeType) { MultiPartEmail mail = new MultiPartEmail(); try {/*from w w w . jav a 2 s . c o m*/ // server setup mail.setHostName("localhost"); // content of the mail mail.addReplyTo(form.getField("email").getValue().toString(), form.getField("name").getValue().toString()); mail.setFrom(bugEMailAddress); mail.addTo(bugEMailAddress); mail.setSubject("[ANNIS BUG] " + form.getField("summary").getValue().toString()); // TODO: add info about version etc. StringBuilder sbMsg = new StringBuilder(); sbMsg.append("Reporter: ").append(form.getField("name").getValue().toString()).append(" (") .append(form.getField("email").getValue().toString()).append(")\n"); sbMsg.append("Version: ").append(VaadinSession.getCurrent().getAttribute("annis-version")).append("\n"); sbMsg.append("URL: ").append(UI.getCurrent().getPage().getLocation().toASCIIString()).append("\n"); sbMsg.append("\n"); sbMsg.append(form.getField("description").getValue().toString()); mail.setMsg(sbMsg.toString()); if (screenImage != null) { try { mail.attach(new ByteArrayDataSource(screenImage, imageMimeType), "screendump.png", "Screenshot of the browser content at time of bug report"); } catch (IOException ex) { log.error(null, ex); } File logfile = new File(VaadinService.getCurrent().getBaseDirectory(), "/WEB-INF/log/annis-gui.log"); if (logfile.exists() && logfile.isFile() && logfile.canRead()) { mail.attach(new FileDataSource(logfile), "annis-gui.log", "Logfile of the GUI (shared by all users)"); } } mail.send(); return true; } catch (EmailException ex) { Notification.show("E-Mail not configured on server", "If this is no Kickstarter version please ask the adminstrator of this ANNIS-instance for assistance. " + "Bug reports are not available for ANNIS Kickstarter", Notification.Type.ERROR_MESSAGE); log.error(null, ex); return false; } }
From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java
/** * Email//from w w w .ja va2 s . c o m * * @param mail * @return * @throws Exception */ protected Email getEmail(MsunMail mail) throws Exception { if (logger.isDebugEnabled()) { logger.debug("send mail use smth : " + hostName); } // set env for logger mail.getEnvironment().setHostName(hostName); mail.getEnvironment().setUser(user); mail.getEnvironment().setPassword(password); Email email = null; if (!StringUtils.isEmpty(mail.getHtmlMessage())) { email = makeHtmlEmail(mail, mail.getCharset()); } else { if ((mail.getAttachment() == null || mail.getAttachment().length == 0) && mail.getAttachments().isEmpty()) { email = makeSimpleEmail(mail, mail.getCharset()); } else { email = makeSimpleEmailWithAttachment(mail, mail.getCharset()); } } if (auth) { // email.setAuthenticator(new MyAuthenticator(user, password)); email.setAuthentication(user, password); } email.setHostName(hostName); if (mail.getTo() == null) { mail.setTo(defaultTo.split(";")); } if (StringUtils.isEmpty(mail.getFrom())) { mail.setFrom(defaultFrom); } email.setFrom(mail.getFrom(), mail.getFromName()); List<String> unqualifiedReceiver = mail.getUnqualifiedReceiver(); String[] mailTo = mail.getTo(); String[] mailCc = mail.getCc(); String[] mailBcc = mail.getBcc(); if (unqualifiedReceiver != null && unqualifiedReceiver.size() > 0) { if (mailTo != null && mailTo.length > 0) { mailTo = filterReceiver(mailTo, unqualifiedReceiver); } if (mailCc != null && mailCc.length > 0) { mailCc = filterReceiver(mailCc, unqualifiedReceiver); } if (mailBcc != null && mailBcc.length > 0) { mailBcc = filterReceiver(mailBcc, unqualifiedReceiver); } } if (mailTo == null && mailCc == null && mailBcc == null) { throw new MessageSerivceException("?????"); } int count = 0; if (mailTo != null) { count += mailTo.length; for (String to : mailTo) { email.addTo(to); } } if (mailCc != null) { count += mailCc.length; for (String cc : mailCc) { email.addCc(cc); } } if (mailBcc != null) { count += mailBcc.length; for (String bcc : mailBcc) { email.addBcc(bcc); } } if (count < 1) { throw new MessageSerivceException("?????"); } if (!StringUtils.isEmpty(mail.getReplyTo())) { email.addReplyTo(mail.getReplyTo()); } if (mail.getHeaders() != null) { for (Iterator<String> iter = mail.getHeaders().keySet().iterator(); iter.hasNext();) { String key = (String) iter.next(); email.addHeader(key, (String) mail.getHeaders().get(key)); } } email.setSubject(mail.getSubject()); // if (email instanceof MultiPartEmail) { MultiPartEmail multiEmail = (MultiPartEmail) email; if (mail.getAttachments().isEmpty()) { File[] fs = mail.getAttachment(); if (fs != null && fs.length > 0) { for (int i = 0; i < fs.length; i++) { EmailAttachment attachment = new EmailAttachment(); attachment.setPath(fs[i].getAbsolutePath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setName(MimeUtility.encodeText(fs[i].getName()));// ??? multiEmail.attach(attachment); } } } else { for (MsunMailAttachment attachment : mail.getAttachments()) { DataSource ds = new ByteArrayDataSource(attachment.getData(), null); multiEmail.attach(ds, MimeUtility.encodeText(attachment.getName()), null); } } } return email; }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeImageLogo(MimeMultipart mimeMultipart) { BodyPart messageBodyPart;/*from w w w . j a v a2 s . c om*/ ArrayList<String> imageFiles = new ArrayList<String>(); imageFiles.add("tracklogo.gif"); // more images can be added here ArrayList<String> cids = new ArrayList<String>(); cids.add("logo"); // for each image there should be a cid here URL imageURL = null; for (int i = 0; i < imageFiles.size(); ++i) { try { DataSource ds = null; messageBodyPart = new MimeBodyPart(); InputStream in = null; in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i)); int length = imageFiles.get(i).length(); String type = imageFiles.get(i).substring(length - 4, length - 1); if (in != null) { ds = new ByteArrayDataSource(in, "image/" + type); System.err.println(type); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i); imageURL = servletContext.getResource(theResource); ds = new URLDataSource(imageURL); } messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setHeader("Content-ID", cids.get(i)); messageBodyPart.setDisposition("inline"); // add it mimeMultipart.addBodyPart(messageBodyPart); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); // what shall we do here? } } }
From source file:com.adobe.acs.commons.email.EmailServiceImplTest.java
@Test public final void testSendEmailAttachment() throws Exception { final String expectedMessage = "This is just a message"; final String expectedSenderName = "John Smith"; final String expectedSenderEmailAddress = "john@smith.com"; String attachment = "This is a attachment."; String attachmentName = "attachment.txt"; //Subject is provided inside the HtmlTemplate directly final String expectedSubject = "Greetings"; final Map<String, String> params = new HashMap<String, String>(); params.put("message", expectedMessage); params.put("senderName", expectedSenderName); params.put("senderEmailAddress", expectedSenderEmailAddress); final String recipient = "upasanac@acs.com"; Map<String, DataSource> attachments = new HashMap(); attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain")); ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class); List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments, recipient);// ww w .j a v a 2 s . c o m verify(messageGatewayHtmlEmail, times(1)).send(captor.capture()); assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress()); assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal()); assertEquals(expectedSubject, captor.getValue().getSubject()); assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString()); Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer"); getContainer.setAccessible(true); MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue()); getContainer.setAccessible(false); assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString()); //If email is sent to the recipient successfully, the response is an empty failureList assertTrue(failureList.isEmpty()); }
From source file:com.adobe.acs.commons.email.impl.EmailServiceImplTest.java
@Test public final void testSendEmailAttachment() throws Exception { final String expectedMessage = "This is just a message"; final String expectedSenderName = "John Smith"; final String expectedSenderEmailAddress = "john@smith.com"; final String attachment = "This is a attachment."; final String attachmentName = "attachment.txt"; //Subject is provided inside the HtmlTemplate directly final String expectedSubject = "Greetings"; final Map<String, String> params = new HashMap<String, String>(); params.put("message", expectedMessage); params.put("senderName", expectedSenderName); params.put("senderEmailAddress", expectedSenderEmailAddress); final String recipient = "upasanac@acs.com"; Map<String, DataSource> attachments = new HashMap(); attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain")); ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class); final List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments, recipient);// w w w . j a v a 2 s. c o m verify(messageGatewayHtmlEmail, times(1)).send(captor.capture()); assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress()); assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal()); assertEquals(expectedSubject, captor.getValue().getSubject()); assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString()); Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer"); getContainer.setAccessible(true); MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue()); getContainer.setAccessible(false); assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString()); //If email is sent to the recipient successfully, the response is an empty failureList assertTrue(failureList.isEmpty()); }
From source file:com.day.cq.wcm.foundation.forms.impl.MailServlet.java
/** * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse) *//*from ww w .ja v a 2 s.co m*/ protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final MailService localService = this.mailService; if (ResourceUtil.isNonExistingResource(request.getResource())) { logger.debug("Received fake request!"); response.setStatus(500); return; } final ResourceBundle resBundle = request.getResourceBundle(null); final ValueMap values = ResourceUtil.getValueMap(request.getResource()); final String[] mailTo = values.get(MAILTO_PROPERTY, String[].class); int status = 200; if (mailTo == null || mailTo.length == 0 || mailTo[0].length() == 0) { // this is a sanity check logger.error( "The mailto configuration is missing in the form begin at " + request.getResource().getPath()); status = 500; } else if (localService == null) { logger.error("The mail service is currently not available! Unable to send form mail."); status = 500; } else { try { final StringBuilder builder = new StringBuilder(); builder.append(request.getScheme()); builder.append("://"); builder.append(request.getServerName()); if ((request.getScheme().equals("https") && request.getServerPort() != 443) || (request.getScheme().equals("http") && request.getServerPort() != 80)) { builder.append(':'); builder.append(request.getServerPort()); } builder.append(request.getRequestURI()); // construct msg final StringBuilder buffer = new StringBuilder(); String text = resBundle.getString("You've received a new form based mail from {0}."); text = text.replace("{0}", builder.toString()); buffer.append(text); buffer.append("\n\n"); buffer.append(resBundle.getString("Values")); buffer.append(":\n\n"); // we sort the names first - we use the order of the form field and // append all others at the end (for compatibility) // let's get all parameters first and sort them alphabetically! final List<String> contentNamesList = new ArrayList<String>(); final Iterator<String> names = FormsHelper.getContentRequestParameterNames(request); while (names.hasNext()) { final String name = names.next(); contentNamesList.add(name); } Collections.sort(contentNamesList); final List<String> namesList = new ArrayList<String>(); final Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource()); while (fields.hasNext()) { final Resource field = fields.next(); final FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field); for (final FieldDescription desc : descs) { // remove from content names list contentNamesList.remove(desc.getName()); if (!desc.isPrivate()) { namesList.add(desc.getName()); } } } namesList.addAll(contentNamesList); // now add form fields to message // and uploads as attachments final List<RequestParameter> attachments = new ArrayList<RequestParameter>(); for (final String name : namesList) { final RequestParameter rp = request.getRequestParameter(name); if (rp == null) { //see Bug https://bugs.day.com/bugzilla/show_bug.cgi?id=35744 logger.debug("skipping form element {} from mail content because it's not in the request", name); } else if (rp.isFormField()) { buffer.append(name); buffer.append(" : \n"); final String[] pValues = request.getParameterValues(name); for (final String v : pValues) { buffer.append(v); buffer.append("\n"); } buffer.append("\n"); } else if (rp.getSize() > 0) { attachments.add(rp); } else { //ignore } } // if we have attachments we send a multi part, otherwise a simple email final Email email; if (attachments.size() > 0) { buffer.append("\n"); buffer.append(resBundle.getString("Attachments")); buffer.append(":\n"); final MultiPartEmail mpEmail = new MultiPartEmail(); email = mpEmail; for (final RequestParameter rp : attachments) { final ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(), rp.getContentType()); mpEmail.attach(ea, rp.getFileName(), rp.getFileName()); buffer.append("- "); buffer.append(rp.getFileName()); buffer.append("\n"); } } else { email = new SimpleEmail(); } email.setMsg(buffer.toString()); // mailto for (final String rec : mailTo) { email.addTo(rec); } // cc final String[] ccRecs = values.get(CC_PROPERTY, String[].class); if (ccRecs != null) { for (final String rec : ccRecs) { email.addCc(rec); } } // bcc final String[] bccRecs = values.get(BCC_PROPERTY, String[].class); if (bccRecs != null) { for (final String rec : bccRecs) { email.addBcc(rec); } } // subject and from address final String subject = values.get(SUBJECT_PROPERTY, resBundle.getString("Form Mail")); email.setSubject(subject); final String fromAddress = values.get(FROM_PROPERTY, ""); if (fromAddress.length() > 0) { email.setFrom(fromAddress); } if (this.logger.isDebugEnabled()) { this.logger.debug("Sending form activated mail: fromAddress={}, to={}, subject={}, text={}.", new Object[] { fromAddress, mailTo, subject, buffer }); } localService.sendEmail(email); } catch (EmailException e) { logger.error("Error sending email: " + e.getMessage(), e); status = 500; } } // check for redirect String redirectTo = request.getParameter(":redirect"); if (redirectTo != null) { int pos = redirectTo.indexOf('?'); redirectTo = redirectTo + (pos == -1 ? '?' : '&') + "status=" + status; response.sendRedirect(redirectTo); return; } if (FormsHelper.isRedirectToReferrer(request)) { FormsHelper.redirectToReferrer(request, response, Collections.singletonMap("stats", new String[] { String.valueOf(status) })); return; } response.setStatus(status); }