Example usage for org.springframework.mail SimpleMailMessage SimpleMailMessage

List of usage examples for org.springframework.mail SimpleMailMessage SimpleMailMessage

Introduction

In this page you can find the example usage for org.springframework.mail SimpleMailMessage SimpleMailMessage.

Prototype

public SimpleMailMessage(SimpleMailMessage original) 

Source Link

Document

Copy constructor for creating a new SimpleMailMessage from the state of an existing SimpleMailMessage instance.

Usage

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Create a new user in LDAP.//from w ww. ja  va 2 s .  c om
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView newUser(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!isFormSubmission(request)) {
        ModelAndView mav = new ModelAndView("newUser");
        UserLogin ul = new UserLogin();
        mav.addObject("user", ul);
        return mav;
    }

    UserLogin ul = new UserLogin();
    ServletRequestDataBinder binder = createBinder(request, ul);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    String systemUserName = getSystemUserName(ul.getUsername());
    String suggestedUsername = null;
    // validate
    if (StringUtils.isEmpty(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (ul.getUsername().length() < minimumUsernameLength) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    } else if (!validateUsername(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.CONTAINS_INVALID_CHARS);
    } else if (ldapUtils.userNameInUse(systemUserName)) {
        // iterate until a username available
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            suggestedUsername = getSystemUserName(ul.getUsername() + i);
            if (!ldapUtils.userNameInUse(suggestedUsername)) {
                break;
            }
        }
        result.rejectValue("username", ErrorMessageKeys.USERNAME_IN_USE);
    }

    if (StringUtils.isEmpty(ul.getFirstName())) {
        result.rejectValue("firstName", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getSurname())) {
        result.rejectValue("surname", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }

    if (!StringUtils.isEmpty(ul.getEmail())) {
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(ul.getEmail());
        boolean validEmail = m.matches();
        if (!validEmail)
            result.rejectValue("email", ErrorMessageKeys.INVALID_VALUE);
    } else {
        result.rejectValue("email", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (!validatePassword(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    }

    if (result.hasErrors()) {
        ModelAndView mav = new ModelAndView("newUser");
        if (suggestedUsername != null) {
            mav.addObject("suggestedUsername", suggestedUsername);
        }
        mav.addObject(BindingResult.MODEL_KEY_PREFIX + "user", result);
        return mav;
    }

    // send verification email
    SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
    verificationMessage.setTo(ul.getEmail());
    String encryptedPassword = passwordUtils.encryptPassword(ul.getPassword(), true);
    verificationMessage.setSubject("Confirm e-mail address for GBIF Data Portal");
    verificationMessage.setText("Please visit the following link to confirm your e-mail address:\n\n"
            + "http://" + request.getHeader("host") + request.getContextPath() + "/user/verification" + "?fn="
            + ul.getFirstName() + "&sn=" + ul.getSurname() + "&e=" + ul.getEmail() + "&u=" + ul.getUsername()
            + "&p=" + encryptedPassword);
    try {
        mailSender.send(verificationMessage);
    } catch (MailException e) {
        // simply log it and go on...
        logger.error("Couldn't send message", e);
        ModelAndView mav = new ModelAndView("registrationVerificationFailureView");
        mav.addObject("user", ul);
        return mav;
    }

    // successful
    ModelAndView mav = new ModelAndView("registrationVerificationSuccessView");
    mav.addObject("user", ul);
    return mav;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * This will send an email for approval to portal@gbif.org to ask if someone can see a providers details
 * //from   w w w. ja v  a  2s .c o  m
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView sendRegistrationLoginsRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String user = request.getParameter("user");
    if (StringUtils.isEmpty(user)) {
        user = request.getRemoteUser();
    }
    UserLogin ul = ldapUtils.getUserLogin(user);

    String[] businessKeysToRemove = request.getParameterValues("businessKeyToRemove");
    List<String> existingKeys = uddiUtils.getAssociatedBusinessKeys(user);

    // remove the selected registration logins
    if (businessKeysToRemove != null) {
        for (String element : businessKeysToRemove) {
            if (existingKeys.contains(element))
                uddiUtils.deleteRegistrationLogin(user, element);
        }
    }

    // send approval email
    String[] businessKeys = request.getParameterValues(REQUEST_BUSINESS_UDDI_KEY);

    // if not businesskeys selected, non requested return to menu
    if (businessKeys == null) {
        return new ModelAndView(new RedirectView(request.getContextPath() + "/register/"));
    }

    // send verification email
    SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
    verificationMessage.setTo(adminEmail);
    verificationMessage.setSubject("User has requested access to Provider Details");
    StringBuffer sb = new StringBuffer("Please click here to review request:\n\n");
    sb.append("http://");
    sb.append(request.getHeader("host"));
    sb.append(request.getContextPath());
    sb.append("/register/reviewUserRequest");
    sb.append("?u=" + user);
    for (String businessKey : businessKeys) {
        sb.append("&r=");
        sb.append(businessKey);
    }
    verificationMessage.setText(sb.toString());
    try {
        mailSender.send(verificationMessage);
    } catch (MailException e) {
        // simply log it and go on...
        logger.error("Couldn't send message", e);
        ModelAndView mav = new ModelAndView("emailDetailsFailureView");
        return mav;
    }

    // request sent view
    ModelAndView mav = new ModelAndView("requestSentView");
    mav.addObject("userLogin", ul);
    return mav;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Update registration logins, creating those for the business keys passed in the request.
 * //from www  .j  a va 2 s  .  com
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView updateRegistrationLogins(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String user = request.getParameter("user");
    boolean sendEmail = ServletRequestUtils.getBooleanParameter(request, "sendEmail", false);

    // if user is not supplied in a parameter, update is for the current user
    if (StringUtils.isEmpty(user)) {
        user = request.getRemoteUser();
    }

    String[] businessKeys = request.getParameterValues(REQUEST_BUSINESS_UDDI_KEY);
    String[] businessKeysToRemove = request.getParameterValues("businessKeyToRemove");
    List<String> existingKeys = uddiUtils.getAssociatedBusinessKeys(user);
    List<String> createdRegistrations = new ArrayList<String>();

    // add the selected registration logins
    if (businessKeys != null) {
        for (int i = 0; i < businessKeys.length; i++) {
            if (!existingKeys.contains(businessKeys[i])) {
                uddiUtils.createRegistrationLogin(user, businessKeys[i]);
                createdRegistrations.add(businessKeys[i]);
            }
        }
    }

    // if required sent a notification email
    if (sendEmail && !createdRegistrations.isEmpty()) {
        UserLogin userLogin = ldapUtils.getUserLogin(user);
        // send verification email
        SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
        verificationMessage.setTo(userLogin.getEmail());
        verificationMessage.setSubject("User has been granted access to Provider Details");
        StringBuffer sb = new StringBuffer(
                "Your request to access the details of the following providers has been granted:\n\n");
        for (String createdRegistration : createdRegistrations) {
            ProviderDetail pd = uddiUtils.createProviderFromUDDI(createdRegistration, userLogin.getUsername());
            sb.append(pd.getBusinessName());
            sb.append("\n");
        }
        verificationMessage.setText(sb.toString());
        try {
            mailSender.send(verificationMessage);
        } catch (MailException e) {
            // simply log it and go on...
            logger.error("Couldn't send message", e);
        }
    }

    // remove the selected registration logins
    if (businessKeysToRemove != null) {
        for (String element : businessKeysToRemove) {
            if (existingKeys.contains(element))
                uddiUtils.deleteRegistrationLogin(user, element);
        }
    }
    return new ModelAndView(new RedirectView(request.getContextPath() + "/register/"));
}

From source file:org.springframework.data.hadoop.admin.examples.EmailNotification.java

@Override
public void afterJob(JobExecution jobExecution) {
    logger.info("afterJob enter");
    SimpleMailMessage message = new SimpleMailMessage(templateMessage);
    message.setSubject("Spring Batch Job Status");
    message.setText("Job " + jobExecution.getJobInstance().getJobName() + " completed. Status is: "
            + jobExecution.getStatus());
    try {//from ww w  .  j a  v a2s  .  c  om
        mailSender.send(message);
    } catch (Throwable t) {
        logger.error("send mail failed", t);
    }
    logger.info("sent mail");
}

From source file:org.uhp.portlets.news.service.NotificationServiceImpl.java

private void sendDailyEmailForTopics(final Category category) {

    final List<Topic> topicsForToday = this.getPendingTopics(category.getCategoryId());

    if (topicsForToday.size() < 1) {
        return;/*from   ww w.  j av  a  2s  .com*/
    }

    final List<IEscoUser> managers = this.getOnlyTopicManagersForTopics(category.getCategoryId(),
            topicsForToday);

    if (managers.isEmpty()) {
        return;
    }
    for (IEscoUser user : managers) {
        if (user.getEmail() != null && user.getEmail().length() > 0) {
            SimpleMailMessage message = new SimpleMailMessage(templateMessage);
            message.setTo(user.getEmail());
            String text = message.getText();
            List<Topic> userTopics = filterUserTopics(user, topicsForToday);
            String[] tIds = new String[userTopics.size()];
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (Topic t : userTopics) {
                tIds[i++] = String.valueOf(t.getTopicId());
                sb.append(t.getName());
                sb.append(" [");
                int k = itemDao.getPendingItemsCountByTopic(t.getTopicId());
                sb.append(k + "]\n");

            }

            text = StringUtils.replace(text, "%NB%",
                    Integer.toString(this.itemDao.getPendingItemsCountByTopics(tIds)));
            text = StringUtils.replace(text, "%CATEGORY%", category.getName());
            text = StringUtils.replace(text, "%TOPICS%", sb.toString());
            message.setText(text);

            try {
                LOG.debug(message);
                this.mailSender.send(message);
            } catch (MailException e) {
                LOG.error("Notification Service:: An exception occured when sending mail, "
                        + "have you correctly configured your mail engine ?" + e);

            }
        }
    }

}

From source file:org.uhp.portlets.news.service.NotificationServiceImpl.java

private void sendDailyEmailForCategory(final Category category) {
    Long cId = category.getCategoryId();
    String n = "";
    LOG.debug("sendDailyEmailForCategory " + category.getName());
    List<Topic> topicsForToday = this.getPendingTopics(cId);
    if (topicsForToday.size() < 1) {
        LOG.debug("send Daily Email For Category [" + category.getName()
                + "] : nothing new, no notification sent");
        return;//from  ww  w  .j  a  va  2  s  .  c  o m
    }
    Set<IEscoUser> managers = this.getManagersForCategory(category);

    if (managers.isEmpty()) {
        return;
    }

    try {
        n = Integer.toString(this.itemDao.getPendingItemsCountByCategory(category.getCategoryId()));
    } catch (DataAccessException e1) {
        LOG.error("Notification error : " + e1.getMessage());

    }
    SimpleMailMessage message = new SimpleMailMessage(templateMessage);
    LOG.debug("send Daily Email For Category [" + category.getName() + "] : status OK");
    String[] recip = new String[managers.size()];
    int nb = 0;
    for (IEscoUser user : managers) {
        if (user.getEmail() != null && user.getEmail().length() > 0) {
            recip[nb++] = user.getEmail();
        }
    }

    message.setTo(recip);

    String text = message.getText();
    text = StringUtils.replace(text, "%NB%", n);
    text = StringUtils.replace(text, "%CATEGORY%", category.getName());
    text = StringUtils.replace(text, "%TOPICS%", this.getPendingTopicsForCategory(cId));
    message.setText(text);

    try {
        LOG.info(message);
        mailSender.send(message);
    } catch (MailException e) {
        LOG.error("Notification Service:: An exception occured when sending mail,"
                + " have you correctly configured your mail engine ?" + e);
    }

}