Example usage for org.springframework.mail MailException getMessage

List of usage examples for org.springframework.mail MailException getMessage

Introduction

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

Prototype

@Override
@Nullable
public String getMessage() 

Source Link

Document

Return the detail message, including the message from the nested exception if there is one.

Usage

From source file:csns.web.controller.UserController.java

@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public String resetPassword(HttpServletRequest request, ModelMap models) {
    String username = request.getParameter("username");
    String cin = request.getParameter("cin");
    String email = request.getParameter("email");

    User user = null;/*from   w  w  w  .  jav a 2  s .  co  m*/
    if (StringUtils.hasText(cin))
        user = userDao.getUserByCin(cin);
    else if (StringUtils.hasText(username))
        user = userDao.getUserByUsername(username);
    else if (StringUtils.hasText(email))
        user = userDao.getUserByEmail(email);

    models.put("backUrl", defaultUrls.homeUrl(request));

    if (user == null) {
        models.put("message", "error.reset.password.user.not.found");
        return "error";
    }

    if (user.isTemporary()) {
        models.put("message", "error.reset.password.temporary.user");
        return "error";
    }

    String newPassword = "" + (int) (Math.random() * 100000000);
    user.setPassword(passwordEncoder.encodePassword(newPassword, null));
    userDao.saveUser(user);

    logger.info("Reset password for " + user.getUsername());

    Map<String, Object> vModels = new HashMap<String, Object>();
    vModels.put("username", user.getUsername());
    vModels.put("password", newPassword);
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email.resetPassword.vm",
            appEncoding, vModels);

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(user.getPrimaryEmail());
    message.setFrom(appEmail);
    message.setText(text);
    try {
        mailSender.send(message);
        logger.info("Password reset message sent to " + user.getPrimaryEmail());
    } catch (MailException e) {
        logger.error(e.getMessage());
        models.put("message", "error.reset.password.email.failure");
        return "error";
    }

    models.put("message", "status.reset.password");
    return "status";
}

From source file:br.com.jreader.controller.RegistrationBean.java

private boolean sendMailActivation() {
    try {/* w  w w. j a  v a 2  s .  c  o  m*/
        EmailService emailService = (EmailService) ServiceFinder.findBean("emailService");
        emailService.sendEmailRegistration(user);
    } catch (MailException me) {
        System.out.println("No conseguiu enviar o e-mail. " + me.getMessage());
        return false;
    }

    return true;
}

From source file:com.globocom.grou.report.ReportService.java

private void notifyByMail(Test test, String email, Map<String, Double> result) throws Exception {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setTo(email);//from   w w  w.j a v a 2  s  .  c  o  m
        messageHelper.setFrom(MAIL_FROM);
        messageHelper.setSubject(getSubject(test));
        Context context = new Context();
        context.setVariable("project", test.getProject());
        context.setVariable("name", test.getName());
        HashMap<String, Object> testContext = new HashMap<>();
        testContext.put("dashboard", test.getDashboard());
        testContext.put("loaders", test.getLoaders().stream().map(Loader::getName).collect(Collectors.toSet()));
        testContext.put("properties", test.getProperties());
        testContext.put("id", test.getId());
        testContext.put("created", test.getCreatedDate().toString());
        testContext.put("lastModified", test.getLastModifiedDate().toString());
        testContext.put("durationTimeMillis", test.getDurationTimeMillis());
        context.setVariable("testContext", mapper.writeValueAsString(testContext).split("\\R"));
        Set<String> tags = test.getTags();
        context.setVariable("tags", tags);
        context.setVariable("metrics", new TreeMap<>(result));
        String content = templateEngine.process("reportEmail", context);
        messageHelper.setText(content, true);
    };
    try {
        emailSender.send(messagePreparator);
        LOGGER.info(
                "Test " + test.getProject() + "." + test.getName() + ": sent notification to email " + email);
    } catch (MailException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:com.sfs.dao.EmailMessageDAOImpl.java

/**
 * Deliver the email message.//w w w .  java 2s.c om
 *
 * @param emailMessage the email message
 * @param message the message
 *
 * @throws SFSDaoException the SFS dao exception
 */
private void deliver(final EmailMessageBean emailMessage, final MimeMessage message) throws SFSDaoException {
    // Send the email message
    try {
        javaMailSender.send(message);
    } catch (MailException me) {
        dataLogger.error("Error sending email: " + me.getMessage());
        throw new SFSDaoException("Error sending email: " + me.getMessage());
    }
}

From source file:alpha.portal.webapp.controller.PasswordHintController.java

/**
 * Handle request.//  w w  w .  j a v  a2  s .c  o  m
 * 
 * @param request
 *            the request
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(final HttpServletRequest request) throws Exception {
    this.log.debug("entering 'handleRequest' method...");

    final String username = request.getParameter("username");
    final MessageSourceAccessor text = new MessageSourceAccessor(this.messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        this.log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }

    this.log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        final User user = this.userManager.getUserByUsername(username);

        final StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        this.message.setTo(user.getEmail());
        final String subject = '[' + text.getMessage("webapp.name") + "] "
                + text.getMessage("user.passwordHint");
        this.message.setSubject(subject);
        this.message.setText(msg.toString());
        this.mailEngine.send(this.message);

        this.saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (final UsernameNotFoundException e) {
        this.log.warn(e.getMessage());
        this.saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (final MailException me) {
        this.log.warn(me.getMessage());
        this.saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:csns.web.controller.SectionGradeController.java

private void emailGrade(Enrollment enrollment) {
    if (enrollment.getGrade() == null || enrollment.isGradeMailed())
        return;//from   ww  w  .j  ava2 s . c om

    User instructor = SecurityUtils.getUser();
    User student = enrollment.getStudent();

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(instructor.getEmail());
    message.setTo(student.getEmail());

    Course course = enrollment.getSection().getCourse();
    String subject = course.getCode() + " Grade";
    message.setSubject(subject);

    Map<String, Object> vModels = new HashMap<String, Object>();
    vModels.put("grade", enrollment.getGrade().getSymbol());
    String comments = enrollment.getComments();
    vModels.put("comments", comments != null ? comments : "");
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email.section.grade.vm",
            appEncoding, vModels);
    message.setText(text);

    try {
        mailSender.send(message);
        enrollment.setGradeMailed(true);
        enrollmentDao.saveEnrollment(enrollment);
        logger.info(instructor.getUsername() + " sent " + course.getCode() + " grade to " + student.getEmail());
    } catch (MailException e) {
        logger.warn(instructor.getUsername() + " failed to send " + course.getCode() + " grade to "
                + student.getEmail());
        logger.debug(e.getMessage());
    }
}

From source file:csns.web.controller.SubmissionController.java

private void emailGrade(Submission submission) {
    if (!StringUtils.hasText(submission.getGrade()) || submission.isGradeMailed())
        return;// w  w  w  .  ja  v  a  2 s .c  om

    User instructor = SecurityUtils.getUser();
    User student = submission.getStudent();

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(instructor.getEmail());
    message.setTo(student.getEmail());

    String subject = submission.getAssignment().getSection().getCourse().getCode() + " "
            + submission.getAssignment().getName() + " Grade";
    message.setSubject(subject);

    Map<String, Object> vModels = new HashMap<String, Object>();
    vModels.put("grade", submission.getGrade());
    String comments = submission.getComments();
    vModels.put("comments", comments != null ? comments : "");
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email.submission.grade.vm",
            appEncoding, vModels);
    message.setText(text);

    try {
        mailSender.send(message);
        submission.setGradeMailed(true);
        submissionDao.saveSubmission(submission);
        logger.info(instructor.getUsername() + " sent grade to " + student.getEmail());
    } catch (MailException e) {
        logger.warn(instructor.getUsername() + " failed to send grade to " + student.getEmail());
        logger.debug(e.getMessage());
    }
}

From source file:edu.txstate.dmlab.clusteringwiki.web.RegisterController.java

@RequestMapping("register.*")
public String getRegisterPage(HttpServletRequest request, HttpServletResponse response, Model model) {

    String action = request.getParameter("applAction");
    if (action != null && action.equals("register") && isAjaxRequest(request)) {
        //requesting registration
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String firstName = request.getParameter("firstname");
        String lastName = request.getParameter("lastname");

        if (email == null || password == null) {
            sendOutput(response, "{\"error\":\"Invalid registration request received.\"}");
            return null;
        }//  w  w w  . java  2  s .c  om

        email = email.toLowerCase();

        IUserDao dao = applicationUser.getUserDao();

        User user = dao.selectUserByEmail(email);
        if (user != null) {
            sendOutput(response,
                    "{\"error\":\"An account is already registered with this "
                            + "email. Please use the forgot password feature to retrieve your credentials "
                            + "or choose an alternate email address.\"}");
            return null;
        }

        //Create a thread safe "sandbox" of the mailMessage
        SimpleMailMessage msg = new SimpleMailMessage(mailMessage);
        msg.setSubject("ClusteringWiki account created");
        msg.setTo(email);
        msg.setText("Dear " + firstName + ", \n\n"
                + "A ClusteringWiki account has been created for this email address.  Log in to ClusteringWiki to "
                + "start editing search result clusters.  Right-click on nodes to access available "
                + "editing operations.  Your edits will improve search for you as well as others "
                + "quering similar things.  \n\n " + "\n\nThank you,\n\nClusteringWiki Admin");
        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            if (ex.contains(com.sun.mail.smtp.SMTPAddressFailedException.class)) {
                sendOutput(response,
                        "{\"error\":\"Invalid email address.  Please specify a valid email address.\"}");
            } else if (!ex.contains(com.sun.mail.smtp.SMTPSendFailedException.class)) {
                //ignore not being able to send this message out.
                sendOutput(response, "{\"error\":\"Email message could not be sent: <br><br>"
                        + StringEscapeUtils.escapeJavaScript(ex.getMessage().replace("\n", "<br>")) + "\"}");
            }
            return null;
        }

        user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setFirstName(firstName);
        user.setLastName(lastName);
        try {
            dao.saveUser(user);
        } catch (Exception e) {
            sendOutput(response, "{\"error\":\"Registration failed: " + e.getMessage() + ".\"}");
            return null;
        }

        applicationUser.setEmail(email);
        applicationUser.setPassword(password);
        try {
            applicationUser.logIn();
        } catch (Exception e) {
            sendOutput(response, "{\"error\":\"Login error: " + e.getMessage() + "\"}");
            return null;
        }

        sendOutput(response, "{\"success\":true}");
        return null;
    }

    return "register";
}

From source file:edu.txstate.dmlab.clusteringwiki.web.LoginController.java

@RequestMapping("reminder.*")
public void sendReminder(HttpServletRequest request, HttpServletResponse response, Model model) {
    // send an email with link to allow changing password
    String action = request.getParameter("applAction");
    if (action != null && action.equals("sendReminder") && isAjaxRequest(request)) {
        //requesting registration
        String email = request.getParameter("email");

        if (email == null) {
            sendOutput(response, "{\"error\":\"Invalid reminder request received.\"}");
            return;
        }//from  w w w.j  a v a2  s. c  o  m

        email = email.toLowerCase();

        IUserDao dao = applicationUser.getUserDao();

        User user = dao.selectUserByEmail(email);
        if (user == null) {
            sendOutput(response, "{\"error\":\"Invalid email.  Please try again.\"}");
            return;
        }

        //create password request link
        CredentialsRequest cred = new CredentialsRequest();
        cred.setEmail(email);
        String link = request.getRequestURL().toString();
        link = link.replace("reminder.html", "changePassword.html?key=" + cred.getKey());

        //Create a thread safe "sandbox" of the mailMessage
        SimpleMailMessage msg = new SimpleMailMessage(mailMessage);
        msg.setTo(email);
        msg.setText("Dear " + user.getFirstName() + ", \n\n"
                + "We have received a forgot password request at ClusteringWiki for the account "
                + "associated with this email address.  If you did not initiate this request, please "
                + "ignore this email message.  Otherwise, copy and paste the link below in your "
                + "browser to complete your password reset.  Please note this forgot pasword request "
                + "will expire in one hour. \n\n " + link + "\n\nThank you,\n\nClusterWiki Admin");
        try {
            mailSender.send(msg);
        } catch (MailException ex) {
            if (ex.contains(com.sun.mail.smtp.SMTPAddressFailedException.class)) {
                sendOutput(response,
                        "{\"error\":\"The email address is no longer valid.  Please contact an administrator or create a new account.\"}");
            } else if (ex.contains(com.sun.mail.smtp.SMTPSendFailedException.class)) {
                //ignore not being able to send this message out.
                sendOutput(response,
                        "{\"error\":\"Email message could not be sent.  Please try again later.\"}");
            } else
                sendOutput(response, "{\"error\":\"Email message could not be sent: <br><br>"
                        + StringEscapeUtils.escapeJavaScript(ex.getMessage().replace("\n", "<br>")) + "\"}");
            return;
        }

        //make valid and save credentials request
        cred.setValid(1);
        try {
            credentialsRequestDao.saveCredentialsRequest(cred);
        } catch (Exception e) {
            sendOutput(response, "{\"error\":\"Credential request could not be saved.  Please try again.\"}");
            return;
        }

        sendOutput(response, "{\"success\":true}");
        return;
    }
}

From source file:edu.washington.iam.registry.ws.RelyingPartyController.java

@RequestMapping(value = "/rp", method = RequestMethod.DELETE)
public ModelAndView deleteRelyingParty(@RequestParam(value = "id", required = true) String id,
        @RequestParam(value = "mdid", required = true) String mdid,
        @RequestParam(value = "role", required = false) String role,
        @RequestParam(value = "xsrf", required = false) String paramXsrf, InputStream in,
        HttpServletRequest request, HttpServletResponse response) {

    RPSession session = processRequestInfo(request, response, false);
    if (session == null)
        return (emptyMV());

    log.info("DELETE for: " + id);
    int status = 200;

    if (session.isBrowser && !(paramXsrf != null && paramXsrf.equals(session.xsrfCode))) {
        log.info("got invalid xsrf=" + paramXsrf + ", expected+" + session.xsrfCode);
        return emptyMV("invalid session (xsrf)");
    }/*from   w  ww.  j  av a  2 s .  c o  m*/

    ModelAndView mv = emptyMV("OK dokey delete rp");

    try {
        if (!userCanEdit(session, id)) {
            status = 401;
            mv.addObject("alert", "You are not the owner.");
        } else {
            status = proxyManager.removeRelyingParty(id);
            status = filterPolicyManager.removeEditableRelyingParty(id);
            status = rpManager.removeRelyingParty(id, mdid);
        }
    } catch (FilterPolicyException e) {
        mv.addObject("alert", "delete of filter policy failed:\n" + e.getCause());
        response.setStatus(500);
        return mv;
    } catch (DNSVerifyException e) {
        mv.addObject("alert", "Could not verify ownership:\n" + e.getCause());
        response.setStatus(500);
        return mv;
    }
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setTo(mailTo);
    msg.setText(
            "User '" + session.remoteUser + "' deleted metadata for '" + id + "'.\nRequest status: " + status);
    try {
        this.mailSender.send(msg);
    } catch (MailException ex) {
        log.error("sending mail: " + ex.getMessage());
    }

    response.setStatus(status);
    return mv;
}