List of usage examples for org.springframework.mail.javamail MimeMessageHelper addInline
public void addInline(String contentId, Resource resource) throws MessagingException
From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java
protected void embedOutput(MimeMessageHelper messageHelper, ReportOutput output) throws MessagingException, JobExecutionException { /***//from w ww . j a v a 2 s .c o m try { BufferedReader in = new BufferedReader(new FileReader("C:/Users/ichan/Desktop/employee.html")); StringBuffer strBuffer = new StringBuffer(); String strLine; while ((strLine = in.readLine()) != null) { strBuffer = strBuffer.append(strLine + "\n"); } content = strBuffer.toString(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("CONTENT = " + content); ****/ // modify content to use inline images StringBuffer primaryPage = new StringBuffer(new String(output.getData().getData())); 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, "cid:"); } } } messageHelper.setText(primaryPage.toString(), true); // add inline images after setting the text in the main body for (Iterator it = output.getChildren().iterator(); it.hasNext();) { ReportOutput child = (ReportOutput) it.next(); String childName = child.getFilename(); DataContainerResource dataContainerResource = new DataContainerResource(child.getData()); dataContainerResource.setFilename(childName); messageHelper.addInline(childName, dataContainerResource); } }
From source file:com.sfs.dao.EmailMessageDAOImpl.java
/** * Send an email message using the configured Spring sender. On success * record the sent message in the datastore for reporting purposes * * @param emailMessage the email message * * @throws SFSDaoException the SFS dao exception *///from w ww. j a v a2s . co m public final void send(final EmailMessageBean emailMessage) throws SFSDaoException { // Check to see whether the required fields are set (to, from, message) if (StringUtils.isBlank(emailMessage.getTo())) { throw new SFSDaoException("Error recording email: Recipient " + "address required"); } if (StringUtils.isBlank(emailMessage.getFrom())) { throw new SFSDaoException("Error recording email: Email requires " + "a return address"); } if (StringUtils.isBlank(emailMessage.getMessage())) { throw new SFSDaoException("Error recording email: No email " + "message specified"); } if (javaMailSender == null) { throw new SFSDaoException("The EmailMessageDAO has not " + "been configured"); } // Prepare the email message MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = null; if (emailMessage.getHtmlMessage()) { try { helper = new MimeMessageHelper(message, true, "UTF-8"); } catch (MessagingException me) { throw new SFSDaoException("Error preparing email for sending: " + me.getMessage()); } } else { helper = new MimeMessageHelper(message); } if (helper == null) { throw new SFSDaoException("The MimeMessageHelper cannot be null"); } try { if (StringUtils.isNotBlank(emailMessage.getTo())) { StringTokenizer tk = new StringTokenizer(emailMessage.getTo(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addTo(address); } } if (StringUtils.isNotBlank(emailMessage.getCC())) { StringTokenizer tk = new StringTokenizer(emailMessage.getCC(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addCc(address); } } if (StringUtils.isNotBlank(emailMessage.getBCC())) { StringTokenizer tk = new StringTokenizer(emailMessage.getBCC(), ","); while (tk.hasMoreTokens()) { String address = tk.nextToken(); helper.addBcc(address); } } if (StringUtils.isNotBlank(emailMessage.getFrom())) { if (StringUtils.isNotBlank(emailMessage.getFromName())) { try { helper.setFrom(emailMessage.getFrom(), emailMessage.getFromName()); } catch (UnsupportedEncodingException uee) { dataLogger.error("Error setting email from", uee); } } else { helper.setFrom(emailMessage.getFrom()); } } helper.setSubject(emailMessage.getSubject()); helper.setPriority(emailMessage.getPriority()); if (emailMessage.getHtmlMessage()) { final String htmlText = emailMessage.getMessage(); String plainText = htmlText; try { ConvertHtmlToText htmlToText = new ConvertHtmlToText(); plainText = htmlToText.convert(htmlText); } catch (Exception e) { dataLogger.error("Error converting HTML to plain text: " + e.getMessage()); } helper.setText(plainText, htmlText); } else { helper.setText(emailMessage.getMessage()); } helper.setSentDate(emailMessage.getSentDate()); } catch (MessagingException me) { throw new SFSDaoException("Error preparing email for sending: " + me.getMessage()); } // Append any attachments (if an HTML email) if (emailMessage.getHtmlMessage()) { for (String id : emailMessage.getAttachments().keySet()) { final Object reference = emailMessage.getAttachments().get(id); if (reference instanceof File) { try { FileSystemResource res = new FileSystemResource((File) reference); helper.addInline(id, res); } catch (MessagingException me) { dataLogger.error("Error appending File attachment: " + me.getMessage()); } } if (reference instanceof URL) { try { UrlResource res = new UrlResource((URL) reference); helper.addInline(id, res); } catch (MessagingException me) { dataLogger.error("Error appending URL attachment: " + me.getMessage()); } } } } // If not in debug mode send the email if (!debugMode) { deliver(emailMessage, message); } }
From source file:com.epam.ta.reportportal.util.email.EmailService.java
/** * Finish launch notification// w w w . jav a 2 s.c o m * * @param recipients List of recipients * @param url ReportPortal URL * @param launch Launch */ public void sendLaunchFinishNotification(final String[] recipients, final String url, final Launch launch, final Project.Configuration settings) { String subject = String.format(FINISH_LAUNCH_EMAIL_SUBJECT, launch.getName(), launch.getNumber()); MimeMessagePreparator preparator = mimeMessage -> { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "utf-8"); message.setSubject(subject); message.setTo(recipients); setFrom(message); Map<String, Object> email = new HashMap<>(); /* Email fields values */ email.put("name", launch.getName()); email.put("number", String.valueOf(launch.getNumber())); email.put("description", launch.getDescription()); email.put("url", url); /* Launch execution statistics */ email.put("total", launch.getStatistics().getExecutionCounter().getTotal().toString()); email.put("passed", launch.getStatistics().getExecutionCounter().getPassed().toString()); email.put("failed", launch.getStatistics().getExecutionCounter().getFailed().toString()); email.put("skipped", launch.getStatistics().getExecutionCounter().getSkipped().toString()); /* Launch issue statistics global counters */ email.put("productBugTotal", launch.getStatistics().getIssueCounter().getProductBugTotal().toString()); email.put("automationBugTotal", launch.getStatistics().getIssueCounter().getAutomationBugTotal().toString()); email.put("systemIssueTotal", launch.getStatistics().getIssueCounter().getSystemIssueTotal().toString()); email.put("noDefectTotal", launch.getStatistics().getIssueCounter().getNoDefectTotal().toString()); email.put("toInvestigateTotal", launch.getStatistics().getIssueCounter().getToInvestigateTotal().toString()); /* Launch issue statistics custom sub-types */ if (launch.getStatistics().getIssueCounter().getProductBug().entrySet().size() > 1) { Map<StatisticSubType, String> pb = new LinkedHashMap<>(); launch.getStatistics().getIssueCounter().getProductBug().forEach((k, v) -> { if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL)) pb.put(settings.getByLocator(k), v.toString()); }); email.put("pbInfo", pb); } if (launch.getStatistics().getIssueCounter().getAutomationBug().entrySet().size() > 1) { Map<StatisticSubType, String> ab = new LinkedHashMap<>(); launch.getStatistics().getIssueCounter().getAutomationBug().forEach((k, v) -> { if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL)) ab.put(settings.getByLocator(k), v.toString()); }); email.put("abInfo", ab); } if (launch.getStatistics().getIssueCounter().getSystemIssue().entrySet().size() > 1) { Map<StatisticSubType, String> si = new LinkedHashMap<>(); launch.getStatistics().getIssueCounter().getSystemIssue().forEach((k, v) -> { if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL)) si.put(settings.getByLocator(k), v.toString()); }); email.put("siInfo", si); } if (launch.getStatistics().getIssueCounter().getNoDefect().entrySet().size() > 1) { Map<StatisticSubType, String> nd = new LinkedHashMap<>(); launch.getStatistics().getIssueCounter().getNoDefect().forEach((k, v) -> { if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL)) nd.put(settings.getByLocator(k), v.toString()); }); email.put("ndInfo", nd); } if (launch.getStatistics().getIssueCounter().getToInvestigate().entrySet().size() > 1) { Map<StatisticSubType, String> ti = new LinkedHashMap<>(); launch.getStatistics().getIssueCounter().getToInvestigate().forEach((k, v) -> { if (!k.equalsIgnoreCase(IssueCounter.GROUP_TOTAL)) ti.put(settings.getByLocator(k), v.toString()); }); email.put("tiInfo", ti); } String text = templateEngine.merge("finish-launch-template.vm", email); message.setText(text, true); message.addInline("logoimg", new UrlResource(getClass().getClassLoader().getResource(LOGO))); }; this.send(preparator); }
From source file:org.yes.cart.service.mail.impl.MailComposerImpl.java
/** * Add inline resource to mail message.//from ww w . j a v a2s. c om * Resource id will be interpreted as file name in following fashion: filename_ext. * * @param helper MimeMessageHelper, that has mail message * @param htmlTemplate html message template * @param mailTemplateChain physical path to resources * @param shopCode shop code * @param locale locale * @param templateName template name * * @throws javax.mail.MessagingException in case if resource can not be inlined */ void inlineResources(final MimeMessageHelper helper, final String htmlTemplate, final List<String> mailTemplateChain, final String shopCode, final String locale, final String templateName) throws MessagingException, IOException { if (StringUtils.isNotBlank(htmlTemplate)) { final List<String> resourcesIds = getResourcesId(htmlTemplate); if (!resourcesIds.isEmpty()) { for (String resourceId : resourcesIds) { final String resourceFilename = transformResourceIdToFileName(resourceId); final byte[] content = mailTemplateResourcesProvider.getResource(mailTemplateChain, shopCode, locale, templateName, resourceFilename); helper.addInline(resourceId, new ByteArrayResource(content) { @Override public String getFilename() { return resourceFilename; } }); } } } }
From source file:org.yes.cart.service.mail.impl.MailComposerImpl.java
/** * Add inline resource to mail message.// w w w. ja v a 2s.c o m * Resource id will be interpreted as file name in following fashion: filename_ext. * * @param helper MimeMessageHelper, that has mail message * @param mail html message template * * @throws javax.mail.MessagingException in case if resource can not be inlined */ void inlineResources(final MimeMessageHelper helper, final Mail mail) throws MessagingException { if (CollectionUtils.isNotEmpty(mail.getParts())) { for (final MailPart part : mail.getParts()) { final String fileName = part.getFilename(); final String resourceId = part.getResourceId(); helper.addInline(resourceId, new ByteArrayResource(part.getData()) { @Override public String getFilename() { return fileName; } }); } } }
From source file:se.vgregion.webbisar.presentation.WebbisarFlowSupportBean.java
public MailMessageResultBean sendWebbis(final Long webbisId, final MailMessageBean mailMessageBean) throws WebbisNotFoundException { // Validate email adresses first MailMessageResultBean result = validateEmailAddresses(mailMessageBean); if (Boolean.FALSE.equals(result.getSuccess())) { return result; }/*from w w w .j a v a2s. c o m*/ // Validate sender name if (StringUtils.isBlank(mailMessageBean.getSenderName())) { result.setSuccess(Boolean.FALSE); result.setMessage("Namn p avsndare mste anges."); return result; } // use this map to store the information that will be merged into the html template Map<String, String> emailInformation = new HashMap<String, String>(); WebbisBean webbisBean = getWebbis(webbisId, null, null, null, null); Map<Long, String> webbisarIdNames = webbisBean.getMultipleBirthSiblingIdsAndNames(); String messageText = mailMessageBean.getMessage(); if (!StringUtils.isEmpty(messageText)) { messageText = messageText.replace("\r", "").replace("\n", "<br/>"); } // add the current webbis to the list of siblings so that // we have them all in the same Map webbisarIdNames.put(webbisBean.getId(), webbisBean.getName()); // add the message and the base url for html links emailInformation.put("baseUrl", cfg.getExternalBaseUrl()); emailInformation.put("message", messageText); emailInformation.put("senderName", mailMessageBean.getSenderName()); emailInformation.put("senderAddress", mailMessageBean.getSenderAddress()); VelocityContext context = new VelocityContext(); context.put("emailInfo", emailInformation); context.put("webbisInfo", webbisarIdNames); Template template = null; StringWriter msgWriter = null; try { velocityEngine.init(); template = velocityEngine.getTemplate(cfg.getMailTemplate()); msgWriter = new StringWriter(); template.merge(context, msgWriter); } catch (Exception e1) { LOGGER.error("Failed to get/merge velocity template.", e1); result.setSuccess(Boolean.FALSE); result.setMessage("Internt fel, webbis kunde inte skickas."); return result; } String msgText = msgWriter.toString(); // Seems OK, try to send mail... try { InternetAddress fromAddress = null; MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, ENCODING_UTF8); try { fromAddress = new InternetAddress(cfg.getMailFromAddress(), cfg.getMailFromAddressName()); } catch (UnsupportedEncodingException e) { fromAddress = new InternetAddress(cfg.getMailFromAddress()); } helper.setTo(mailMessageBean.getRecipientAddresses().split(",")); helper.setFrom(fromAddress); helper.setSubject(mailMessageBean.getSubject()); helper.setText(msgText, true); // include the vgr logo String logoPath = cfg.getMultimediaFileBaseDir() + "/" + cfg.getMailLogo(); FileSystemResource res = new FileSystemResource(new File(logoPath)); helper.addInline("imageIdentifier", res); mailSender.send(mimeMessage); } catch (MailException ex) { LOGGER.error("Failed to create/send mail.", ex); result.setSuccess(Boolean.FALSE); result.setMessage("Internt fel, webbis kunde inte skickas."); return result; } catch (MessagingException e) { LOGGER.error("Failed to create/send mail.", e); result.setSuccess(Boolean.FALSE); result.setMessage("Internt fel, webbis kunde inte skickas."); return result; } // ...and all was well... result.setSuccess(Boolean.TRUE); result.setMessage("Webbis skickad!"); return result; }