List of usage examples for org.springframework.mail.javamail MimeMessageHelper setText
public void setText(String plainText, String htmlText) throws MessagingException
From source file:org.jresponder.message.MessageRefImpl.java
/** * Render a message in the context of a particular subscriber * and subscription./*from w w w . j a v a 2 s . c om*/ */ @Override public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber, Subscription aSubscription) { try { // prepare context Map<String, Object> myRenderContext = new HashMap<String, Object>(); myRenderContext.put("subscriber", aSubscriber); myRenderContext.put("subscription", aSubscription); myRenderContext.put("config", aSendConfig); myRenderContext.put("message", this); // render the whole file String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext); // now parse again with Jsoup Document myDocument = Jsoup.parse(myRenderedFileContents); String myHtmlBody = ""; String myTextBody = ""; // html body Elements myBodyElements = myDocument.select("#htmlbody"); if (!myBodyElements.isEmpty()) { myHtmlBody = myBodyElements.html(); } // text body Elements myJrTextBodyElements = myDocument.select("#textbody"); if (!myJrTextBodyElements.isEmpty()) { myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first()); } // now build the actual message MimeMessage myMimeMessage = aMimeMessage; // wrap it in a MimeMessageHelper - since some things are easier with that MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage); // set headers // subject myMimeMessageHelper.setSubject(TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext)); // TODO: implement DKIM, figure out subetha String mySenderEmailPattern = aSendConfig.getSenderEmailPattern(); String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext); myMimeMessage.setSender(new InternetAddress(mySenderEmail)); myMimeMessageHelper.setTo(aSubscriber.getEmail()); // from myMimeMessageHelper.setFrom( TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext), TextRenderUtil.getInstance() .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext)); // see how to set body // if we have both text and html, then do multipart if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) { // create wrapper multipart/alternative part MimeMultipart ma = new MimeMultipart("alternative"); myMimeMessage.setContent(ma); // create the plain text BodyPart plainText = new MimeBodyPart(); plainText.setText(myTextBody); ma.addBodyPart(plainText); // create the html part BodyPart html = new MimeBodyPart(); html.setContent(myHtmlBody, "text/html"); ma.addBodyPart(html); } // if only HTML, then just use that else if (myHtmlBody.trim().length() > 0) { myMimeMessageHelper.setText(myHtmlBody, true); } // if only text, then just use that else if (myTextBody.trim().length() > 0) { myMimeMessageHelper.setText(myTextBody, false); } // if neither text nor HTML, then the message is being skipped, // so we just return null else { return false; } return true; } catch (MessagingException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
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 ww w . jav a2 s .c o 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:edu.unc.lib.dl.services.MailNotifier.java
/** * @param e/*from w w w . j ava 2 s . co 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:au.org.theark.core.service.ArkCommonServiceImpl.java
public void sendEmail(final SimpleMailMessage simpleMailMessage) throws MailSendException, VelocityException { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(simpleMailMessage.getTo()); // The "from" field is required if (simpleMailMessage.getFrom() == null) { simpleMailMessage.setFrom(Constants.ARK_ADMIN_EMAIL); }/*from w w w . j a v a 2 s . c o m*/ message.setFrom(simpleMailMessage.getFrom()); message.setSubject(simpleMailMessage.getSubject()); // Map all the fields for the email template Map<String, Object> model = new HashMap<String, Object>(); // Add the host name into the footer of the email String host = InetAddress.getLocalHost().getHostName(); // Message title model.put("title", "Message from The ARK"); // Message header model.put("header", "Message from The ARK"); // Message subject model.put("subject", simpleMailMessage.getSubject()); // Message text model.put("text", simpleMailMessage.getText()); // Hostname in message footer model.put("host", host); // TODO: Add inline image(s)?? // Add inline image header // FileSystemResource res = new FileSystemResource(new // File("c:/Sample.jpg")); // message.addInline("bgHeaderImg", res); // Set up the email text String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "au/org/theark/core/velocity/resetPasswordEmail.vm", model); message.setText(text, true); } }; // send out the email javaMailSender.send(preparator); }
From source file:com.epam.ta.reportportal.util.email.EmailService.java
/** * Finish launch notification//from ww w . j a v a 2s . co 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:com.glaf.mail.MailSenderImpl.java
public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception { if (StringUtils.isEmpty(mailMessage.getMessageId())) { mailMessage.setMessageId(UUID32.getUUID()); }/*from ww w . j ava 2s .co m*/ mailHelper = new MxMailHelper(); MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true); if (StringUtils.isNotEmpty(mailMessage.getFrom())) { messageHelper.setFrom(mailMessage.getFrom()); mailFrom = mailMessage.getFrom(); } else { if (StringUtils.isEmpty(mailFrom)) { mailFrom = MailProperties.getString("mail.mailFrom"); } messageHelper.setFrom(mailFrom); } logger.debug("mailFrom:" + mailFrom); if (mailMessage.getTo() != null) { messageHelper.setTo(mailMessage.getTo()); } if (mailMessage.getCc() != null) { messageHelper.setCc(mailMessage.getCc()); } if (mailMessage.getBcc() != null) { messageHelper.setBcc(mailMessage.getBcc()); } if (mailMessage.getReplyTo() != null) { messageHelper.setReplyTo(mailMessage.getReplyTo()); } String mailSubject = mailMessage.getSubject(); if (mailSubject == null) { mailSubject = ""; } if (mailSubject != null) { // mailSubject = MimeUtility.encodeText(new // String(mailSubject.getBytes(), encoding), encoding, "B"); mailSubject = MimeUtility.encodeWord(mailSubject); } mimeMessage.setSubject(mailSubject); Map<String, Object> dataMap = mailMessage.getDataMap(); if (dataMap == null) { dataMap = new java.util.HashMap<String, Object>(); } String serviceUrl = SystemConfig.getServiceUrl(); logger.debug("mailSubject:" + mailSubject); logger.debug("serviceUrl:" + serviceUrl); if (serviceUrl != null) { String loginUrl = serviceUrl + "/mx/login"; String mainUrl = serviceUrl + "/mx/main"; logger.debug("loginUrl:" + loginUrl); dataMap.put("loginUrl", loginUrl); dataMap.put("mainUrl", mainUrl); } mailMessage.setDataMap(dataMap); if (StringUtils.isEmpty(mailMessage.getContent())) { Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId()); if (template != null) { String templateType = template.getTemplateType(); logger.debug("templateType:" + templateType); // logger.debug("content:" + template.getContent()); if (StringUtils.equals(templateType, "eml")) { if (template.getContent() != null) { Mail m = mailHelper.getMail(template.getContent().getBytes()); String content = m.getContent(); if (StringUtils.isNotEmpty(content)) { template.setContent(content); try { Writer writer = new StringWriter(); TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer); String text = writer.toString(); writer.close(); writer = null; mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } else { try { String text = TemplateUtils.process(dataMap, template.getContent()); mailMessage.setContent(text); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } if (StringUtils.isNotEmpty(mailMessage.getContent())) { String text = mailMessage.getContent(); if (StringUtils.isNotEmpty(callbackUrl)) { String href = callbackUrl + "?messageId=" + mailMessage.getMessageId(); text = mailHelper.embedCallbackScript(text, href); mailMessage.setContent(text); logger.debug(text); messageHelper.setText(text, true); } messageHelper.setText(text, true); } logger.debug("mail body:" + mailMessage.getContent()); Collection<Object> files = mailMessage.getFiles(); if (files != null && !files.isEmpty()) { Iterator<Object> iterator = files.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); if (object instanceof java.io.File) { java.io.File file = (java.io.File) object; FileSystemResource resource = new FileSystemResource(file); String name = file.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, resource); logger.debug("add attachment:" + name); } else if (object instanceof DataSource) { DataSource dataSource = (DataSource) object; String name = dataSource.getName(); name = MailTools.chineseStringToAscii(name); messageHelper.addAttachment(name, dataSource); logger.debug("add attachment:" + name); } else if (object instanceof DataFile) { DataFile dataFile = (DataFile) object; if (StringUtils.isNotEmpty(dataFile.getFilename())) { String name = dataFile.getFilename(); name = MailTools.chineseStringToAscii(name); InputStreamSource inputStreamSource = new MxMailInputSource(dataFile); messageHelper.addAttachment(name, inputStreamSource); logger.debug("add attachment:" + name); } } } } mimeMessage.setSentDate(new java.util.Date()); javaMailSender.send(mimeMessage); logger.info("-----------------------------------------"); logger.info("????"); logger.info("-----------------------------------------"); }
From source file:nl.strohalm.cyclos.utils.MailHandler.java
private void doSend(final String subject, final InternetAddress replyTo, final InternetAddress to, final String body, final boolean isHTML, final boolean throwException) { if (to == null || StringUtils.isEmpty(to.getAddress())) { return;/* w w w .ja v a 2 s.co m*/ } final LocalSettings localSettings = settingsService.getLocalSettings(); final MailSettings mailSettings = settingsService.getMailSettings(); final JavaMailSender mailSender = mailSettings.getMailSender(); final MimeMessage message = mailSender.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(message, localSettings.getCharset()); try { helper.setFrom(getSystemAddress()); if (replyTo != null) { helper.setReplyTo(replyTo); } helper.setTo(to); helper.setSubject(subject); helper.setText(body, isHTML); mailSender.send(message); } catch (final MessagingException e) { if (throwException) { throw new MailSendingException(subject, e); } // Store the current Exception CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } catch (final MailException e) { if (throwException) { throw new MailSendingException(subject, e); } CurrentTransactionData.setMailError(new MailSendingException(subject, e)); } }
From source file:ome.services.mail.MailUtil.java
/** * Main method which takes typical email fields as arguments, to prepare and * populate the given new MimeMessage instance and send. * * @param from/*w ww .j a va 2 s . com*/ * email address message is sent from * @param to * email address message is sent to * @param topic * topic of the message * @param body * body of the message * @param html * flag determines the content type to apply. * @param ccrecipients * list of email addresses message is sent as copy to * @param bccrecipients * list of email addresses message is sent as blind copy to */ public void sendEmail(final String from, final String to, final String topic, final String body, final boolean html, final List<String> ccrecipients, final List<String> bccrecipients) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setText(body, html); message.setFrom(from); message.setSubject(topic); message.setTo(to); if (ccrecipients != null && !ccrecipients.isEmpty()) { message.setCc(ccrecipients.toArray(new String[ccrecipients.size()])); } if (bccrecipients != null && !bccrecipients.isEmpty()) { message.setCc(bccrecipients.toArray(new String[bccrecipients.size()])); } } }; this.mailSender.send(preparator); }
From source file:org.akaza.openclinica.control.core.SecureController.java
License:asdf
public Boolean sendEmail(String to, String from, String subject, String body, Boolean htmlEmail, String successMessage, String failMessage, Boolean sendMessage) throws Exception { Boolean messageSent = true;/*from w w w . j a va 2 s.c o m*/ try { JavaMailSenderImpl mailSender = (JavaMailSenderImpl) SpringServletAccess.getApplicationContext(context) .getBean("mailSender"); // @pgawade 09-Feb-2012 #issue 13201 - setting the "mail.smtp.localhost" property to localhost when java API // is not able to // retrieve the host name Properties javaMailProperties = mailSender.getJavaMailProperties(); if (null != javaMailProperties) { if (javaMailProperties.get("mail.smtp.localhost") == null || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) { javaMailProperties.put("mail.smtp.localhost", "localhost"); } } MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail); helper.setFrom(from); helper.setTo(processMultipleImailAddresses(to.trim())); helper.setSubject(subject); helper.setText(body, true); mailSender.send(mimeMessage); if (successMessage != null && sendMessage) { addPageMessage(successMessage); } logger.debug("Email sent successfully on {}", new Date()); } catch (MailException me) { me.printStackTrace(); if (failMessage != null && sendMessage) { addPageMessage(failMessage); } logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString()); messageSent = false; } return messageSent; }
From source file:org.alfresco.web.bean.TemplateMailHelperBean.java
/** * Send an email notification to the specified User authority * /*from w w w. j a v a 2s. c o m*/ * @param person Person node representing the user * @param node Node they are invited too * @param from From text message * @param roleText The role display label for the user invite notification */ public void notifyUser(NodeRef person, NodeRef node, final String from, String roleText) { final String to = (String) this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL); if (to != null && to.length() != 0) { String body = this.body; if (this.usingTemplate != null) { FacesContext fc = FacesContext.getCurrentInstance(); // use template service to format the email NodeRef templateRef = new NodeRef(Repository.getStoreRef(), this.usingTemplate); ServiceRegistry services = Repository.getServiceRegistry(fc); Map<String, Object> model = DefaultModelHelper.buildDefaultModel(services, Application.getCurrentUser(fc), templateRef); model.put("role", roleText); model.put("space", node); // object to allow client urls to be generated in emails model.put("url", new BaseTemplateContentServlet.URLHelper(fc)); model.put("msg", new I18NMessageMethod()); model.put("document", node); if (nodeService.getType(node).equals(ContentModel.TYPE_CONTENT)) { NodeRef parentNodeRef = nodeService.getParentAssocs(node).get(0).getParentRef(); if (parentNodeRef == null) { throw new IllegalArgumentException("Parent folder doesn't exists for node: " + node); } model.put("space", parentNodeRef); } model.put("shareUrl", UrlUtil.getShareUrl(services.getSysAdminParams())); body = services.getTemplateService().processTemplate("freemarker", templateRef.toString(), model); } this.finalBody = body; MimeMessagePreparator mailPreparer = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setTo(to); message.setSubject(subject); message.setText(finalBody, MailActionExecuter.isHTML(finalBody)); message.setFrom(from); } }; if (logger.isDebugEnabled()) logger.debug("Sending notification email to: " + to + "\n...with subject:\n" + subject + "\n...with body:\n" + body); try { // Send the message this.getMailSender().send(mailPreparer); } catch (Throwable e) { // don't stop the action but let admins know email is not getting sent logger.error("Failed to send email to " + to, e); } } }