@Asynchronous public void sendEmail( final String body, final String subject, List<String> recipients, final String from, List<String> attachment, boolean html) { if (recipients != null && !recipients.isEmpty()) { HtmlEmail email = new HtmlEmail(); try { email.setHostName(MainConfig.EMAIL_SMTP_HOST); email.setSmtpPort(MainConfig.EMAIL_SMTP_PORT); if (!MainConfig.EMAIL_SMTP_USER.isEmpty() && !MainConfig.EMAIL_SMTP_PASSWORD.isEmpty()) { email.setAuthenticator( new DefaultAuthenticator(MainConfig.EMAIL_SMTP_USER, MainConfig.EMAIL_SMTP_PASSWORD)); } email.setTLS(MainConfig.EMAIL_SMTP_TLS); email.setFrom(from, MainConfig.EMAIL_FROM, "UTF-8"); email.setSubject(subject); email.setCharset("UTF-8"); if (html) { email.setHtmlMsg(body); } else { email.setTextMsg(body); } for (String s : recipients) { email.addTo(s); } if (attachment != null && !attachment.isEmpty()) { for (String s : attachment) { EmailAttachment at = new EmailAttachment(); at.setPath(s); at.setDisposition(EmailAttachment.ATTACHMENT); String parts[] = s.split("/"); if (parts.length > 0) { at.setName(parts[parts.length - 1]); } } } email.send(); } catch (Exception e) { logger.error("Can not send e-mail to " + recipients + " with subject: " + subject, e); } } else { logger.warn("Try send email with subject " + subject + " but recipients empty."); } }
public void sendEmail() { try { List<Emails> emails = emailsDao.getEmailsByStatus('N'); if (!ITeachUtility.isEmptyList(emails)) { for (Emails emailToSend : emails) { try { HtmlEmail email = new HtmlEmail(); email.setHostName(ITeachUtility.getPropValue("hostName", true)); email.setSmtpPort(Integer.parseInt(ITeachUtility.getPropValue("portNumber", true))); email.setAuthenticator( new DefaultAuthenticator( ITeachUtility.getPropValue("userName", true), ITeachUtility.getPropValue("password", true))); email.addTo(emailToSend.getEmailTo()); email.setFrom(emailToSend.getEmailFrom(), emailToSend.getEmailFromName()); email.setSubject(emailToSend.getEmailSub()); String emailContent = emailToSend.getEmailBody(); /* * if(StringUtils.isNotBlank(emailToSend. * getEmailAttachments ())){ Set<String> * attachments=ITeachUtility.getStringAsSet(emailToSend. * getEmailAttachments(), ","); } */ // set the html message email.setHtmlMsg("<html>" + emailContent + "</html>"); email.send(); emailToSend.setSendAttempt( emailToSend.getSendAttempt() == null ? 1 : (emailToSend.getSendAttempt() + 1)); emailToSend.setEmailStatus('S'); emailToSend.setSentOn(Calendar.getInstance().getTime()); System.out.println("sent email to " + emailToSend.getEmailTo()); } catch (EmailException e) { // if any exception then updating the attempt. emailToSend.setSendAttempt( emailToSend.getSendAttempt() == null ? 1 : (emailToSend.getSendAttempt() + 1)); e.printStackTrace(); } emailsDao.updateEmails(emailToSend); } } else { System.out.println("No email to send."); } } catch (ITeachException ex) { ex.printStackTrace(); } }
public void sendSmtpTestMail( String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername, String smtpPassword, String toMail) { SystemConfig systemConfig = SystemConfigUtil.getSystemConfig(); MailConfig mailConfig = TemplateConfigUtil.getMailConfig(MailConfig.SMTP_TEST); String subject = mailConfig.getSubject(); String templateFilePath = mailConfig.getTemplateFilePath(); try { email = new HtmlEmail(); email.setHostName(systemConfig.getSmtpHost()); email.setSmtpPort(systemConfig.getSmtpPort()); email.setAuthenticator( new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword())); email.setSSLOnConnect(true); WebAppResourceLoader resourceLoader = new WebAppResourceLoader(); Configuration cfg = Configuration.defaultConfiguration(); GroupTemplate gt = new GroupTemplate(resourceLoader, cfg); Template template = gt.getTemplate(templateFilePath); template.binding("systemConfig", systemConfig); String text = template.render(); email.setFrom( MimeUtility.encodeWord(systemConfig.getShopName()) + " <" + systemConfig.getSmtpFromMail() + ">"); email.setSubject(subject); email.setMsg(text); email.addTo(toMail); email.send(); } catch (EmailException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public boolean sendMail( String subject, String templateFilePath, Map<String, Object> data, String toMail) { boolean isSend = false; try { SystemConfig systemConfig = SystemConfigUtil.getSystemConfig(); email = new HtmlEmail(); email.setHostName(systemConfig.getSmtpHost()); email.setSmtpPort(systemConfig.getSmtpPort()); email.setAuthenticator( new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword())); email.setSSLOnConnect(true); WebAppResourceLoader resourceLoader = new WebAppResourceLoader(); Configuration cfg = Configuration.defaultConfiguration(); GroupTemplate gt = new GroupTemplate(resourceLoader, cfg); Template template = gt.getTemplate(templateFilePath); template.binding(data); String text = template.render(); email.setFrom( MimeUtility.encodeWord(systemConfig.getShopName()) + " <" + systemConfig.getSmtpFromMail() + ">"); email.setSubject(subject); email.setMsg(text); email.addTo(toMail); email.send(); isSend = true; } catch (EmailException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return isSend; }
public static void sendResetPwdMail(String appCode, ODocument user) throws Exception { final String errorString = "Cannot send mail to reset the password: "******" 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; 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); // Plain text Email Text ST textMailTemplate = new ST(textEmail, '$', '$'); textMailTemplate.add("link", resetUrl); textMailTemplate.add("user_name", username); 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); if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) { email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp)); } email.setFrom(emailFrom); email.addTo(userEmail); email.setSubject(emailSubject); if (Logger.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") .append("Message: ") .append(email.toString()) .append("\n") .append("SentDate: ") .append(email.getSentDate()) .append("\n"); Logger.debug("Password Recovery is ready to send: \n" + logEmail.toString()); } email.send(); } catch (EmailException authEx) { Logger.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) { Logger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e)); throw new Exception(errorString, e); } }
public void sendEmailConfirmation( String reportUrl, WoParametri woParametri, User user, List<String> fakture) { try { List<String> emails = new ArrayList<String>(); if (user.getWoPartnerSetting() != null && user.getWoPartnerSetting().get(0) != null && user.getWoPartnerSetting().get(0).getReceiveConfirm() == 1 && user.getWoPartnerSetting().get(0).getEmailAddress() != null) { emails.add(user.getWoPartnerSetting().get(0).getEmailAddress()); } if (user.getWoUserHasRights() != null && user.getWoUserHasRights().get("EMP") != null && user.getWoUserHasRights().get("EMP") && user.getWoUser() != null && user.getWoUser().getEmail() != null) { if (emails.size() == 0 || (emails.size() > 0 && !emails.get(0).equals(user.getWoUser().getEmail()))) emails.add(user.getWoUser().getEmail()); } if ("INTERNI".equals(user.getWoUser().getUserType()) && user.getWoUser().getEmail() != null) { emails.add(user.getWoUser().getEmail()); } if (emails.size() > 0) { String emailContent = woParametri .getConfirmMailContent() .substring(1, Integer.valueOf(woParametri.getConfirmMailContent().length() + "")); log.info( "Prametri su " + woParametri.getMailServerPort() + " " + woParametri.getMailaddress() + " " + woParametri.getMailserver() + " " + woParametri.getPassword()); HtmlEmail email = new HtmlEmail(); email.setHostName(woParametri.getMailserver()); email.setSmtpPort(woParametri.getMailServerPort()); email.setCharset("Windows-1250"); // email.setDebug(true); if (woParametri.getWomailaddress() != null && woParametri.getPassword() != null) { email.setStartTLSRequired(true); // obavezno u slucaju gmail-a email.setAuthenticator( new DefaultAuthenticator(woParametri.getWomailaddress(), woParametri.getPassword())); } String[] sendTo = new String[emails.size()]; for (int i = 0; i < emails.size(); i++) { System.out.println(emails.get(i)); sendTo[i] = emails.get(i); } email.addTo(sendTo); email.setFrom(woParametri.getMailaddress(), "WebOrdering"); email.setSubject("Potvrda porudžbine..."); HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(reportUrl); for (String idDokumenta : fakture) { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("idDokumenta", idDokumenta)); UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8); post.setEntity(sendentity); HttpResponse postResponse = client.execute(post); email.attach( new ByteArrayDataSource(postResponse.getEntity().getContent(), "application/pdf"), idDokumenta + ".pdf", "Document description", EmailAttachment.ATTACHMENT); } // embed the image and get the content id // String cid = email.embed("http://www.apache.org/images/asf_logo_wide.gif", "Apache // logo"); // set the html message // email.setHtmlMsg("<html> Bla bla truc truc <br><br><br> <img src=\"cid:" + cid + // "\"></html>"); // email.setHtmlMsg("<html><font face='verdana' color='#e26f16'><b>" + emailContent + // "</b></font></html>"); email.setHtmlMsg(emailContent); email.send(); } } catch (Exception e) { log.error(e.getMessage(), e); } }