List of usage examples for org.apache.commons.mail HtmlEmail setFrom
public Email setFrom(final String email, final String name) throws EmailException
From source file:Email.CommonsEmail.java
/** * Envia email no formato HTML//from w w w . j ava 2s . com * * @throws EmailException * @throws MalformedURLException */ private void enviaEmailFormatoHtml() throws EmailException, MalformedURLException, IOException, Exception { String para = "alessandropereirarezende@gmail.com;alessandrorezende@msn.com"; StringTokenizer stPara = new StringTokenizer(para, ";"); while (stPara.hasMoreTokens()) { HtmlEmail email = new HtmlEmail(); // adiciona uma imagem ao corpo da mensagem e retorna seu id URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif"); String cid = email.embed(url, "Apache logo"); System.out.println(cid); // configura a mensagem para o formato HTML File img = new File(Functions.getCurrentPath() + "web\\resources\\images\\facom.png"); StringBuilder msg = new StringBuilder(); msg.append("<html><body>"); msg.append("<img src=cid:").append(email.embed(img)).append(">"); msg.append("</body></html>"); // configure uma mensagem alternativa caso o servidor no suporte HTML email.setTextMsg("Seu servidor de e-mail no suporta mensagem HTML"); // o servidor SMTP para envio do e-mail email.setHostName("smtp.gmail.com"); // remetente email.setFrom(emailConfig.getEmail(), emailConfig.getNome()); email.setAuthentication(emailConfig.getUsuario(), emailConfig.getSenha()); email.setSmtpPort(emailConfig.getPorta()); email.setSSLOnConnect(emailConfig.getSsl()); //destinatrio //email.addTo("alessandropereirarezende@gmail.com", "Alessandro"); email.addTo(stPara.nextToken().trim()); // assunto do e-mail email.setSubject("Teste -> Html Email"); email.setHtmlMsg(msg.toString()); //conteudo do e-mail //email.setMsg("Teste de Email HTML utilizando commons-email"); // envia email email.send(); } }
From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java
@Override public boolean send(final EmailMessageModel message) { if (message == null) { throw new IllegalArgumentException("message must not be null"); }/* w w w .ja v a2s .com*/ final boolean sendEnabled = getConfigurationService().getConfiguration() .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true); if (sendEnabled) { try { final HtmlEmail email = getPerConfiguredEmail(); email.setCharset("UTF-8"); final List<EmailAddressModel> toAddresses = message.getToAddresses(); if (CollectionUtils.isNotEmpty(toAddresses)) { email.setTo(getAddresses(toAddresses)); } else { throw new IllegalArgumentException("message has no To addresses"); } final List<EmailAddressModel> ccAddresses = message.getCcAddresses(); if (ccAddresses != null && !ccAddresses.isEmpty()) { email.setCc(getAddresses(ccAddresses)); } final List<EmailAddressModel> bccAddresses = message.getBccAddresses(); if (bccAddresses != null && !bccAddresses.isEmpty()) { email.setBcc(getAddresses(bccAddresses)); } final EmailAddressModel fromAddress = message.getFromAddress(); email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName())); // Add the reply to if specified final String replyToAddress = message.getReplyToAddress(); if (replyToAddress != null && !replyToAddress.isEmpty()) { email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null))); } email.setSubject(message.getSubject()); email.setHtmlMsg(getBody(message)); // To support plain text parts use email.setTextMsg() final List<EmailAttachmentModel> attachments = message.getAttachments(); if (attachments != null && !attachments.isEmpty()) { for (final EmailAttachmentModel attachment : attachments) { try { final DataSource dataSource = new ByteArrayDataSource( getMediaService().getDataFromMedia(attachment), attachment.getMime()); email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText()); } catch (final EmailException ex) { LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex); return false; } } } // Important to log all emails sent out LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From [" + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]"); // Send the email and capture the message ID final String messageID = email.send(); message.setSent(true); message.setSentMessageID(messageID); message.setSentDate(new Date()); getModelService().save(message); return true; } catch (final EmailException e) { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "] cause: " + e.getMessage()); if (LOG.isDebugEnabled()) { LOG.debug(e); } } } else { LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]"); LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'"); return true; } return false; }
From source file:de.jaide.courier.email.MessageHandlerEMail.java
public void handleMessage(Map<String, Object> parameters) throws CourierException { /*/* w ww . j a va 2 s . c om*/ * 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:bean.OrdemBean.java
private void enviarEmailOrdem(OrdOrdem ordemNova, boolean novaOrdem) { try {/* w ww. j a v a2 s . 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:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java
@TriggersRemove(cacheName = { "EmployeeCache", "GroupCache", "EmployeeKeyedByGroupCache" }, when = When.AFTER_METHOD_INVOCATION, removeAll = true, keyGenerator = @KeyGenerator(name = "HashCodeCacheKeyGenerator", properties = @Property(name = "includeMethod", value = "false"))) @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, rollbackFor = ExceptionWrapper.class) public void updateAllEmployee(List<EmployeeBO> employeeListFromLDAP) throws ExceptionWrapper { try {/*from ww w .jav a 2s. c o m*/ 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 user is added to the system.</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 necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n" + " <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>"; String messageTemplateDeleted = "<html>\n" + "<head>\n" + "</head>\n" + "\n" + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n" + " <p>An user is removed from the system.</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 necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n" + " <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>"; LinkedHashMap<Long, EmployeeBO> employeeLinkedHashMap = employeeDataAccessor.getAllEmployees(); for (EmployeeBO employeeBO : employeeListFromLDAP) { if (!employeeLinkedHashMap.containsKey(Long.valueOf(employeeBO.getEmployeeId()))) { //Add a new employee Employee employee = new Employee(); employee.setEmployeeId(Long.parseLong(employeeBO.getEmployeeId())); employee.setEmail(employeeBO.getEmail()); employee.setEmployeeName(employeeBO.getEmployeeName()); employee.setEmployeeUid(employeeBO.getEmployeeUid()); employee.setJobTitle(employeeBO.getJobTitle()); employee.setMobileNumber(employeeBO.getMobileNumber()); employee.setManager(employeeBO.getManager()); employee.setManagerEmail(employeeBO.getManagerEmail()); employee.setExtensionNum(employeeBO.getExtensionNum()); employee.setWorkspace(employeeBO.getWorkspace()); employee.setIsActive(true); employeeDataAccessor.addEmployee(employee); LoggingHelpUtil.printDebug(String.format("Adding user ----> %s with details %s %s", employeeBO.getEmployeeName(), System.getProperty("line.separator"), ReflectionToStringBuilder.toString(employeeBO))); //Send the mail HtmlEmail emailToSend = new HtmlEmail(); emailToSend.setHostName(email.getHostName()); 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(); //Send mail to scrum masters and Development Managers Group Id 15 Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union( getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")), getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15"))); for (EmployeeBO item : allEmployeesNeedToGetMail) { emailToSend.addTo(item.getEmail(), item.getEmployeeName()); } emailToSend.addTo(employeeBO.getManagerEmail(), employeeBO.getManager());//Send the mail to manager //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central"); emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata"); emailToSend.setSubject(String.format("New employee added : %s", employeeBO.getEmployeeName())); emailToSend.send(); //==========================Mail send ends here=========================================================================================================== //sendMailToPerceptiveOpsTeam(employeeBO);//Send mail to operations team in Shawnee } else { //Update a new employee employeeDataAccessor.updateEmployee(employeeBO); LoggingHelpUtil.printDebug(String.format("Updating user ----> %s with details %s %s", employeeBO.getEmployeeName(), System.getProperty("line.separator"), ReflectionToStringBuilder.toString(employeeBO))); } //======================================================================================================================================== } //Delete employees if any for (Object obj : employeeLinkedHashMap.values()) { final EmployeeBO emp = (EmployeeBO) obj; if (!CollectionUtils.exists(employeeListFromLDAP, new Predicate() { @Override public boolean evaluate(Object o) { return emp.getEmployeeId().trim().equalsIgnoreCase(((EmployeeBO) o).getEmployeeId().trim()); //To change body of implemented methods use File | Settings | File Templates. } })) { emp.setActive(false); //Soft delete the Employee employeeDataAccessor.updateEmployee(emp);//Rest deletion will be taken care by the Trigger AFTER_EMPLOYEE_UPDATE LoggingHelpUtil.printDebug( String.format("Deleting user ----> %s with details %s %s", emp.getEmployeeName(), System.getProperty("line.separator"), ReflectionToStringBuilder.toString(emp))); //Send the mail HtmlEmail emailToSend = new HtmlEmail(); emailToSend.setHostName(email.getHostName()); String messageToSend = String.format(messageTemplateDeleted, emp.getEmployeeName(), emp.getEmployeeUid(), emp.getEmployeeId().toString(), emp.getEmail(), emp.getMobileNumber(), emp.getJobTitle()); emailToSend.setHtmlMsg(messageToSend); //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend)); emailToSend.getToAddresses().clear(); //Send mail to scrum masters ==Group ID 14 and Development Managers Group Id 15 Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union( getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")), getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15"))); for (EmployeeBO item : allEmployeesNeedToGetMail) { emailToSend.addTo(item.getEmail(), item.getEmployeeName()); } //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central"); emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata"); emailToSend.setSubject(String.format("Employee removed : %s", emp.getEmployeeName())); emailToSend.send(); } } luceneUtil.indexUserInfo(getAllEmployees().values()); } catch (Exception ex) { throw new ExceptionWrapper(ex); } }
From source file:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java
private void sendMailToPerceptiveOpsTeam(EmployeeBO employeeBO) throws Exception { try {// w w w .j a v a 2s. co 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:org.gravidence.gravifon.email.ApacheCommonsEmailSender.java
@Override public boolean send(String toAddress, String toName, String subject, String htmlMessage, String textMessage) { HtmlEmail email = new HtmlEmail(); email.setHostName(host);//from ww w . j a v a2 s. com email.setSslSmtpPort(port); email.setAuthenticator(new DefaultAuthenticator(username, password)); email.setSSLOnConnect(true); try { if (StringUtils.isBlank(toName)) { email.addTo(toAddress); } else { email.addTo(toAddress, toName); } email.setFrom(fromAddress, fromName); email.setSubject(subject); if (htmlMessage != null) { email.setHtmlMsg(htmlMessage); } if (textMessage != null) { email.setTextMsg(textMessage); } email.send(); } catch (EmailException ex) { // TODO think about throwing GravifonException LOGGER.warn(String.format("Failed to send an email to %s", toAddress), ex); return false; } return true; }
From source file:org.infoglue.cms.util.mail.MailService.java
/** * * @param from the sender of the email./* w w w . j a va 2s.c o m*/ * @param to the recipient of the email. * @param subject the subject of the email. * @param content the body of the email. * @throws SystemException if the email couldn't be sent due to some mail server exception. */ public void sendHTML(String from, String to, String cc, String bcc, String bounceAddress, String replyTo, String subject, String content, String encoding) throws SystemException { try { HtmlEmail email = new HtmlEmail(); String mailServer = CmsPropertyHandler.getMailSmtpHost(); String mailPort = CmsPropertyHandler.getMailSmtpPort(); String systemEmailSender = CmsPropertyHandler.getSystemEmailSender(); email.setHostName(mailServer); if (mailPort != null && !mailPort.equals("")) email.setSmtpPort(Integer.parseInt(mailPort)); boolean needsAuthentication = false; try { needsAuthentication = new Boolean(CmsPropertyHandler.getMailSmtpAuth()).booleanValue(); } catch (Exception ex) { needsAuthentication = false; } if (needsAuthentication) { final String userName = CmsPropertyHandler.getMailSmtpUser(); final String password = CmsPropertyHandler.getMailSmtpPassword(); email.setAuthentication(userName, password); } email.setBounceAddress(systemEmailSender); email.setCharset(encoding); if (logger.isInfoEnabled()) { logger.info("systemEmailSender:" + systemEmailSender); logger.info("to:" + to); logger.info("from:" + from); logger.info("mailServer:" + mailServer); logger.info("mailPort:" + mailPort); logger.info("cc:" + cc); logger.info("bcc:" + bcc); logger.info("replyTo:" + replyTo); logger.info("subject:" + subject); } if (to.indexOf(";") > -1) { cc = to; to = from; } String limitString = CmsPropertyHandler.getEmailRecipientLimit(); if (limitString != null && !limitString.equals("-1")) { try { Integer limit = new Integer(limitString); int count = 0; if (cc != null) count = count + cc.split(";").length; if (bcc != null) count = count + bcc.split(";").length; logger.info("limit: " + limit + ", count: " + count); if (count > limit) throw new Exception("You are not allowed to send mail to more than " + limit + " recipients at a time. This is specified in app settings."); } catch (NumberFormatException e) { logger.error("Exception validating number of recipients in mailservice:" + e.getMessage(), e); } } email.addTo(to, to); email.setFrom(from, from); if (cc != null) email.setCc(createInternetAddressesList(cc)); if (bcc != null) email.setBcc(createInternetAddressesList(bcc)); if (replyTo != null) email.setReplyTo(createInternetAddressesList(replyTo)); email.setSubject(subject); email.setHtmlMsg(content); email.setTextMsg("Your email client does not support HTML messages"); email.send(); logger.info("Email sent!"); } catch (Exception e) { logger.error("An error occurred when we tried to send this mail:" + e.getMessage(), e); throw new SystemException("An error occurred when we tried to send this mail:" + e.getMessage(), e); } }
From source file:org.onehippo.forge.resetpassword.services.mail.MailServiceImpl.java
@Override public void sendMail(final MailMessage mailMessage) throws EmailException { final HtmlEmail email = new HtmlEmail(); final Session session = getSession(); if (session == null) { throw new EmailException("Unable to send mail; no mail session available"); }//from w w w. ja v a 2 s. co m email.setMailSession(session); email.addTo(mailMessage.getToMail(), mailMessage.getToName()); email.setFrom(mailMessage.getFromMail(), mailMessage.getFromName()); email.setSubject(mailMessage.getSubject()); // set the html message email.setHtmlMsg(mailMessage.getHtmlTextBody()); // set the alternative message email.setTextMsg(mailMessage.getPlainTextBody()); // send the email email.send(); }
From source file:org.oscarehr.oscar_apps.util.Log4JGmailExecutorTask.java
private void sendEmail() throws EmailException { HtmlEmail email = new HtmlEmail(); email.setHostName(smtpServer);/*from ww w. j a v a 2 s . c o m*/ if (smtpUser != null && smtpPassword != null) email.setAuthentication(smtpUser, smtpPassword); if (smtpSslPort != null) { email.setSSL(true); email.setSslSmtpPort(smtpSslPort); } Session session = email.getMailSession(); Properties properties = session.getProperties(); properties.setProperty("mail.smtp.connectiontimeout", "20000"); properties.setProperty("mail.smtp.timeout", "20000"); email.addTo(recipientEmailAddress, recipientEmailAddress); email.setFrom(smtpUser, smtpUser); email.setSubject(subject); email.setHtmlMsg(contents); email.setTextMsg(contents); email.send(); }