List of usage examples for org.apache.commons.mail HtmlEmail setAuthenticator
public void setAuthenticator(final Authenticator newAuthenticator)
Authenticator
to be used when authentication is requested from the mail server. From source file:br.com.mysqlmonitor.monitor.Monitor.java
private void enviarEmailDBA() { try {/*from w w w . j av a 2s. co m*/ if (logs.length() != 0) { System.out.println("Divergencias: " + logs); for (Usuario usuario : usuarioDAO.findAll()) { System.out.println("Enviando email para: " + usuario.getNome()); HtmlEmail email = new HtmlEmail(); email.setHostName("smtp.googlemail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("mysqlmonitorsuporte", "4rgvr6RM")); email.setSSL(true); email.setFrom("mysqlmonitorsuporte@gmail.com"); email.setSubject("Log Mysql Monitor"); email.setHtmlMsg(logs.toString()); email.addTo(usuario.getEmail()); email.send(); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.aquest.emailmarketing.web.service.SendEmail.java
/** * Send email.//from w w w.j a va 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:br.com.asisprojetos.email.SendEmail.java
public void enviar(String toEmail[], String subject, String templateFile, List<String> fileNames, String mes, int codContrato) { try {//from w w w .j a v a2 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.dattack.jtoolbox.commons.email.HtmlEmailBuilder.java
/** * Builder method.//from www .java 2 s. c om * * @return the HtmlEmail * @throws EmailException * if an error occurs while creating the email */ public HtmlEmail build() throws EmailException { if (hostname == null || hostname.isEmpty()) { throw new EmailException(String.format("Invalid SMTP server (hostname: '%s')", hostname)); } if (from == null || from.isEmpty()) { throw new EmailException(String.format("Invalid email address (FROM: '%s'", from)); } final HtmlEmail email = new HtmlEmail(); email.setHostName(hostname); email.setFrom(from); email.setSubject(subject); if (message != null && !message.isEmpty()) { email.setMsg(message); } if (port > 0) { email.setSmtpPort(port); } if (username != null && !username.isEmpty()) { email.setAuthenticator(new DefaultAuthenticator(username, password)); } if (sslOnConnect != null) { email.setSSLOnConnect(sslOnConnect); } if (startTlsEnabled != null) { email.setStartTLSEnabled(startTlsEnabled); } if (!toList.isEmpty()) { email.setTo(toList); } if (!ccList.isEmpty()) { email.setCc(ccList); } if (!bccList.isEmpty()) { email.setBcc(bccList); } return email; }
From source file:de.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java
public void send() throws EmailException { if (files != null && urls != null) { attachments = new EmailAttachment[files.length + urls.length]; int cnt = 0; for (int i = 0; i < files.length; i++) { attachments[cnt] = new EmailAttachment(); attachments[cnt].setPath(files[i].getPath()); attachments[cnt].setName(files[i].getName()); attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT); cnt++;//from ww w .j a v a 2s . co m } for (int i = 0; i < urls.length; i++) { attachments[cnt] = new EmailAttachment(); attachments[cnt].setURL(urls[i]); attachments[cnt].setName(urls[i].getFile()); attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT); cnt++; } } else if (files != null) { attachments = new EmailAttachment[files.length]; for (int i = 0; i < files.length; i++) { attachments[i] = new EmailAttachment(); attachments[i].setPath(files[i].getPath()); attachments[i].setName(files[i].getName()); attachments[i].setDisposition(EmailAttachment.ATTACHMENT); } } else if (urls != null) { attachments = new EmailAttachment[urls.length]; for (int i = 0; i < urls.length; i++) { attachments[i] = new EmailAttachment(); attachments[i].setURL(urls[i]); attachments[i].setName(urls[i].getFile()); attachments[i].setDisposition(EmailAttachment.ATTACHMENT); } } HtmlEmail email = new HtmlEmail(); email.setHostName(Config.get("mailHost", "")); email.setSmtpPort(Config.getConfigInt("mailPort", 25)); email.setTLS(Config.getConfigBoolean("mailTLS", false)); email.setSSL(Config.getConfigBoolean("mailSSL", false)); //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25)); email.setAuthenticator( new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", ""))); email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null)); email.setSubject(subject); email.setHtmlMsg(body); email.setTextMsg(nohtmlmsg); for (int i = 0; i < adress.length; i++) { email.addTo(adress[i]); } if (cc != null) { for (int i = 0; i < cc.length; i++) { email.addCc(cc[i]); } } if (attachments != null) { for (int i = 0; i < attachments.length; i++) { email.attach(attachments[i]); } } email.send(); }
From source file:de.jaide.courier.email.MessageHandlerEMail.java
public void handleMessage(Map<String, Object> parameters) throws CourierException { /*// w w w. j a v a2 s . c o 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:br.ufg.reqweb.components.MailBean.java
public void sendMailToDiscente(final Requerimento requerimento) { Thread sender = new Thread() { @Override/*from w ww . j a v a 2 s. c o m*/ public void run() { try { Configuration templateConf = new Configuration(); templateConf.setObjectWrapper(new DefaultObjectWrapper()); templateConf.setDefaultEncoding("UTF-8"); templateConf.setDirectoryForTemplateLoading(new File(context.getRealPath("/reports/mail"))); Map objectRoot = new HashMap(); objectRoot.put("TITULO", LocaleBean.getDefaultMessageBundle().getString("appTitle")); objectRoot.put("DISCENTE", LocaleBean.getDefaultMessageBundle().getString("discente")); objectRoot.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento")); objectRoot.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status")); objectRoot.put("ATENDENTE", LocaleBean.getDefaultMessageBundle().getString("atendente")); objectRoot.put("OBSERVACAO", LocaleBean.getDefaultMessageBundle().getString("observacao")); objectRoot.put("matricula", requerimento.getDiscente().getMatricula()); objectRoot.put("discente", requerimento.getDiscente().getNome()); objectRoot.put("tipoRequerimento", LocaleBean.getDefaultMessageBundle() .getString(requerimento.getTipoRequerimento().getTipo())); objectRoot.put("status", LocaleBean.getDefaultMessageBundle().getString(requerimento.getStatus().getStatus())); objectRoot.put("atendente", requerimento.getAtendimento().getAtendente().getNome()); objectRoot.put("observacao", requerimento.getAtendimento().getObservacao()); URL logo = new File(context.getRealPath("/resources/img/logo-mono-mini.png")).toURI().toURL(); Template template = templateConf.getTemplate("notificacao_discente.ftl"); Writer writer = new StringWriter(); HtmlEmail email = new HtmlEmail(); String logoId = email.embed(logo, "logo"); objectRoot.put("logo", logoId); template.process(objectRoot, writer); email.setHostName(configDao.getValue("mail.mailHost")); email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort"))); String mailSender = configDao.getValue("mail.mailSender"); String user = configDao.getValue("mail.mailUser"); String password = configDao.getValue("mail.mailPassword"); boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL")); email.setAuthenticator(new DefaultAuthenticator(user, password)); email.setSSLOnConnect(useSSL); email.setFrom(mailSender); email.addTo(requerimento.getDiscente().getEmail()); email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail")); email.setHtmlMsg(writer.toString()); String alternativeMessage = String.format("%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s", LocaleBean.getDefaultMessageBundle().getString("messageMail"), objectRoot.get("REQUERIMENTO"), objectRoot.get("tipoRequerimento"), objectRoot.get("STATUS"), objectRoot.get("status"), objectRoot.get("ATENDENTE"), objectRoot.get("atendente"), objectRoot.get("OBSERVACAO"), objectRoot.get("observacao")); email.setTextMsg(alternativeMessage); email.send(); System.out.println(String.format("message to discente:<%s: %s>", requerimento.getDiscente().getNome(), requerimento.getDiscente().getEmail())); } catch (EmailException | IOException | TemplateException e) { System.out.println("erro ao enviar email"); System.out.println(e); } } }; sender.start(); }
From source file:com.baasbox.service.user.UserService.java
public static void sendResetPwdMail(String appCode, ODocument user) throws Exception { final String errorString = "Cannot send mail to reset the password: "; //check method input if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME)) throw new PasswordRecoveryException(errorString + " invalid user object"); //initialization String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString(); int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger(); if (StringUtils.isEmpty(siteUrl)) throw new PasswordRecoveryException(errorString + " invalid site url (is empty)"); String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString(); String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString(); if (StringUtils.isEmpty(htmlEmail)) htmlEmail = textEmail;/* w w w .j av a 2s . com*/ if (StringUtils.isEmpty(htmlEmail)) throw new PasswordRecoveryException(errorString + " text to send is not configured"); boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean(); boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean(); String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString(); int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger(); if (StringUtils.isEmpty(smtpHost)) throw new PasswordRecoveryException(errorString + " SMTP host is not configured"); String username_smtp = null; String password_smtp = null; if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) { username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString(); password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString(); if (StringUtils.isEmpty(username_smtp)) throw new PasswordRecoveryException(errorString + " SMTP username is not configured"); } String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString(); String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString(); if (StringUtils.isEmpty(emailFrom)) throw new PasswordRecoveryException(errorString + " sender email is not configured"); try { String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email") .toString(); String username = (String) ((ODocument) user.field("user")).field("name"); //Random String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID(); String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes())); //Save on DB ResetPwdDao.getInstance().create(new Date(), sBase64Random, user); //Send mail HtmlEmail email = null; URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl, sitePort, "/user/password/reset/" + sBase64Random); //HTML Email Text ST htmlMailTemplate = new ST(htmlEmail, '$', '$'); htmlMailTemplate.add("link", resetUrl); htmlMailTemplate.add("user_name", username); htmlMailTemplate.add("token", sBase64Random); //Plain text Email Text ST textMailTemplate = new ST(textEmail, '$', '$'); textMailTemplate.add("link", resetUrl); textMailTemplate.add("user_name", username); textMailTemplate.add("token", sBase64Random); email = new HtmlEmail(); email.setHtmlMsg(htmlMailTemplate.render()); email.setTextMsg(textMailTemplate.render()); //Email Configuration email.setSSL(useSSL); email.setSSLOnConnect(useSSL); email.setTLS(useTLS); email.setStartTLSEnabled(useTLS); email.setStartTLSRequired(useTLS); email.setSSLCheckServerIdentity(false); email.setSslSmtpPort(String.valueOf(smtpPort)); email.setHostName(smtpHost); email.setSmtpPort(smtpPort); email.setCharset("utf-8"); if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) { email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp)); } email.setFrom(emailFrom); email.addTo(userEmail); email.setSubject(emailSubject); if (BaasBoxLogger.isDebugEnabled()) { StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName()) .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n") .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n") .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS()) .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity()) .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n") .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n") .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n") .append("SubType: ").append(email.getSubType()).append("\n") .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n") .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n") .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ") .append(email.getReplyToAddresses()).append("\n").append("BCC: ") .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses()) .append("\n") .append("Subject: ").append(email.getSubject()).append("\n") //the following line throws a NPE in debug mode //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n") .append("SentDate: ").append(email.getSentDate()).append("\n"); BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString()); } email.send(); } catch (EmailException authEx) { BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx)); throw new PasswordRecoveryException( errorString + " Could not reach the mail server. Please contact the server administrator"); } catch (Exception e) { BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e)); throw new Exception(errorString, e); } }
From source file:net.wildpark.dswp.supports.MailService.java
public boolean sendEmail(String to, String textBody) { try {/*from w ww . j a v a2 s .c om*/ HtmlEmail email = new HtmlEmail(); email.setCharset("utf-8"); email.setHostName("mail.wildpark.net"); email.setSmtpPort(25); email.setAuthenticator(new DefaultAuthenticator("informer@mksat.net", "22v5C728")); email.setFrom("informer@mksat.net"); email.setSubject("Automatic message from darkside.wildpark.net"); email.setHtmlMsg(textBody); email.addTo(to); email.send(); logFacade.create(new Log("Sended mail " + to)); } catch (EmailException ex) { logFacade.create(new Log("Error with mail sending", ex, LoggerLevel.ERROR)); System.out.println(ex); return false; } return true; }
From source file:org.apache.unomi.plugins.mail.actions.SendMailAction.java
public int execute(Action action, Event event) { String from = (String) action.getParameterValues().get("from"); String to = (String) action.getParameterValues().get("to"); String cc = (String) action.getParameterValues().get("cc"); String bcc = (String) action.getParameterValues().get("bcc"); String subject = (String) action.getParameterValues().get("subject"); String template = (String) action.getParameterValues().get("template"); ST stringTemplate = new ST(template); stringTemplate.add("profile", event.getProfile()); stringTemplate.add("event", event); // load your HTML email template String htmlEmailTemplate = stringTemplate.render(); // define you base URL to resolve relative resource locations try {//from w w w.jav a 2 s.co m new URL("http://www.apache.org"); } catch (MalformedURLException e) { // } // create the email message HtmlEmail email = new ImageHtmlEmail(); // email.setDataSourceResolver(new DataSourceResolverImpl(url)); email.setHostName(mailServerHostName); email.setSmtpPort(mailServerPort); email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword)); email.setSSLOnConnect(mailServerSSLOnConnect); try { email.addTo(to); email.setFrom(from); if (cc != null && cc.length() > 0) { email.addCc(cc); } if (bcc != null && bcc.length() > 0) { email.addBcc(bcc); } email.setSubject(subject); // set the html message email.setHtmlMsg(htmlEmailTemplate); // set the alternative message email.setTextMsg("Your email client does not support HTML messages"); // send the email email.send(); } catch (EmailException e) { logger.error("Cannot send mail", e); } return EventService.NO_CHANGE; }