List of usage examples for org.springframework.mail.javamail MimeMessageHelper addAttachment
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) throws MessagingException
From source file:com.cubusmail.mail.MessageHandler.java
/** * @throws MessagingException/* ww w . j av a 2s . c o m*/ * @throws IOException */ private void buildBodyContent() throws MessagingException, IOException { boolean hasAttachments = (this.composeAttachments != null && this.composeAttachments.size() > 0); boolean multipart = hasAttachments || isHtmlMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(this.message, multipart); if (isHtmlMessage()) { String plainText = MessageTextUtil.convertHtml2PlainText(this.messageTextHtml); messageHelper.setText(plainText, this.messageTextHtml); } else { messageHelper.setText(this.messageTextPlain, false); } if (hasAttachments) { for (DataSource attachment : this.composeAttachments) { messageHelper.addAttachment(attachment.getName(), attachment); } } if (!isRead()) { this.message.setFlag(Flags.Flag.SEEN, true); } }
From source file:com.seer.datacruncher.utils.mail.MailService.java
public void sendMail(MailConfig mailConfig) throws Exception { String logMsg = "MailService:sendMail():"; InputStream attachment = null; MimeMessage mimeMessage = null;/*from ww w .j av a2s. com*/ MimeMessageHelper helper = null; try { mimeMessage = mailSender.createMimeMessage(); helper = new MimeMessageHelper(mimeMessage, true); helper.setText(mailConfig.getText(), true); if (StringUtils.isEmpty(mailConfig.getMailTo())) { log.error("Invalid or empty 'toAddress' configured!!"); throw new Exception("Invalid or empty 'toAddress' configured"); } if (StringUtils.isEmpty(mailConfig.getMailFrom())) { log.error("Invalid or empty 'FromAddress' configured!!"); throw new Exception("Invalid or empty 'FromAddress' configured"); } if (!isEmailValid(mailConfig.getMailFrom())) { log.error("Invalid 'FromAddress' configured!!"); throw new Exception("Invalid 'FromAddress' configured"); } helper.setFrom(new InternetAddress(mailConfig.getMailFrom())); helper.setSubject(mailConfig.getSubject()); helper.setTo(getToAddress(mailConfig.getMailTo())); attachment = mailConfig.getAttachment(); if (attachment != null) { StreamAttachmentDataSource datasource = new StreamAttachmentDataSource(mailConfig.getAttachment()); helper.addAttachment(mailConfig.getAttachmentName(), datasource); } this.mailSender.send(mimeMessage); } catch (AuthenticationFailedException afex) { log.error(logMsg + "AuthenticationFailedException:", afex); throw new Exception("AuthenticationFailedException", afex); } catch (MessagingException mex) { log.error(logMsg + "Exception:", mex); throw new Exception("MessagingException", mex); } catch (Exception ex) { log.error(logMsg + "Exception:", ex); throw ex; } }
From source file:org.opentides.eventhandler.EmailHandler.java
public void sendEmail(String[] to, String[] cc, String[] bcc, String replyTo, String subject, String body, File[] attachments) {//from w ww .j av a 2s.c o m try { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setTo(toInetAddress(to)); InternetAddress[] ccAddresses = toInetAddress(cc); if (ccAddresses != null) mimeMessageHelper.setCc(ccAddresses); InternetAddress[] bccAddresses = toInetAddress(bcc); if (bccAddresses != null) mimeMessageHelper.setBcc(bccAddresses); if (!StringUtil.isEmpty(replyTo)) mimeMessageHelper.setReplyTo(replyTo); Map<String, Object> templateVariables = new HashMap<String, Object>(); templateVariables.put("message-title", subject); templateVariables.put("message-body", body); StringWriter writer = new StringWriter(); VelocityEngineUtils.mergeTemplate(velocityEngine, mailVmTemplate, "UTF-8", templateVariables, writer); mimeMessageHelper.setFrom(new InternetAddress(this.fromEmail, this.fromName)); mimeMessageHelper.setSubject(subject); mimeMessageHelper.setText(writer.toString(), true); // check for attachment if (attachments != null && attachments.length > 0) { for (File attachment : attachments) { mimeMessageHelper.addAttachment(attachment.getName(), attachment); } } /** * The name of the identifier should be image * the number after the image name is the counter * e.g. <img src="cid:image1" /> */ if (imagesPath != null && imagesPath.size() > 0) { int x = 1; for (String path : imagesPath) { FileSystemResource res = new FileSystemResource(new File(path)); String imageName = "image" + x; mimeMessageHelper.addInline(imageName, res); x++; } } javaMailSender.send(mimeMessage); } catch (MessagingException e) { _log.error(e, e); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } }
From source file:eu.openanalytics.shinyproxy.controllers.IssueController.java
public void sendSupportMail(IssueForm form, Proxy proxy) { String supportAddress = getSupportAddress(); if (supportAddress == null) throw new RuntimeException("Cannot send mail: no support address configured"); if (mailSender == null) throw new RuntimeException("Cannot send mail: no smtp settings configured"); try {//w w w . jav a 2s. c o m MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); // Headers helper.setFrom(environment.getProperty("proxy.support.mail-from-address", "issues@shinyproxy.io")); helper.addTo(supportAddress); helper.setSubject("ShinyProxy Error Report"); // Body StringBuilder body = new StringBuilder(); String lineSep = System.getProperty("line.separator"); body.append(String.format("This is an error report generated by ShinyProxy%s", lineSep)); body.append(String.format("User: %s%s", form.userName, lineSep)); if (form.appName != null) body.append(String.format("App: %s%s", form.appName, lineSep)); if (form.currentLocation != null) body.append(String.format("Location: %s%s", form.currentLocation, lineSep)); if (form.customMessage != null) body.append(String.format("Message: %s%s", form.customMessage, lineSep)); helper.setText(body.toString()); // Attachments (only if container-logging is enabled) if (logService.isLoggingEnabled() && proxy != null) { Path[] filePaths = logService.getLogFiles(proxy); for (Path p : filePaths) { if (Files.exists(p)) helper.addAttachment(p.toFile().getName(), p.toFile()); } } mailSender.send(message); } catch (Exception e) { throw new RuntimeException("Failed to send email", e); } }
From source file:uk.ac.gda.dls.client.feedback.FeedbackDialog.java
@Override protected void createButtonsForButtonBar(Composite parent) { GridData data = new GridData(SWT.FILL, SWT.FILL, false, true, 4, 1); GridLayout layout = new GridLayout(5, false); parent.setLayoutData(data);//from w ww . j av a 2 s . c o m parent.setLayout(layout); Button attachButton = new Button(parent, SWT.TOGGLE); attachButton.setText("Attach File(s)"); attachButton.setToolTipText("Add files to feedback"); final Button screenGrabButton = new Button(parent, SWT.CHECK); screenGrabButton.setText("Include Screenshot"); screenGrabButton.setToolTipText("Send screenshot with feedback"); Label space = new Label(parent, SWT.NONE); space.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true)); Button sendButton = new Button(parent, SWT.PUSH); sendButton.setText("Send"); Button cancelButton = new Button(parent, SWT.PUSH); cancelButton.setText("Cancel"); sendButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final String name = nameText.getText(); final String email = emailText.getText(); final String subject = subjectText.getText(); final String description = descriptionText.getText(); fileList = attachedFileList.getItems(); Job job = new Job("Send feedback email") { @Override protected IStatus run(IProgressMonitor monitor) { try { final String recipientsProperty = LocalProperties.get("gda.feedback.recipients", "dag-group@diamond.ac.uk"); final String[] recipients = recipientsProperty.split(" "); for (int i = 0; i < recipients.length; i++) { recipients[i] = recipients[i].trim(); } final String from = String.format("%s <%s>", name, email); final String beamlineName = LocalProperties.get("gda.beamline.name", "Beamline Unknown"); final String mailSubject = String.format("[GDA feedback - %s] %s", beamlineName.toUpperCase(), subject); final String smtpHost = LocalProperties.get("gda.feedback.smtp.host", "localhost"); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(smtpHost); MimeMessage message = mailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message, (FeedbackDialog.this.hasFiles && fileList.length > 0) || FeedbackDialog.this.screenshot); helper.setFrom(from); helper.setTo(recipients); helper.setSubject(mailSubject); helper.setText(description); if (FeedbackDialog.this.screenshot) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { String fileName = "/tmp/feedbackScreenshot.png"; try { captureScreen(fileName); FileSystemResource file = new FileSystemResource(new File(fileName)); helper.addAttachment(file.getFilename(), file); } catch (Exception e) { logger.error("Could not attach screenshot to feedback", e); } } }); } if (FeedbackDialog.this.hasFiles) { for (String fileName : fileList) { FileSystemResource file = new FileSystemResource(new File(fileName)); helper.addAttachment(file.getFilename(), file); } } {//required to workaround class loader issue with "no object DCH..." error MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap( "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap( "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); CommandMap.setDefaultCommandMap(mc); } mailSender.send(message); return Status.OK_STATUS; } catch (Exception ex) { logger.error("Could not send feedback", ex); return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 1, "Error sending email", ex); } } }; job.schedule(); setReturnCode(OK); close(); } }); cancelButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setReturnCode(CANCEL); close(); } }); attachButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { hasFiles = !hasFiles; GridData data = ((GridData) attachments.getLayoutData()); data.exclude = !hasFiles; attachments.setVisible(hasFiles); topParent.layout(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); screenGrabButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { screenshot = ((Button) e.widget).getSelection(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java
protected void attachOutputs(ReportExecutionJob job, MimeMessageHelper messageHelper, List reportOutputs) throws MessagingException, JobExecutionException { String attachmentName = null; DataContainer attachmentData = job.createDataContainer(); boolean close = true; ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream()); try {/*from w ww . j a v a 2s . c om*/ for (Iterator it = reportOutputs.iterator(); it.hasNext();) { ReportOutput output = (ReportOutput) it.next(); if (attachmentName == null) attachmentName = removeExtension(output.getFilename()) + ".zip"; zipOutput(job, output, zipOut); } zipOut.finish(); zipOut.flush(); close = false; zipOut.close(); } catch (IOException e) { throw new JSExceptionWrapper(e); } finally { if (close) { try { zipOut.close(); } catch (IOException e) { log.error("Error closing stream", e); } } } try { attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null); } catch (UnsupportedEncodingException e) { throw new JSExceptionWrapper(e); } messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData)); }
From source file:edu.unc.lib.dl.services.MailNotifier.java
/** * @param e// www.ja v a 2s . c o m * @param user */ public void sendIngestFailureNotice(Throwable ex, IngestProperties props) { String html = null, text = null; MimeMessage mimeMessage = null; boolean logEmail = true; try { // create templates Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestFailHtml.ftl", Locale.getDefault(), "utf-8"); Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestFailText.ftl", Locale.getDefault(), "utf-8"); if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) { ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true); } // create mail message mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED); // put data into the model HashMap<String, Object> model = new HashMap<String, Object>(); model.put("irBaseUrl", this.irBaseUrl); /* List<ContainerPlacement> tops = new ArrayList<ContainerPlacement>(); tops.addAll(props.getContainerPlacements().values()); model.put("tops", tops);*/ if (ex != null && ex.getMessage() != null) { model.put("message", ex.getMessage()); } else if (ex != null) { model.put("message", ex.toString()); } else { model.put("message", "No exception or error message available."); } // specific exception processing if (ex instanceof FilesDoNotMatchManifestException) { model.put("FilesDoNotMatchManifestException", ex); } else if (ex instanceof InvalidMETSException) { model.put("InvalidMETSException", ex); InvalidMETSException ime = (InvalidMETSException) ex; if (ime.getSvrl() != null) { Document jdomsvrl = ((InvalidMETSException) ex).getSvrl(); DOMOutputter domout = new DOMOutputter(); try { org.w3c.dom.Document svrl = domout.output(jdomsvrl); model.put("svrl", NodeModel.wrap(svrl)); // also dump SVRL to attachment message.addAttachment("schematron-output.xml", new JDOMStreamSource(jdomsvrl)); } catch (JDOMException e) { throw new Error(e); } } } else if (ex instanceof METSParseException) { log.debug("putting MPE in the model"); model.put("METSParseException", ex); } else { log.debug("IngestException without special email treatment", ex); } // attach error xml if available if (ex instanceof IngestException) { IngestException ie = (IngestException) ex; if (ie.getErrorXML() != null) { message.addAttachment("error.xml", new JDOMStreamSource(ie.getErrorXML())); } } model.put("user", props.getSubmitter()); model.put("irBaseUrl", this.irBaseUrl); StringWriter sw = new StringWriter(); htmlTemplate.process(model, sw); html = sw.toString(); sw = new StringWriter(); textTemplate.process(model, sw); text = sw.toString(); // Addressing: to initiator if a person, otherwise to all members of // admin group if (props.getEmailRecipients() != null) { for (String r : props.getEmailRecipients()) { message.addTo(r); } } message.addTo(this.getAdministratorAddress(), "CDR Administrator"); message.setSubject("CDR ingest failed"); message.setFrom(this.getRepositoryFromAddress()); message.setText(text, html); // attach Events XML // if (aip != null) { // /message.addAttachment("events.xml", new JDOMStreamSource(aip.getEventLogger().getAllEvents())); // } this.mailSender.send(mimeMessage); logEmail = false; } catch (MessagingException e) { log.error("Unable to send ingest fail email.", e); } catch (MailSendException e) { log.error("Unable to send ingest fail email.", e); } catch (UnsupportedEncodingException e) { log.error("Unable to send ingest fail email.", e); } catch (IOException e1) { throw new Error("Unable to load email template for Ingest Failure", e1); } catch (TemplateException e) { throw new Error("There was a problem loading FreeMarker templates for email notification", e); } finally { if (mimeMessage != null && logEmail) { try { mimeMessage.writeTo(System.out); } catch (Exception e) { log.error("Could not log email message after error.", e); } } } }
From source file:org.brushingbits.jnap.email.Email.java
public void prepare(MimeMessage mimeMessage) throws Exception { final EmailAccountInfo acc = getAccountInfo(); boolean multipart = StringUtils.isNotBlank(getHtmlText()) || (getInlineResources() != null && getInlineResources().size() > 0) || (getAttachments() != null && getAttachments().size() > 0); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart); helper.setTo(getTo());// w ww . ja v a 2s . c o m if (getCc() != null) { helper.setCc(getCc()); } if (getBcc() != null) { helper.setBcc(getBcc()); } helper.setSentDate(new Date()); helper.setSubject(i18nTextProvider.getText(getSubject())); // sender info // if (acc != null && StringUtils.isNotBlank(acc.getFromName())) { // helper.setFrom(getFrom(), i18nTextProvider.getText(acc.getFromName())); // } else { // helper.setFrom(getFrom()); // } if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) { if (StringUtils.isNotBlank(acc.getReplyToName())) { helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName()); } else { helper.setReplyTo(acc.getReplyToEmailAddress()); } } final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText()); final boolean hasText = StringUtils.isNotBlank(getText()); if (hasHtmlText && hasText) { helper.setText(getText(), getHtmlText()); } else if (hasHtmlText || hasText) { helper.setText(hasHtmlText ? getHtmlText() : getText()); } // add inline resources final Map<String, Resource> inlineRes = this.getInlineResources(); if (inlineRes != null) { for (String cid : inlineRes.keySet()) { helper.addInline(cid, inlineRes.get(cid)); } } // add attachments final Map<String, Resource> attachments = this.getAttachments(); if (attachments != null) { for (String attachmentName : attachments.keySet()) { helper.addAttachment(attachmentName, attachments.get(attachmentName)); } } }
From source file:org.jnap.core.email.Email.java
public void prepare(MimeMessage mimeMessage) throws Exception { final EmailAccountInfo acc = getAccountInfo(); boolean multipart = StringUtils.isNotBlank(getHtmlText()) || (getInlineResources() != null && getInlineResources().size() > 0) || (getAttachments() != null && getAttachments().size() > 0); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart); if (acc.getFromName() != null) { helper.setFrom(acc.getFromEmailAddress(), acc.getFromName()); } else {/*from w w w. ja va 2 s . co m*/ this.setFrom(acc.getFromEmailAddress()); } helper.setTo(getTo()); if (getCc() != null) { helper.setCc(getCc()); } if (getBcc() != null) { helper.setBcc(getBcc()); } helper.setSentDate(new Date()); mimeMessage.setSubject(getMessage(getSubject()), this.encoding); // sender info if (acc != null && StringUtils.isNotBlank(acc.getFromName())) { helper.setFrom(acc.getFromEmailAddress(), getMessage(acc.getFromName())); } else { helper.setFrom(acc.getFromEmailAddress()); } if (acc != null && StringUtils.isNotBlank(acc.getReplyToEmailAddress())) { if (StringUtils.isNotBlank(acc.getReplyToName())) { helper.setReplyTo(acc.getReplyToEmailAddress(), acc.getReplyToName()); } else { helper.setReplyTo(acc.getReplyToEmailAddress()); } } final boolean hasHtmlText = StringUtils.isNotBlank(getHtmlText()); final boolean hasText = StringUtils.isNotBlank(getText()); if (hasHtmlText && hasText) { helper.setText(getText(), getHtmlText()); } else if (hasHtmlText || hasText) { helper.setText(hasHtmlText ? getHtmlText() : getText()); } // set headers final Map<String, String> mailHeaders = this.getHeaders(); for (String header : mailHeaders.keySet()) { mimeMessage.addHeader(header, mailHeaders.get(header)); } // add inline resources final Map<String, Resource> inlineRes = this.getInlineResources(); if (inlineRes != null) { for (String cid : inlineRes.keySet()) { helper.addInline(cid, inlineRes.get(cid)); } } // add attachments final Map<String, Resource> attachments = this.getAttachments(); if (attachments != null) { for (String attachmentName : attachments.keySet()) { helper.addAttachment(attachmentName, attachments.get(attachmentName)); } } }
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java
protected void attachOutput(ReportExecutionJob job, MimeMessageHelper messageHelper, ReportOutput output, boolean useZipFormat) throws MessagingException, JobExecutionException { String attachmentName;/*from ww w . ja v a 2 s. c om*/ DataContainer attachmentData; if (output.getChildren().isEmpty()) { attachmentName = output.getFilename(); attachmentData = output.getData(); } else if (useZipFormat) { // use zip format attachmentData = job.createDataContainer(); boolean close = true; ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream()); try { zipOutput(job, output, zipOut); zipOut.finish(); zipOut.flush(); close = false; zipOut.close(); } catch (IOException e) { throw new JSExceptionWrapper(e); } finally { if (close) { try { zipOut.close(); } catch (IOException e) { log.error("Error closing stream", e); } } } attachmentName = output.getFilename() + ".zip"; } else { // NO ZIP FORMAT attachmentName = output.getFilename(); try { attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null); } catch (UnsupportedEncodingException e) { throw new JSExceptionWrapper(e); } StringBuffer primaryPage = null; for (Iterator it = output.getChildren().iterator(); it.hasNext();) { ReportOutput child = (ReportOutput) it.next(); String childName = child.getFilename(); // NOTE: add the ".dat" extension to all image resources // email client will automatically append ".dat" extension to all the files with no extension // should do it in JasperReport side if (output.getFileType().equals(ContentResource.TYPE_HTML)) { if (primaryPage == null) primaryPage = new StringBuffer(new String(output.getData().getData())); int fromIndex = 0; while ((fromIndex = primaryPage.indexOf("src=\"" + childName + "\"", fromIndex)) > 0) { primaryPage.insert(fromIndex + 5 + childName.length(), ".dat"); } childName = childName + ".dat"; } try { childName = MimeUtility.encodeWord(childName, job.getCharacterEncoding(), null); } catch (UnsupportedEncodingException e) { throw new JSExceptionWrapper(e); } messageHelper.addAttachment(childName, new DataContainerResource(child.getData())); } if (primaryPage == null) { messageHelper.addAttachment(attachmentName, new DataContainerResource(output.getData())); } else { messageHelper.addAttachment(attachmentName, new DataContainerResource(new MemoryDataContainer(primaryPage.toString().getBytes()))); } return; } try { attachmentName = MimeUtility.encodeWord(attachmentName, job.getCharacterEncoding(), null); } catch (UnsupportedEncodingException e) { throw new JSExceptionWrapper(e); } messageHelper.addAttachment(attachmentName, new DataContainerResource(attachmentData)); }