Ejemplo n.º 1
0
 private void sendEmail(User user, String subject, String text) {
   if (host != null && !host.equals("")) {
     JavaMailSenderImpl sender = new JavaMailSenderImpl();
     sender.setHost(host);
     sender.setPort(port);
     sender.setUsername(smtpUser);
     sender.setPassword(smtpPassword);
     SimpleMailMessage message = new SimpleMailMessage();
     message.setTo(user.getLogin());
     message.setFrom(from);
     message.setSubject(subject);
     message.setText(text);
     try {
       sender.send(message);
       if (log.isDebugEnabled()) {
         log.debug("Sent e-mail to User '" + user.getLogin() + "'!");
       }
     } catch (MailException e) {
       log.warn("Warning! SMTP server error, could not send e-mail.");
       if (log.isDebugEnabled()) {
         log.debug("SMTP Error : " + e.getMessage());
         log.debug("Did you configure your SMTP settings in /META-INF/tatami/tatami.properties ?");
       }
     }
   } else {
     log.debug("SMTP server is not configured in /META-INF/tatami/tatami.properties");
   }
 }
Ejemplo n.º 2
0
  private void sendEmail(String to, String subject, String body, Boolean htmlEmail)
      throws Exception {
    try {
      JavaMailSenderImpl mailSender = (JavaMailSenderImpl) appContext.getBean("mailSender");
      Properties javaMailProperties = mailSender.getJavaMailProperties();
      if (null != javaMailProperties) {
        if (javaMailProperties.get("mail.smtp.localhost") == null
            || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) {
          javaMailProperties.put("mail.smtp.localhost", "localhost");
        }
      }

      MimeMessage mimeMessage = mailSender.createMimeMessage();

      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail);
      helper.setFrom(EmailEngine.getAdminEmail());
      helper.setTo(processMultipleImailAddresses(to.trim()));
      helper.setSubject(subject);
      helper.setText(body, true);

      mailSender.send(mimeMessage);

      logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
      logger.error("Email could not be sent on {} due to: {}", new Date(), me.getMessage());
    }
  }
Ejemplo n.º 3
0
 public boolean send() {
   try {
     MimeMessage msg = javaMailSender.createMimeMessage();
     MimeMessageHelper message = new MimeMessageHelper(msg, true, "UTF-8");
     message.setFrom(from);
     message.setSubject(title);
     message.setTo(toEmails);
     message.setText(getMessage(), true); // 如果发的不是html内容去掉true参数��
     // message.addInline("myLogo",new ClassPathResource("img/mylogo.gif"));
     // message.addAttachment("myDocument.pdf", new ClassPathResource("doc/myDocument.pdf"));
     javaMailSender.send(msg);
   } catch (MessagingException e) {
     e.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("邮件信息导常! 邮件标题为: " + title);
     }
     return false;
   } catch (MailException me) {
     me.printStackTrace();
     if (log.isWarnEnabled()) {
       log.warn("发送邮件失败! 邮件标题为: " + title);
     }
     return false;
   }
   return true;
 }
Ejemplo n.º 4
0
 /**
  * Send a simple message with pre-populated values.
  *
  * @param msg
  */
 public void send(SimpleMailMessage msg) {
   try {
     mailSender.send(msg);
   } catch (MailException ex) {
     // log it and go on
     log.error(ex.getMessage());
   }
 }
Ejemplo n.º 5
0
 /**
  * Send a simple message with pre-populated values.
  *
  * @param msg the message to send
  * @throws org.springframework.mail.MailException when SMTP server is down
  */
 public void send(SimpleMailMessage msg) throws MailException {
   try {
     mailSender.send(msg);
   } catch (MailException ex) {
     log.error(ex.getMessage());
     throw ex;
   }
 }
Ejemplo n.º 6
0
  /**
   * Execute sending the password hint via e-mail.
   *
   * @return success if username works, input if not
   */
  public String execute() {
    List<Object> args = new ArrayList<Object>();

    // ensure that the username has been sent
    if (username == null) {
      log.warn("Username not specified, notifying user that it's a required field.");

      args.add(getText("user.username"));
      addActionError(getText("errors.requiredField", args));
      return INPUT;
    }

    if (log.isDebugEnabled()) {
      log.debug("Processing Password Hint...");
    }

    // look up the user's information
    try {
      User user = userManager.getUserByUsername(username);
      String hint = user.getPasswordHint();

      if (hint == null || hint.trim().equals("")) {
        log.warn("User '" + username + "' found, but no password hint exists.");
        addActionError(getText("login.passwordHint.missing"));
        return INPUT;
      }

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

      mailMessage.setTo(user.getEmail());
      String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
      mailMessage.setSubject(subject);
      mailMessage.setText(msg.toString());
      mailEngine.send(mailMessage);

      args.add(username);
      args.add(user.getEmail());

      saveMessage(getText("login.passwordHint.sent", args));
    } catch (UsernameNotFoundException e) {
      log.warn(e.getMessage());
      args.add(username);
      addActionError(getText("login.passwordHint.error", args));
      getSession().setAttribute("errors", getActionErrors());
      return INPUT;
    } catch (MailException me) {
      addActionError(me.getCause().getLocalizedMessage());
      getSession().setAttribute("errors", getActionErrors());
      return INPUT;
    }

    return SUCCESS;
  }
  private void send(String subject, String content) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setTo(supportEmail);
    mailMessage.setReplyTo(supportEmail);
    mailMessage.setFrom(supportEmail);
    mailMessage.setSubject(subject);
    mailMessage.setText(content);

    try {
      // javaMailSender.send(mailMessage);
    } catch (MailException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 8
0
  public void execute() {
    // 短信
    try {
      List<User> users = userManager.getNotifiedSmsUser();
      for (User user : users) {
        String mobile = user.getMobile();
        if (!StringUtils.isNumeric(mobile)) continue;

        // 待办
        /*                List<FlowNode> todoList = flowNodeManager.getAllPendingNodes(user);
        for (FlowNode todo : todoList) {
            messageManager.buildSms(mobile,todo.getFlow().getTitle());
            todo.setNotified("true");
            flowNodeManager.save(todo);
        }*/
        // 系统消息
        List<Message> allUnSms = messageManager.getAllUnSms(user);
        for (Message msg : allUnSms) {
          if (msg.getNotified().equals("3")) messageManager.buildSms(mobile, msg.getContent());
          else messageManager.buildSms(mobile, msg.getTitle());
          msg.setNotified(MsgConstants.NOTIFIED);
          messageManager.save(msg);
        }
      }
    } catch (Exception e) {
      logger.debug(e.getMessage());
    }

    // 邮件
    try {
      List<User> users = userManager.getNotifiedUsers();
      messages = new ArrayList<MimeMessage>();
      from = userManager.getAdmin().getEmail();

      for (User user : users) {
        List<FlowNode> todoList = flowNodeManager.getAllPendingNodes(user);
        String to = user.getEmail();
        if (StringUtils.isBlank(to)) continue;
        for (FlowNode todo : todoList) {
          buildEmail(to, todo);
          todo.setNotified("true");
          flowNodeManager.save(todo);
        }
      }
      mailSender.send(messages.toArray(new MimeMessage[messages.size()]));
    } catch (MailException e) {
      logger.debug(e.getMessage());
    }
  }
  /**
   * Save the user, encrypting their passwords if necessary
   *
   * @return success when good things happen
   * @throws Exception when bad things happen
   */
  public String save() throws Exception {
    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
      userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (UserExistsException e) {
      log.warn(e.getMessage());
      List<Object> args = new ArrayList<Object>();
      args.add(user.getUsername());
      args.add(user.getEmail());
      addActionError(getText("errors.existing.user", args));

      // redisplay the unencrypted passwords
      user.setPassword(user.getConfirmPassword());
      return INPUT;
    }

    saveMessage(getText("user.registered"));
    getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send an account information e-mail
    mailMessage.setSubject(getText("signup.email.subject"));

    try {
      sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
    } catch (MailException me) {
      addActionError(me.getMostSpecificCause().getMessage());
    }

    return SUCCESS;
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

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

    // ensure that the username has been sent
    if (username == null) {
      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");
    }

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

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

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

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

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

    return new ModelAndView(new RedirectView(request.getContextPath()));
  }
Ejemplo n.º 11
0
  /**
   * Send mail with result
   *
   * @param email recipient adress
   * @param result result of validation
   * @param id identification number of result
   */
  public void sendMail(final String email, final String result, final long id) {

    MimeMessagePreparator preparator =
        new MimeMessagePreparator() {

          public void prepare(MimeMessage mimeMessage) throws Exception {
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
            mimeMessage.setSubject("Výsledek validace POM souboru");
            mimeMessage.setFrom(new InternetAddress("*****@*****.**"));
            mimeMessage.setText("http://localhost:8080/result/result?id=" + id);
            // mimeMessage.setText(result);
          }
        };
    try {
      mailSender.send(preparator);
    } catch (MailException ex) {
      System.err.println(ex.getMessage());
    }
  }
Ejemplo n.º 12
0
 public void sendMail(
     String fromEmail, String toEmail, String ccEmail, String subject, String body)
     throws MailException {
   SimpleMailMessage message = new SimpleMailMessage();
   message.setFrom(fromEmail);
   message.setTo(toEmail);
   if (StringUtils.isNotEmpty(ccEmail)) {
     message.setCc(ccEmail);
   }
   message.setSubject(subject);
   message.setText(body);
   try {
     mailSender.send(message);
     System.out.println("Mail sent");
   } catch (MailException e) {
     e.printStackTrace();
     System.out.println("Mail failed");
     throw e;
   }
 }
  @Override
  @Async
  public void sendViaForm(EmailForm form) {
    message = javaMailSender.createMimeMessage();

    try {
      helper = new MimeMessageHelper(message, true, "UTF-8");
      helper.setFrom(senderMailAddress);
      helper.setSubject(form.getSubject());
      helper.setText(form.getBody());
      helper.setTo(form.getTo());

      javaMailSender.send(message);

      System.out.println("\n Mail sent to: " + form.getTo() + "\n");
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (MailException mailException) {
      mailException.printStackTrace();
    }
  }
  @Override
  @Async
  public void send(String to, String subject, String body) {
    message = javaMailSender.createMimeMessage();

    try {
      // Set MimeMessageHelper
      helper = new MimeMessageHelper(message, true, "UTF-8");

      helper.setSubject(subject);
      helper.setText(body, true);
      helper.setTo(to);
      helper.setFrom(senderMailAddress);

      // Send mail
      javaMailSender.send(message);
      System.out.println("\n Mail sent to: " + to + "\n");
    } catch (MessagingException e) {
      e.printStackTrace();
    } catch (MailException mailException) {
      mailException.printStackTrace();
    }
  }
  public void sendMail(
      final String from, final String to, final String subject, final String text) {

    MimeMessagePreparator preparator =
        new MimeMessagePreparator() {

          @Override
          public void prepare(MimeMessage mimeMessage) throws Exception {

            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setSubject(subject, "UTF-8");
            mimeMessage.setContent(text, "text/html; charset=UTF-8");
            mimeMessage.setFrom(new InternetAddress(from));
            Address[] addresses = new Address[] {new InternetAddress("*****@*****.**")};
            mimeMessage.setReplyTo(addresses);
          }
        };
    try {
      this.mailSender.send(preparator);
    } catch (MailException ex) {
      // simply log it and go on...
      ex.printStackTrace();
    }
  }
Ejemplo n.º 16
0
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      final User user,
      final BindingResult errors,
      final HttpServletRequest request,
      final HttpServletResponse response)
      throws Exception {
    if (request.getParameter("cancel") != null) {
      return getCancelView();
    }

    if (validator != null) { // validator is null during testing
      validator.validate(user, errors);

      if (StringUtils.isBlank(user.getPassword())) {
        errors.rejectValue(
            "password",
            "errors.required",
            new Object[] {getText("user.password", request.getLocale())},
            "Password is a required field.");
      }

      if (errors.hasErrors()) {
        return "signup";
      }
    }

    final Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    // unencrypted users password to log in user automatically
    final String password = user.getPassword();

    try {
      this.getUserManager().saveUser(user);
    } catch (final AccessDeniedException ade) {
      // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
      log.warn(ade.getMessage());
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    } catch (final UserExistsException e) {
      errors.rejectValue(
          "username",
          "errors.existing.user",
          new Object[] {user.getUsername(), user.getEmail()},
          "duplicate user");

      return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    final UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            user.getUsername(), password, user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
      log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));

    try {
      sendUserMessage(
          user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (final MailException me) {
      saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
  }
Ejemplo n.º 17
0
  @RequestMapping(method = RequestMethod.POST)
  public String onSubmit(
      UserForm userForm,
      BindingResult errors,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    if (validator != null) { // validator is null during testing
      validator.validate(userForm, errors);
      if (request.getParameter(Constants.SECURITY_SUPERVISION_CODE)
          == null) { // don't validate when supervision
        if (!validateCaptcha(request)) {
          errors.rejectValue("captcha", "errors.captcha", new Object[] {}, "captcha error");
        }
        if (errors.hasErrors()) {
          return "signup";
        }
      }
    }
    Locale locale = request.getLocale();
    // Set the default user role on this new user
    userForm.addRole(roleManager.getRole(Constants.USER_ROLE));
    try {
      this.getUserManager().savePerson(userForm);
    } catch (UserExistsException e) {
      if (e.isContainsType(StateEnum.USERNAME_EXISTENCE))
        errors.rejectValue(
            "username",
            "errors.existing.user",
            new Object[] {userForm.getUsername()},
            "duplicate user");
      if (e.isContainsType(StateEnum.EMAIL_EXISTENCE))
        errors.rejectValue(
            "email",
            "errors.existing.email",
            new Object[] {userForm.getEmail()},
            "duplicate user email");
      userForm.setPassword(userForm.getConfirmPassword()); // redisplay the unencrypted passwords
      return "signup";
    } catch (Exception e) {
      log.warn(e.getMessage());
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return null;
    }
    saveMessage(request, getText("user.registered", userForm.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);
    // log user in automatically
    UsernamePasswordAuthenticationToken auth =
        new UsernamePasswordAuthenticationToken(
            userForm.getUsername(), userForm.getConfirmPassword(), userForm.getAuthorities());
    auth.setDetails(userForm);
    SecurityContextHolder.getContext().setAuthentication(auth);
    // cas
    SecurityContext.addCasSignin(
        centralAuthenticationService,
        ticketGrantingTicketCookieGenerator,
        userForm.getUsername(),
        userForm.getConfirmPassword(),
        true,
        false,
        response);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
      log.debug("Sending user '" + userForm.getUsername() + "' an account information e-mail");
    }
    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject", locale));
    try {
      RequestUtil.setCookie(
          response,
          Constants.STATES_EMAIL_VERIFIED,
          Long.toString(System.currentTimeMillis()),
          "/");
      sendUserMessage(
          userForm,
          getText("signup.email.message", locale),
          RequestUtil.getAppURL(request)
              + "/hint?"
              + AuthCodeUtil.wrap(userForm.getUsername())
              + "&activation");
    } catch (MailException me) {
      saveError(request, me.getMostSpecificCause().getMessage());
    }
    return getRedirectView("/login", request.getParameter("service"));
  }