List of usage examples for org.apache.commons.mail Email addTo
public Email addTo(final String... emails) throws EmailException
From source file:com.doculibre.constellio.wicket.panels.admin.indexing.AdminIndexingPanel.java
private void sendEmail(String hostName, int smtpPort, DefaultAuthenticator authenticator, String sender, String subject, String message, String receiver) throws EmailException { Email email = new SimpleEmail(); email.setHostName(hostName);// ww w. j a v a 2 s . com email.setSmtpPort(smtpPort); email.setAuthenticator(authenticator); email.setFrom(sender); email.setSubject(subject); email.setMsg(message); email.addTo(receiver); email.send(); }
From source file:fr.gael.dhus.messaging.mail.MailServer.java
public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException { email.setHostName(getSmtpServer());/*from w w w . j a va 2 s .c om*/ email.setSmtpPort(getPort()); if (getUsername() != null) { email.setAuthentication(getUsername(), getPassword()); } if (getFromMail() != null) { if (getFromName() != null) email.setFrom(getFromMail(), getFromName()); else email.setFrom(getFromMail()); } if (getReplyto() != null) { try { email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto()))); } catch (AddressException e) { logger.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage()); } } // Message configuration email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject); email.addTo(to); // Add CCed if (cc != null) { email.addCc(cc); } // Add BCCed if (bcc != null) { email.addBcc(bcc); } email.setStartTLSEnabled(isTls()); try { email.send(); } catch (EmailException e) { logger.error("Cannot send email: " + e.getMessage()); throw e; } }
From source file:au.edu.ausstage.utils.EmailManager.java
/** * A method for sending a simple email message * * @param subject the subject of the message * @param message the text of the message * * @return true, if and only if, the email is successfully sent *//*from w w w . j ava2s . c om*/ public boolean sendSimpleMessage(String subject, String message) { // check the input parameters if (InputUtils.isValid(subject) == false || InputUtils.isValid(message) == false) { throw new IllegalArgumentException("The subject and message parameters cannot be null"); } try { // define helper variables Email email = new SimpleEmail(); // configure the instance of the email class email.setSmtpPort(options.getPortAsInt()); // define authentication if required if (InputUtils.isValid(options.getUser()) == true) { email.setAuthenticator(new DefaultAuthenticator(options.getUser(), options.getPassword())); } // turn on / off debugging email.setDebug(DEBUG); // set the host name email.setHostName(options.getHost()); // set the from email address email.setFrom(options.getFromAddress()); // set the subject email.setSubject(subject); // set the message email.setMsg(message); // set the to address String[] addresses = options.getToAddress().split(":"); for (int i = 0; i < addresses.length; i++) { email.addTo(addresses[i]); } // set the security options if (options.getTLS() == true) { email.setTLS(true); } if (options.getSSL() == true) { email.setSSL(true); } // send the email email.send(); } catch (EmailException ex) { if (DEBUG) { System.err.println("ERROR: Sending of email failed.\n" + ex.toString()); } return false; } return true; }
From source file:com.neu.controller.MessageController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource"); String action = request.getParameter("action"); ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); String userName = (String) session.getAttribute("userName"); if (action.equalsIgnoreCase("reply")) { try {/*from ww w . jav a 2s .c o m*/ String receiver = request.getParameter("to"); System.out.println("Printing receiver in reply case: " + receiver); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); UsersBean ub = run.query("select * from userstable where userName =?", user, receiver); if (ub != null) { System.out.println("printing userEmail received from DB: " + ub.getUserEmail()); mv.addObject("toEmail", ub.getUserEmail()); mv.addObject("to", receiver); } mv.setViewName("reply"); } catch (SQLException e) { System.out.println(e); } } else if (action.equalsIgnoreCase("sent")) { System.out.println("In sent case"); try { String receiver = request.getParameter("to"); String receiverEmail = request.getParameter("toEmail"); System.out.println("printing receiver email: " + receiverEmail); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); UsersBean ub = run.query("select * from userstable where userName =?", user, userName); if (ub != null) { String senderEmail = ub.getUserEmail(); System.out.println("printing senderemail: " + senderEmail); ResultSetHandler<MessageBean> msg = new BeanHandler<MessageBean>(MessageBean.class); Object[] params = new Object[4]; params[0] = userName; params[1] = request.getParameter("message"); Date d = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String messageDate = format.format(d); params[2] = messageDate; params[3] = receiver; int inserts = run.update( "Insert into messages (fromUser,message,messageDate,userName) values(?,?,?,?)", params);//Logic to send the email try { Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com");//If a server is capable of sending email, then you don't need the authentication. In this case, an email server needs to be running on that machine. Since we are running this application on the localhost and we don't have a email server, we are simply asking gmail to relay this email. email.setSmtpPort(465); email.setAuthenticator( new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc")); email.setSSLOnConnect(true); email.setFrom(senderEmail);//This email will appear in the from field of the sending email. It doesn't have to be a real email address.This could be used for phishing/spoofing! email.setSubject("Thanks for Signing Up!"); email.setMsg("Welcome to Web tools Lab 5 Spring Application sign up email test!"); email.addTo(receiverEmail);//Will come from the database email.send(); } catch (Exception e) { System.out.println("Email Exception" + e.getMessage()); e.printStackTrace(); } mv.setViewName("messageSent"); } else { mv.addObject("error", "true"); mv.setViewName("index"); } } catch (Exception ex) { System.out.println("Error Message" + ex.getMessage()); ex.printStackTrace(); } } return mv; }
From source file:com.neu.controller.LoginController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource"); String action = request.getParameter("action"); ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); if (action.equalsIgnoreCase("login")) { try {//from w w w. j av a 2 s .c o m String userName = request.getParameter("user"); String password = request.getParameter("password"); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[2]; params[0] = userName; params[1] = password; UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user, params); if (ub != null) { ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>( MessageBean.class); List<MessageBean> msg = run.query("select * from messages where userName =?", messages, userName); session.setAttribute("userName", userName); session.setAttribute("messageList", msg); mv.setViewName("userhome"); } else { mv.addObject("error", "true"); mv.setViewName("index"); } } catch (Exception ex) { System.out.println("Error Message" + ex.getMessage()); } } else if (action.equalsIgnoreCase("logout")) { session.invalidate(); mv.setViewName("index"); } else if (action.equalsIgnoreCase("signup")) { System.out.println("sign up"); // // String userName = request.getParameter("user"); // String password = request.getParameter("password"); // String emailObj = request.getParameter("emailObj"); // // System.out.println("printing details: " + userName + " " +password + " "+emailObj); mv.setViewName("signup"); } else if (action.equalsIgnoreCase("signupsubmit")) { System.out.println("sign up submit"); String userName = request.getParameter("user"); String password = request.getParameter("password"); String email = request.getParameter("email"); System.out.println("printing details: " + userName + " " + password + " " + email); if (userName.equals("") || (password.equals("")) || (email.equals(""))) { System.out.println("empty values"); mv.addObject("error", "true"); } else { ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[3]; params[0] = userName; params[1] = password; params[2] = email; QueryRunner run = new QueryRunner(ds); int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)", params);//Logic to insert into table System.out.println("inserts value " + inserts); if (inserts > 0) { mv.addObject("success", "true"); Email emailObj = new SimpleEmail(); emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj. emailObj.setSmtpPort(465); emailObj.setAuthenticator( new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc")); emailObj.setSSLOnConnect(true); emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing! emailObj.setSubject("TestMail"); emailObj.setMsg("This is spring MVC Contact Application sending you the email"); emailObj.addTo(email);//Will come from the sign up details emailObj.send(); } } mv.setViewName("signup"); } return mv; }
From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java
public void sendNotificationSMS(String send_sms_to_provider, String send_sms_to, String from, String username, String password, String hostname, String portno, boolean setSSLOnConnectFlag, String subject, String message) {/*from ww w. j a v a2s . c om*/ try { send_sms_to_provider = settings.getString(TO_SMS_PROVIDER_PROPERTY); send_sms_to = settings.getString(TO_SMS_PROPERTY); Email smsObject = new SimpleEmail(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); String dateStr = dateFormat.format(cal.getTime()); smsObject.setHostName(hostname); smsObject.setSmtpPort(Integer.parseInt(portno)); smsObject.setAuthenticator(new DefaultAuthenticator(username, password)); smsObject.setSSL(true); smsObject.setFrom(from); smsObject.setSubject(""); smsObject.setMsg("Sonar analysis completed successfully at " + dateStr + " . Please visit " + settings.getString("sonar.host.url") + " for more details!"); //multiple SMS recipients. String[] addrs = StringUtils.split(to_email, "\t\r\n;, "); for (String addr : addrs) { smsObject.addTo(send_sms_to); } smsObject.send(); } catch (EmailException e) { throw new SonarException("Unable to send sms", e); } catch (Exception ex) { // TODO Auto-generated catch block ex.printStackTrace(); } }
From source file:com.cws.esolutions.security.quartz.PasswordExpirationNotifier.java
/** * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) *//*from w ww . java 2s. co m*/ public void execute(final JobExecutionContext context) { final String methodName = PasswordExpirationNotifier.CNAME + "#execute(final JobExecutionContext jobContext)"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("JobExecutionContext: {}", context); } final Map<String, Object> jobData = context.getJobDetail().getJobDataMap(); if (DEBUG) { DEBUGGER.debug("jobData: {}", jobData); } try { UserManager manager = UserManagerFactory .getUserManager(bean.getConfigData().getSecurityConfig().getUserManager()); if (DEBUG) { DEBUGGER.debug("UserManager: {}", manager); } List<String[]> accounts = manager.listUserAccounts(); if (DEBUG) { DEBUGGER.debug("accounts: {}", accounts); } if ((accounts == null) || (accounts.size() == 0)) { return; } Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 30); Long expiryTime = cal.getTimeInMillis(); if (DEBUG) { DEBUGGER.debug("Calendar: {}", cal); DEBUGGER.debug("expiryTime: {}", expiryTime); } for (String[] account : accounts) { if (DEBUG) { DEBUGGER.debug("Account: {}", (Object) account); } List<Object> accountDetail = manager.loadUserAccount(account[0]); if (DEBUG) { DEBUGGER.debug("List<Object>: {}", accountDetail); } try { Email email = new SimpleEmail(); email.setHostName((String) jobData.get("mailHost")); email.setSmtpPort(Integer.parseInt((String) jobData.get("portNumber"))); if ((Boolean) jobData.get("isSecure")) { email.setSSLOnConnect(true); } if ((Boolean) jobData.get("isAuthenticated")) { email.setAuthenticator(new DefaultAuthenticator((String) jobData.get("username"), PasswordUtils.decryptText((String) (String) jobData.get("password"), (String) jobData.get("salt"), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()))); } email.setFrom((String) jobData.get("emailAddr")); email.addTo((String) accountDetail.get(6)); email.setSubject((String) jobData.get("messageSubject")); email.setMsg(String.format((String) jobData.get("messageBody"), (String) accountDetail.get(4))); if (DEBUG) { DEBUGGER.debug("SimpleEmail: {}", email); } email.send(); } catch (EmailException ex) { ERROR_RECORDER.error(ex.getMessage(), ex); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); } } } catch (UserManagementException umx) { ERROR_RECORDER.error(umx.getMessage(), umx); } }
From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java
/** * Send the actual email.//from ww w . j ava 2 s .c o m * * @param oid * @param from * @param recipient * @param subject * @param body * @return */ public boolean email(String oid, String from, String recipient, String subject, String body) { try { Email email = new SimpleEmail(); log.debug("Email host: " + host); log.debug("Email port: " + port); log.debug("Email username: " + username); log.debug("Email from: " + from); log.debug("Email to: " + recipient); log.debug("Email Subject is: " + subject); log.debug("Email Body is: " + body); email.setHostName(host); email.setSmtpPort(Integer.parseInt(port)); email.setAuthenticator(new DefaultAuthenticator(username, password)); // the method setSSL is deprecated on the newer versions of commons // email... email.setSSL("true".equalsIgnoreCase(ssl)); email.setTLS("true".equalsIgnoreCase(tls)); email.setFrom(from); email.setSubject(subject); email.setMsg(body); if (recipient.indexOf(",") >= 0) { String[] recs = recipient.split(","); for (String rec : recs) { email.addTo(rec); } } else { email.addTo(recipient); } email.send(); } catch (Exception ex) { log.debug("Error sending notification mail for oid:" + oid, ex); return false; } return true; }
From source file:com.day.cq.wcm.foundation.forms.impl.MailServlet.java
/** * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse) *//*from w w w. ja va 2 s . c o m*/ protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final MailService localService = this.mailService; if (ResourceUtil.isNonExistingResource(request.getResource())) { logger.debug("Received fake request!"); response.setStatus(500); return; } final ResourceBundle resBundle = request.getResourceBundle(null); final ValueMap values = ResourceUtil.getValueMap(request.getResource()); final String[] mailTo = values.get(MAILTO_PROPERTY, String[].class); int status = 200; if (mailTo == null || mailTo.length == 0 || mailTo[0].length() == 0) { // this is a sanity check logger.error( "The mailto configuration is missing in the form begin at " + request.getResource().getPath()); status = 500; } else if (localService == null) { logger.error("The mail service is currently not available! Unable to send form mail."); status = 500; } else { try { final StringBuilder builder = new StringBuilder(); builder.append(request.getScheme()); builder.append("://"); builder.append(request.getServerName()); if ((request.getScheme().equals("https") && request.getServerPort() != 443) || (request.getScheme().equals("http") && request.getServerPort() != 80)) { builder.append(':'); builder.append(request.getServerPort()); } builder.append(request.getRequestURI()); // construct msg final StringBuilder buffer = new StringBuilder(); String text = resBundle.getString("You've received a new form based mail from {0}."); text = text.replace("{0}", builder.toString()); buffer.append(text); buffer.append("\n\n"); buffer.append(resBundle.getString("Values")); buffer.append(":\n\n"); // we sort the names first - we use the order of the form field and // append all others at the end (for compatibility) // let's get all parameters first and sort them alphabetically! final List<String> contentNamesList = new ArrayList<String>(); final Iterator<String> names = FormsHelper.getContentRequestParameterNames(request); while (names.hasNext()) { final String name = names.next(); contentNamesList.add(name); } Collections.sort(contentNamesList); final List<String> namesList = new ArrayList<String>(); final Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource()); while (fields.hasNext()) { final Resource field = fields.next(); final FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field); for (final FieldDescription desc : descs) { // remove from content names list contentNamesList.remove(desc.getName()); if (!desc.isPrivate()) { namesList.add(desc.getName()); } } } namesList.addAll(contentNamesList); // now add form fields to message // and uploads as attachments final List<RequestParameter> attachments = new ArrayList<RequestParameter>(); for (final String name : namesList) { final RequestParameter rp = request.getRequestParameter(name); if (rp == null) { //see Bug https://bugs.day.com/bugzilla/show_bug.cgi?id=35744 logger.debug("skipping form element {} from mail content because it's not in the request", name); } else if (rp.isFormField()) { buffer.append(name); buffer.append(" : \n"); final String[] pValues = request.getParameterValues(name); for (final String v : pValues) { buffer.append(v); buffer.append("\n"); } buffer.append("\n"); } else if (rp.getSize() > 0) { attachments.add(rp); } else { //ignore } } // if we have attachments we send a multi part, otherwise a simple email final Email email; if (attachments.size() > 0) { buffer.append("\n"); buffer.append(resBundle.getString("Attachments")); buffer.append(":\n"); final MultiPartEmail mpEmail = new MultiPartEmail(); email = mpEmail; for (final RequestParameter rp : attachments) { final ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(), rp.getContentType()); mpEmail.attach(ea, rp.getFileName(), rp.getFileName()); buffer.append("- "); buffer.append(rp.getFileName()); buffer.append("\n"); } } else { email = new SimpleEmail(); } email.setMsg(buffer.toString()); // mailto for (final String rec : mailTo) { email.addTo(rec); } // cc final String[] ccRecs = values.get(CC_PROPERTY, String[].class); if (ccRecs != null) { for (final String rec : ccRecs) { email.addCc(rec); } } // bcc final String[] bccRecs = values.get(BCC_PROPERTY, String[].class); if (bccRecs != null) { for (final String rec : bccRecs) { email.addBcc(rec); } } // subject and from address final String subject = values.get(SUBJECT_PROPERTY, resBundle.getString("Form Mail")); email.setSubject(subject); final String fromAddress = values.get(FROM_PROPERTY, ""); if (fromAddress.length() > 0) { email.setFrom(fromAddress); } if (this.logger.isDebugEnabled()) { this.logger.debug("Sending form activated mail: fromAddress={}, to={}, subject={}, text={}.", new Object[] { fromAddress, mailTo, subject, buffer }); } localService.sendEmail(email); } catch (EmailException e) { logger.error("Error sending email: " + e.getMessage(), e); status = 500; } } // check for redirect String redirectTo = request.getParameter(":redirect"); if (redirectTo != null) { int pos = redirectTo.indexOf('?'); redirectTo = redirectTo + (pos == -1 ? '?' : '&') + "status=" + status; response.sendRedirect(redirectTo); return; } if (FormsHelper.isRedirectToReferrer(request)) { FormsHelper.redirectToReferrer(request, response, Collections.singletonMap("stats", new String[] { String.valueOf(status) })); return; } response.setStatus(status); }
From source file:net.scran24.user.server.services.HelpServiceImpl.java
@Override public void reportUncaughtException(String strongName, List<String> classNames, List<String> messages, List<StackTraceElement[]> stackTraces, String surveyState) { Subject subject = SecurityUtils.getSubject(); ScranUserId userId = (ScranUserId) subject.getPrincipal(); if (userId == null) throw new RuntimeException("User must be logged in"); String rateKey = userId.survey + "#" + userId.username; RateInfo rateInfo = rateMap.get(rateKey); boolean rateExceeded = false; long time = System.currentTimeMillis(); if (rateInfo == null) { rateMap.put(rateKey, new RateInfo(1, time)); } else {/* w ww .java 2s .co m*/ long timeSinceLastRequest = time - rateInfo.lastRequestTime; if (timeSinceLastRequest > 10000) { rateMap.put(rateKey, new RateInfo(1, time)); } else if (rateInfo.requestCount >= 10) { rateExceeded = true; } else { rateMap.put(rateKey, new RateInfo(rateInfo.requestCount + 1, time)); } } if (!rateExceeded) { System.out.println(String.format("Sending email", userId.survey, userId.username)); Email email = new SimpleEmail(); email.setHostName(smtpHostName); email.setSmtpPort(smtpPort); email.setCharset(EmailConstants.UTF_8); email.setAuthenticator(new DefaultAuthenticator(smtpUserName, smtpPassword)); email.setSSLOnConnect(true); StringBuilder sb = new StringBuilder(); for (int i = 0; i < classNames.size(); i++) { sb.append(String.format("%s: %s\n", classNames.get(i), messages.get(i))); StackTraceElement[] deobfStackTrace = deobfuscator.resymbolize(stackTraces.get(i), strongName); for (StackTraceElement ste : deobfStackTrace) { sb.append(String.format(" %s\n", ste.toString())); } sb.append("\n"); } sb.append("Survey state:\n"); sb.append(surveyState); sb.append("\n"); try { email.setFrom("no-reply@intake24.co.uk", "Intake24"); email.setSubject(String.format("Client exception (%s/%s): %s", userId.survey, userId.username, messages.get(0))); email.setMsg(sb.toString()); email.addTo("bugs@intake24.co.uk"); email.send(); } catch (EmailException ee) { log.error("Failed to send e-mail notification", ee); } } }