List of usage examples for org.apache.commons.mail HtmlEmail setHtmlMsg
public HtmlEmail setHtmlMsg(final String aHtml) throws EmailException
From source file:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java
private void sendMailToPerceptiveOpsTeam(EmployeeBO employeeBO) throws Exception { try {//from w w w . j a v a 2 s. c o m //Send the mail HtmlEmail emailToSend = new HtmlEmail(); emailToSend.setHostName(email.getHostName()); String messageTemplateAdded = "<html>\n" + "<head>\n" + "</head>\n" + "\n" + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n" + " <p>A new employee has joined Perceptive Kolkata.</p>\n" + "</blockquote>\n" + "<ul>\n" + " <li><strong><em>User Name</em></strong>: <strong>%s</strong></li>\n" + " <li><em><strong>User Short Id</strong></em>: <strong>%s</strong></li>\n" + " <li><em><strong>Employee Id</strong></em>: <strong>%s</strong></li>\n" + " <li><strong><em>User Email-Id</em></strong>:<strong> %s</strong></li>\n" + " <li><em><strong>Mobile Number</strong></em>:<strong> %s</strong></li>\n" + " <li><em><strong>Job Title</strong></em> : <strong>%s</strong></li>\n" + "</ul>\n" + "<p>Please take following actions.</p>\n" + "<ul>\n" + " <li>Access to Rally.</li>\n" + " <li>Access to Salesforce.</li>\n" + " <li>Access to Confluence.</li>\n" + " <li>Access to Perceptive AD.</li>\n" + " <li>Access to TFS.</li>\n" + "</ul>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n" + " <p>Perceptive Kolkata Central( http://10.195.17.14/PerceptiveKolkataCentral )</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>"; String messageToSend = String.format(messageTemplateAdded, employeeBO.getEmployeeName(), employeeBO.getEmployeeUid(), employeeBO.getEmployeeId().toString(), employeeBO.getEmail(), employeeBO.getMobileNumber(), employeeBO.getJobTitle()); emailToSend.setHtmlMsg(messageToSend); //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend)); emailToSend.getToAddresses().clear(); emailToSend.addTo("per.special.rad.operations@perceptivesoftware.com", "RAD - Operations"); emailToSend.addTo("radops@perceptivesoftware.com", "RAD - Operations Team"); Collection<EmployeeBO> allEmployeesNeedToGetMail = getAllEmployeesKeyedByGroupId() .get(Integer.valueOf("14")); for (EmployeeBO item : allEmployeesNeedToGetMail) { emailToSend.addCc(item.getEmail(), item.getEmployeeName()); } //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central"); emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata"); emailToSend.setSubject( String.format("New employee joined @ Lexmark Kolkata : %s", employeeBO.getEmployeeName())); emailToSend.send(); } catch (Exception ex) { throw new ExceptionWrapper(ex); } }
From source file:com.mycollab.module.mail.DefaultMailer.java
private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail, List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) { try {//from ww w . j a v a 2 s .c o m HtmlEmail email = new HtmlEmail(); email.setHostName(emailConf.getHost()); email.setSmtpPort(emailConf.getPort()); email.setStartTLSEnabled(emailConf.getIsStartTls()); email.setSSLOnConnect(emailConf.getIsSsl()); email.setFrom(fromEmail, fromName); email.setCharset(EmailConstants.UTF_8); for (MailRecipientField aToEmail : toEmail) { if (isValidate(aToEmail.getEmail()) && isValidate(aToEmail.getName())) { email.addTo(aToEmail.getEmail(), aToEmail.getName()); } else { LOG.error(String.format("Invalid to email input: %s---%s", aToEmail.getEmail(), aToEmail.getName())); } } if (CollectionUtils.isNotEmpty(ccEmail)) { for (MailRecipientField aCcEmail : ccEmail) { if (isValidate(aCcEmail.getEmail()) && isValidate(aCcEmail.getName())) { email.addCc(aCcEmail.getEmail(), aCcEmail.getName()); } else { LOG.error(String.format("Invalid cc email input: %s---%s", aCcEmail.getEmail(), aCcEmail.getName())); } } } if (CollectionUtils.isNotEmpty(bccEmail)) { for (MailRecipientField aBccEmail : bccEmail) { if (isValidate(aBccEmail.getEmail()) && isValidate(aBccEmail.getName())) { email.addBcc(aBccEmail.getEmail(), aBccEmail.getName()); } else { LOG.error(String.format("Invalid bcc email input: %s---%s", aBccEmail.getEmail(), aBccEmail.getName())); } } } if (emailConf.getUser() != null) { email.setAuthentication(emailConf.getUser(), emailConf.getPassword()); } email.setSubject(subject); if (StringUtils.isNotBlank(html)) { email.setHtmlMsg(html); } return email; } catch (EmailException e) { throw new MyCollabException(e); } }
From source file:de.jaide.courier.email.MessageHandlerEMail.java
public void handleMessage(Map<String, Object> parameters) throws CourierException { /*/*from ww w .j a va 2 s . co m*/ * Check if the obligatory parameters are there. */ for (String key : obligatoryMappingParameters) if (!parameters.containsKey(key)) throw new CourierException(new MissingParameterException( "The parameter '" + key + "' was expected but couldn't be found.")); /* * Now retrieve the obligatory parameters. */ String configurationName = (String) parameters.get(MAPPING_PARAM_CONFIGURATION_NAME); String templatePath = (String) parameters.get(MAPPING_PARAM_TEMPLATE_PATH); if ((templatePath != null) && (!templatePath.endsWith("/"))) templatePath += "/"; else if (templatePath == null) templatePath = "/"; Class<?> templatePathClass = (Class<?>) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_CLASS); File templatePathFile = (File) parameters.get(MAPPING_PARAM_TEMPLATE_PATH_FILE); String templateName = (String) parameters.get(MAPPING_PARAM_TEMPLATE_NAME); TemplateTypeEnum templateTypeEnum = (TemplateTypeEnum) parameters.get(MAPPING_PARAM_TEMPLATE_TYPE); String recipientFirstname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_FIRSTNAME); String recipientLastname = (String) parameters.get(MAPPING_PARAM_RECIPIENT_LASTNAME); String recipientEMail = (String) parameters.get(MAPPING_PARAM_RECIPIENT_EMAIL); String ccRecipientFirstname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_FIRSTNAME); String ccRecipientLastname = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_LASTNAME); String ccRecipientEMail = (String) parameters.get(MAPPING_PARAM_CC_RECIPIENT_EMAIL); /* * The next three parameters are optional, as they might also be specified in the SMTP configuration file. If they are specified they * tell us to overwrite what was specified in the SMTP configuration file and use those values (firstname, lastname, e-mail) for the * sender instead. */ String senderFirstname = null; if (parameters.containsKey(MAPPING_PARAM_SENDER_FIRSTNAME)) senderFirstname = (String) parameters.get(MAPPING_PARAM_SENDER_FIRSTNAME); String senderLastname = null; if (parameters.containsKey(MAPPING_PARAM_SENDER_LASTNAME)) senderLastname = (String) parameters.get(MAPPING_PARAM_SENDER_LASTNAME); String senderEMail = null; if (parameters.containsKey(MAPPING_PARAM_SENDER_EMAIL)) senderEMail = (String) parameters.get(MAPPING_PARAM_SENDER_EMAIL); /* * Will be used for parsing the templates. */ StringWriter writer = new StringWriter(); try { /* * Construct the template that we're about to process. First set the path to load the template(s) from. In case a Directory was given * as the base for template loading purposes use that instead. */ if (templatePathFile == null) { if (templatePathClass == null) templatingConfiguration.setClassForTemplateLoading(getClass(), templatePath); else templatingConfiguration.setClassForTemplateLoading(templatePathClass, templatePath); } else templatingConfiguration.setDirectoryForTemplateLoading(templatePathFile); /* * Get the headers and Freemarker-parse them. If there are no headers then ignore the errors. The file has to be one header per line, * header name and value separated by a colon (":"). */ Template template; Map<String, String> headers = new HashMap<String, String>(); String headersFilename = retrieveTemplateFilename(templateName, MessageHandlerEMail.TEMPLATENAME_SUFFIX_HEADERS, true); if (headersFilename != null) { try { template = loadTemplate(headersFilename); template.process(parameters, writer); BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); headers = new HashMap<String, String>(); String str = ""; while ((str = reader.readLine()) != null) { String[] split = str.split(":"); if (split.length > 1) headers.put(split[0].trim(), split[1].trim()); } } catch (IOException ioe) { // The header file is optional, hence we don't care if it couldn't be found } } /* * Get the subject line and Freemarker-parse it. */ String subject = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_SUBJECT, templateName, false); /* * Get the body content and Freemarker-parse it. */ String contentText = null; String contentHtml = null; /* * Load all requested versions of the template. */ if (templateTypeEnum == TemplateTypeEnum.TEXT) { contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, false); } else if (templateTypeEnum == TemplateTypeEnum.HTML) { contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true); } else if (templateTypeEnum == TemplateTypeEnum.BOTH) { contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, false); contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true); } else if (templateTypeEnum == TemplateTypeEnum.ANY) { try { contentText = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, false); } catch (IOException ioe) { } finally { try { contentHtml = loadAndProcessTemplate(parameters, MessageHandlerEMail.TEMPLATENAME_SUFFIX_BODY, templateName, true); } catch (IOException ioe) { throw new RuntimeException( "Neither the HTML nor the TEXT-only version of the e-mail template '" + templateName + "' could be found. Are you sure they reside in '" + templatePath + "' as '" + templateName + "_body.ftl.html' or '" + templateName + "_body.ftl.txt'?", ioe); } } } /* * Set the parameters that are identical for that sender, for all recipients. * Note: attachments may not be removed once they have been attached, hence the performance-improving caching had to be removed. */ SmtpConfiguration smtpConfiguration = (SmtpConfiguration) smtpConfigurations.get(configurationName); HtmlEmail htmlEmail = new HtmlEmail(); htmlEmail.setCharset("UTF-8"); htmlEmail.setHostName(smtpConfiguration.getSmtpHostname()); htmlEmail.setSmtpPort(smtpConfiguration.getSmtpPort()); if (smtpConfiguration.isTls()) { htmlEmail.setAuthenticator( new DefaultAuthenticator(smtpConfiguration.getUsername(), smtpConfiguration.getPassword())); htmlEmail.setStartTLSEnabled(smtpConfiguration.isTls()); } htmlEmail.setSSLOnConnect(smtpConfiguration.isSsl()); /* * Changing the sender, to differ from what was specified in the particular SMTP configuration, is optional. As explained above this * will only happen if they were specified by the caller. */ if ((senderFirstname != null) || (senderLastname != null) || (senderEMail != null)) htmlEmail.setFrom(senderEMail, senderFirstname + " " + senderLastname); else htmlEmail.setFrom(smtpConfiguration.getFromEMail(), smtpConfiguration.getFromSenderName()); /* * Set the parameters that differ for each recipient. */ htmlEmail.addTo(recipientEMail, recipientFirstname + " " + recipientLastname); if ((ccRecipientFirstname != null) && (ccRecipientLastname != null) && (ccRecipientEMail != null)) htmlEmail.addCc(ccRecipientEMail, ccRecipientFirstname + " " + ccRecipientLastname); htmlEmail.setHeaders(headers); htmlEmail.setSubject(subject); /* * Set the HTML and Text version of the e-mail body. */ if (contentHtml != null) htmlEmail.setHtmlMsg(contentHtml); if (contentText != null) htmlEmail.setTextMsg(contentText); /* * Add attachments, if available. */ if (parameters.containsKey(MAPPING_PARAM_ATTACHMENTS)) { @SuppressWarnings("unchecked") List<EmailAttachment> attachments = (List<EmailAttachment>) parameters .get(MAPPING_PARAM_ATTACHMENTS); for (EmailAttachment attachment : attachments) { htmlEmail.attach(attachment); } } /* * Finished - now send the e-mail. */ htmlEmail.send(); } catch (IOException ioe) { throw new CourierException(ioe); } catch (TemplateException te) { throw new CourierException(te); } catch (EmailException ee) { throw new CourierException(ee); } finally { if (writer != null) { writer.flush(); try { writer.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } }
From source file:com.moss.error_reporting.server.Notifier.java
public void sendEmailNotification(ReportId id, ErrorReport report) { try {//from w w w . j a v a 2s. c o m HtmlEmail email = new HtmlEmail(); prepEmail(email, id); StringBuffer body = new StringBuffer(); body.append("<html><body>"); List<ErrorReportChunk> chunks = report.getReportChunks(); for (int x = 0; x < chunks.size(); x++) { ErrorReportChunk chunk = chunks.get(x); body.append("<div style=\"padding:5px;text-align:center;border:1px solid black;\">"); body.append("<span style=\"font-weight:bold;\">" + chunk.getName() + "</span>"); body.append("<span style=\"font-style:italic;\">[" + chunk.getMimeType() + "</span>]"); body.append("</div>"); String mimeType = chunk.getMimeType(); if (mimeType != null && mimeType.equals("text/plain")) { body.append( "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>"); boolean needsTruncation = chunk.getData().length > MAX_MESSAGE_LENGTH; int length = needsTruncation ? MAX_MESSAGE_LENGTH : chunk.getData().length; body.append(new String(chunk.getData(), 0, length)); if (needsTruncation) { body.append("\n"); body.append((chunk.getData().length - MAX_MESSAGE_LENGTH) + " more bytes"); } body.append("</pre></div>"); } else if (mimeType != null && mimeType.equals("application/zip")) { body.append( "<div style=\"border:1px solid black;border-top:0px;padding:5px;background:#dddddd;\"><pre>"); ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(chunk.getData())); try { new ZipToTextTool().run(in, body); } catch (IOException e) { e.printStackTrace(); body.append("Error Reading Zip:" + e.getMessage()); } body.append("</pre></div>"); } if (x != chunks.size() - 1 && chunks.size() > 1) body.append("<br/><br/>"); } body.append("</body></html>"); // email.setHtmlMsg("<html><body>Hello World</body></html>"); email.setHtmlMsg(body.toString()); // email.setTextMsg("HTML EMAIL"); email.buildMimeMessage(); email.sendMimeMessage(); } catch (EmailException e) { e.printStackTrace(); } }
From source file:br.com.asisprojetos.email.SendEmail.java
public void enviar(String toEmail[], String subject, String templateFile, List<String> fileNames, String mes, int codContrato) { try {/* w w w .j av a 2 s . c o m*/ String htmlFileTemplate = loadHtmlFile(templateFile); for (String to : toEmail) { String htmlFile = htmlFileTemplate; // Create the email message HtmlEmail email = new HtmlEmail(); email.setHostName(config.getHostname()); email.setSmtpPort(config.getPort()); email.setFrom(config.getFrom(), config.getFromName()); // remetente email.setAuthenticator( new DefaultAuthenticator(config.getAuthenticatorUser(), config.getAuthenticatorPassword())); email.setSSL(true); email.setSubject(subject); //Assunto email.addTo(to);//para logger.debug("Enviando Email para : [{}] ", to); int i = 1; for (String fileName : fileNames) { String cid; if (fileName.startsWith("diagnostico")) { try { cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName))); htmlFile = StringUtils.replace(htmlFile, "$codGraph24$", "<img src=\"cid:" + cid + "\">"); } catch (EmailException ex) { logger.error("Arquivo de diagnostico nao encontrado."); } } else if (fileName.startsWith("recorrencia")) { try { cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName))); htmlFile = StringUtils.replace(htmlFile, "$codGraph25$", "<img src=\"cid:" + cid + "\">"); } catch (EmailException ex) { logger.error("Arquivo de recorrencia nao encontrado."); } } else { cid = email.embed(new File(String.format("%s/%s", config.getOutDirectory(), fileName))); htmlFile = StringUtils.replace(htmlFile, "$codGraph" + i + "$", "<img src=\"cid:" + cid + "\">"); i++; } } //apaga $codGraph$ no usado do template for (int t = i; t <= 25; t++) { htmlFile = StringUtils.replace(htmlFile, "$codGraph" + t + "$", " "); } htmlFile = StringUtils.replace(htmlFile, "$MES$", mes); htmlFile = StringUtils.replace(htmlFile, "$MAIL$", to); htmlFile = StringUtils.replace(htmlFile, "$CONTRATO$", Integer.toString(codContrato)); email.setHtmlMsg(htmlFile); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); } logger.debug("Email enviado com sucesso......"); } catch (FileNotFoundException ex) { logger.error("Arquivo [{}/{}] nao encontrado para leitura.", config.getHtmlDirectory(), templateFile); } catch (Exception ex) { logger.error("Erro ao Enviar email : {}", ex); } }
From source file:com.aquest.emailmarketing.web.service.SendEmail.java
/** * Send email.// w w w .jav a 2 s. co m * * @param broadcast the broadcast * @param emailConfig the email config * @param emailList the email list * @throws EmailException the email exception * @throws MalformedURLException the malformed url exception * @throws InterruptedException the interrupted exception */ @Async public void sendEmail(Broadcast broadcast, EmailConfig emailConfig, EmailList emailList) throws EmailException, MalformedURLException, InterruptedException { Timestamp curTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime()); // email configuration part HtmlEmail email = new HtmlEmail(); email.setSmtpPort(emailConfig.getPort()); email.setHostName(emailConfig.getHostname()); email.setAuthenticator(new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword())); email.setSSLOnConnect(emailConfig.isSslonconnect()); email.setDebug(emailConfig.isDebug()); email.setFrom(emailConfig.getFrom_address()); //ovde dodati i email from description System.out.println(emailList); HashMap<String, String> variables = processVariableService.ProcessVariable(emailList); for (String keys : variables.keySet()) { System.out.println("key:" + keys + ", value:" + variables.get(keys)); } String processSubject = broadcast.getSubject(); String newHtml = broadcast.getHtmlbody_embed(); String newPlainText = broadcast.getPlaintext(); for (String key : variables.keySet()) { processSubject = processSubject.replace("[" + key + "]", variables.get(key)); System.out.println(key + "-" + variables.get(key)); newHtml = newHtml.replace("[" + key + "]", variables.get(key)); newPlainText = newPlainText.replace("[" + key + "]", variables.get(key)); } System.out.println(processSubject); email.setSubject(processSubject); email.addTo(emailList.getEmail()); String image = embeddedImageService.getEmbeddedImages(broadcast.getBroadcast_id()).getUrl(); List<String> images = Arrays.asList(image.split(";")); for (int j = 0; j < images.size(); j++) { System.out.println(images.get(j)); } for (int i = 0; i < images.size(); i++) { String id = email.embed(images.get(i), "Slika" + i); newHtml = newHtml.replace("[IMAGE:" + i + "]", "cid:" + id); } Config config = configService.getConfig("trackingurl"); //DONE: Create jsp page for tracking server url String serverUrl = config.getValue(); System.out.println(serverUrl); Base64 base64 = new Base64(true); Pattern pattern = Pattern.compile("<%tracking=(.*?)=tracking%>"); Matcher matcher = pattern.matcher(newHtml); while (matcher.find()) { String url = matcher.group(1); System.out.println(url); logger.debug(url); String myEncryptedUrl = new String(base64.encode(url.getBytes())); String oldurl = "<%tracking=" + url + "=tracking%>"; logger.debug(oldurl); System.out.println(oldurl); String newurl = serverUrl + "tracking?id=" + myEncryptedUrl; logger.debug(newurl); System.out.println(newurl); newHtml = newHtml.replace(oldurl, newurl); } // System.out.println(newHtml); email.setHtmlMsg(newHtml); email.setTextMsg(newPlainText); try { System.out.println("A ovo ovde?"); email.send(); emailList.setStatus("SENT"); emailList.setProcess_dttm(curTimestamp); emailListService.SaveOrUpdate(emailList); } catch (Exception e) { logger.error(e); } // time in seconds to wait between 2 mails TimeUnit.SECONDS.sleep(emailConfig.getWait()); }
From source file:gov.osti.services.Metadata.java
/** * Send a NOTIFICATION EMAIL (if configured) when a record is SUBMITTED or * ANNOUNCED.//from w w w. ja v a 2 s . c o m * * @param md the METADATA in question */ private static void sendStatusNotification(DOECodeMetadata md) { HtmlEmail email = new HtmlEmail(); email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8); email.setHostName(EMAIL_HOST); // if EMAIL or DESTINATION ADDRESS are not set, abort if (StringUtils.isEmpty(EMAIL_HOST) || StringUtils.isEmpty(EMAIL_SUBMISSION)) return; // only applicable to SUBMITTED or ANNOUNCED records if (!Status.Announced.equals(md.getWorkflowStatus()) && !Status.Submitted.equals(md.getWorkflowStatus())) return; // get the SITE information String siteCode = md.getSiteOwnershipCode(); Site site = SiteServices.findSiteBySiteCode(siteCode); if (null == site) { log.warn("Unable to locate SITE information for SITE CODE: " + siteCode); return; } String lab = site.getLab(); lab = lab.isEmpty() ? siteCode : lab; try { email.setFrom(EMAIL_FROM); email.setSubject("DOE CODE Record " + md.getWorkflowStatus().toString()); email.addTo(EMAIL_SUBMISSION); String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", ""); StringBuilder msg = new StringBuilder(); msg.append("<html>"); msg.append("A new DOE CODE record has been ").append(md.getWorkflowStatus()).append(" for ").append(lab) .append(" and is awaiting approval:"); msg.append("<P>Code ID: ").append(md.getCodeId()); msg.append("<BR>Software Title: ").append(softwareTitle); msg.append("</html>"); email.setHtmlMsg(msg.toString()); email.send(); } catch (EmailException e) { log.error("Failed to send submission/announcement notification message for #" + md.getCodeId()); log.error("Message: " + e.getMessage()); } }
From source file:gov.osti.services.Metadata.java
/** * Send a POC email notification on SUBMISSION/APPROVAL of DOE CODE records. * * @param md the METADATA to send notification for *//* w w w . j a v a2s . c o m*/ private static void sendPOCNotification(DOECodeMetadata md) { // if HOST or MD or PROJECT MANAGER NAME isn't set, cannot send if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(PM_NAME)) return; Long codeId = md.getCodeId(); String siteCode = md.getSiteOwnershipCode(); Status workflowStatus = md.getWorkflowStatus(); // if SITE OWNERSHIP isn't set, cannot send if (StringUtils.isEmpty(siteCode)) return; // only applicable to APPROVED records if (!Status.Approved.equals(workflowStatus)) return; // get the SITE information Site site = SiteServices.findSiteBySiteCode(siteCode); if (null == site) { log.warn("Unable to locate SITE information for SITE CODE: " + siteCode); return; } // lookup previous Snapshot status info for item EntityManager em = DoeServletContextListener.createEntityManager(); TypedQuery<MetadataSnapshot> querySnapshot = em .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class) .setParameter("status", DOECodeMetadata.Status.Approved).setParameter("codeId", codeId); String lastApprovalFor = "submitted/announced"; List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList(); for (MetadataSnapshot ms : results) { lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString().toLowerCase(); } List<String> emails = site.getPocEmails(); // if POC is setup if (emails != null && !emails.isEmpty()) { try { HtmlEmail email = new HtmlEmail(); email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8); email.setHostName(EMAIL_HOST); String lab = site.getLab(); lab = lab.isEmpty() ? siteCode : lab; String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", ""); email.setFrom(EMAIL_FROM); email.setSubject("POC Notification -- " + workflowStatus + " -- DOE CODE ID: " + codeId + ", " + softwareTitle); for (String pocEmail : emails) email.addTo(pocEmail); // if email is provided, BCC the Project Manager if (!StringUtils.isEmpty(PM_EMAIL)) email.addBcc(PM_EMAIL, PM_NAME); StringBuilder msg = new StringBuilder(); msg.append("<html>"); msg.append("Dear Sir or Madam:"); String biblioLink = SITE_URL + "/biblio/" + codeId; msg.append("<p>As a point of contact for ").append(lab) .append(", we wanted to inform you that a software project, titled ").append(softwareTitle) .append(", associated with your organization was ").append(lastApprovalFor) .append(" to DOE CODE and assigned DOE CODE ID: ").append(codeId) .append(". This project record is discoverable in <a href=\"").append(SITE_URL) .append("\">DOE CODE</a>, e.g. searching by the project title or DOE CODE ID #, and can be found here: <a href=\"") .append(biblioLink).append("\">").append(biblioLink).append("</a></p>"); msg.append( "<p>If you have any questions, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</p>"); msg.append("<p>Sincerely,</p>"); msg.append("<p>").append(PM_NAME).append("<br/>Product Manager for DOE CODE<br/>USDOE/OSTI</p>"); msg.append("</html>"); email.setHtmlMsg(msg.toString()); email.send(); } catch (EmailException e) { log.error("Unable to send POC notification to " + Arrays.toString(emails.toArray()) + " for #" + md.getCodeId()); log.error("Message: " + e.getMessage()); } } }
From source file:bean.OrdemBean.java
private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) { try {/* ww w. ja va2s . c om*/ String emailAutenticacao = "chravent@gmail.com"; String senhaAutenticacao = "23421Felix"; //MultiPartEmail email = new MultiPartEmail(); HtmlEmail emailOrdem = new HtmlEmail(); //Informaes do Servidor emailOrdem.setHostName("smtp.gmail.com"); emailOrdem.setSmtpPort(587); //DADOS DE QUEM ESTA ENVIANDO O E-MAIL emailOrdem.setFrom(emailAutenticacao, "GESPED"); //PARA QUEM VAI O EMAIL, VC PODE COLOCAR O USUARIO DE CRIACAO, O QUE ACOMPANHA E O ALTERACO if (!novaOrdem) { if (ordemNova.getUsuUsuarioByUsuAcompanha() != null) { emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuAcompanha().getUsuEmail(), ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario()); emailOrdem.setSubject("Atribuio de Ordem - Com Acompanhamento"); } else { emailOrdem.addTo(ordemNova.getDepDepartamentoByDepIdDestino().getDepEmail(), ordemNova.getUsuUsuarioByUsuCriacao().getUsuUsuario()); emailOrdem.setSubject("Atribuio de Ordem - Sem Acompanhamento"); } } else { emailOrdem.addTo(ordemNova.getUsuUsuarioByUsuCriacao().getUsuEmail(), ordemNova.getUsuUsuarioByUsuAcompanha().getUsuUsuario()); emailOrdem.setSubject("Criao de Nova de Ordem"); } emailOrdem.setSocketConnectionTimeout(30000); emailOrdem.setSocketTimeout(30000); //if (contaPadrao.contains("gmail")) { emailOrdem.setSSL(true); emailOrdem.setTLS(true); //Autenticando no servidor emailOrdem.setAuthentication(emailAutenticacao, senhaAutenticacao); //Montando o e-mail StringBuilder htmlEmail = new StringBuilder(); htmlEmail.append( "<html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\" /> </head><body>"); htmlEmail.append("<br/>").append("Ol ").append(ordem.getUsuUsuarioByUsuAcompanha().getUsuDescricao()) .append(",").append("<br/>"); htmlEmail.append("Uma Ordem Atribuda para seu Usurio:").append("<br/>"); htmlEmail.append("Protocolo : ").append(ordem.getOrdNumProtocolo()).append("<br/>"); if (ordem.getOrdPrioridade()) { htmlEmail.append("Prioridade : Urgente").append("<br/>"); } else { htmlEmail.append("Prioridade : Normal").append("<br/>"); } htmlEmail.append("\"</body></html>\""); //PODE ENVIAR UMA COPIA OCULPA emailOrdem.setHtmlMsg(htmlEmail.toString()); // List<InternetAddress> copiasOcultas = new ArrayList<>(); // copiasOcultas.add(new InternetAddress("enio.a.nunes@gmail.com")); // emailOrdem.setBcc(copiasOcultas); emailOrdem.send(); // context.addMessage(null, new FacesMessage("E-mail enviado com sucesso", this.destino)); } catch (Exception e) { e.printStackTrace(); } }
From source file:gov.osti.services.Metadata.java
/** * Send an email notification on APPROVAL of DOE CODE records. * * @param md the METADATA to send notification for */// ww w.j av a2 s. co m private static void sendApprovalNotification(DOECodeMetadata md) { HtmlEmail email = new HtmlEmail(); email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8); email.setHostName(EMAIL_HOST); // if HOST or record OWNER or PROJECT MANAGER NAME isn't set, cannot send if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(md.getOwner()) || StringUtils.isEmpty(PM_NAME)) return; // only has meaning for APPROVED records if (!Status.Approved.equals(md.getWorkflowStatus())) return; try { // get the OWNER information User owner = UserServices.findUserByEmail(md.getOwner()); if (null == owner) { log.warn("Unable to locate USER information for Code ID: " + md.getCodeId()); return; } Long codeId = md.getCodeId(); // lookup previous Snapshot status info for item EntityManager em = DoeServletContextListener.createEntityManager(); TypedQuery<MetadataSnapshot> querySnapshot = em .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class) .setParameter("status", DOECodeMetadata.Status.Approved).setParameter("codeId", codeId); String lastApprovalFor = "submitted/announced"; List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList(); for (MetadataSnapshot ms : results) { lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString().toLowerCase(); } String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", ""); email.setFrom(EMAIL_FROM); email.setSubject("Approved -- DOE CODE ID: " + codeId + ", " + softwareTitle); email.addTo(md.getOwner()); // if email is provided, BCC the Project Manager if (!StringUtils.isEmpty(PM_EMAIL)) email.addBcc(PM_EMAIL, PM_NAME); StringBuilder msg = new StringBuilder(); msg.append("<html>"); msg.append("Dear ").append(owner.getFirstName()).append(" ").append(owner.getLastName()).append(":"); msg.append("<P>Thank you -- your ").append(lastApprovalFor).append(" project, DOE CODE ID: <a href=\"") .append(SITE_URL).append("/biblio/").append(codeId).append("\">").append(codeId) .append("</a>, has been approved. It is now <a href=\"").append(SITE_URL) .append("\">searchable</a> in DOE CODE by, for example, title or CODE ID #.</P>"); // OMIT the following for BUSINESS TYPE software, or last ANNOUNCED software if (!DOECodeMetadata.Type.B.equals(md.getSoftwareType()) && !lastApprovalFor.equalsIgnoreCase("announced")) { msg.append( "<P>You may need to continue editing your project to announce it to the Department of Energy ") .append("to ensure announcement and dissemination in accordance with DOE statutory responsibilities. For more information please see ") .append("<a href=\"").append(SITE_URL) .append("/faq#what-does-it-mean-to-announce\">What does it mean to announce scientific code to DOE CODE?</a></P>"); } msg.append( "<P>If you have questions such as What are the benefits of getting a DOI for code or software?, see the ") .append("<a href=\"").append(SITE_URL).append("/faq\">DOE CODE FAQs</a>.</P>"); msg.append( "<P>If we can be of assistance, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</P>"); msg.append("<P>Sincerely,</P>"); msg.append("<P>").append(PM_NAME).append("<BR/>Product Manager for DOE CODE<BR/>USDOE/OSTI</P>"); msg.append("</html>"); email.setHtmlMsg(msg.toString()); email.send(); } catch (EmailException e) { log.error("Unable to send APPROVAL notification for #" + md.getCodeId()); log.error("Message: " + e.getMessage()); } }