コード例 #1
1
  private void sendEmail(String from, String to, String subject, String message) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setFrom(from);
    mailMessage.setTo(to.split(","));

    mailMessage.setSubject(subject);
    mailMessage.setText(message);

    mailSender.send(mailMessage);
  }
コード例 #2
0
  /**
   * 이메일을 전송한다.
   *
   * @param mntrngLog 모니터링 대상정보
   * @return
   */
  private void sendEmail(DbMntrngLog mntrngLog) {
    String subject = null;
    String text = null;
    String errorContents = null;

    SimpleMailMessage msg = new SimpleMailMessage(this.mntrngMessage);
    // 수신자
    msg.setTo(mntrngLog.getMngrEmailAddr());
    // 메일제목
    subject = msg.getSubject();
    subject = EgovStringUtil.replace(subject, "{모니터링종류}", "DB서비스모니터링");
    msg.setSubject(subject);
    // 메일내용
    text = msg.getText();
    text = EgovStringUtil.replace(text, "{모니터링종류}", "DB서비스모니터링");
    errorContents = "데이타소스명 : " + mntrngLog.getDataSourcNm() + "\n";
    errorContents = errorContents + "서버명  : " + mntrngLog.getServerNm() + "\n";
    errorContents = errorContents + "DBMS종류 : " + mntrngLog.getDbmsKindNm() + "\n";
    errorContents = errorContents + "체크SQL : " + mntrngLog.getCeckSql() + "\n";
    errorContents = errorContents + "상태 : " + mntrngLog.getMntrngSttusNm() + "\n";
    errorContents = errorContents + "모니터링시각 : " + mntrngLog.getCreatDt() + "\n";
    errorContents = errorContents + "에러메시지 : " + mntrngLog.getLogInfo() + "\n";
    text = EgovStringUtil.replace(text, "{에러내용}", errorContents);
    msg.setText(text);

    this.mntrngMailSender.send(msg);
  }
コード例 #3
0
ファイル: MailService.java プロジェクト: SanziShi/Symagic
  private static void sendMail(String str, String sendTo, String subject) {
    if (javaMail == null) {
      try {
        javaMail = new JavaMailSenderImpl();

        javaMail.setUsername(MAIL_USERNAME);
        javaMail.setPassword(MAIL_PASSWORD);

        Properties prop = new Properties();
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.debug", "true");
        prop.setProperty("mail.smtp.socketFactory.port", "465");
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.port", "465");
        prop.setProperty("host", MAIL_SMTP);

        javaMail.setJavaMailProperties(prop);
        javaMail.setProtocol("smtp");
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    // 初始化邮件信息
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(MAIL_USERNAME + "@" + MAIL_HOST);
    message.setTo(sendTo);
    message.setSubject(subject);
    message.setText(str);

    javaMail.send(message);
  }
コード例 #4
0
 /** This method will send compose and send the message */
 public void sendMail(String to, String subject, String body) {
   SimpleMailMessage message = new SimpleMailMessage();
   message.setTo(to);
   message.setSubject(subject);
   message.setText(body);
   mailSender.send(message);
 }
コード例 #5
0
ファイル: MailService.java プロジェクト: ptemplier/tatami
 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");
   }
 }
コード例 #6
0
 private SimpleMailMessage constructEmail(String subject, String body, User user) {
   final SimpleMailMessage email = new SimpleMailMessage();
   email.setSubject(subject);
   email.setText(body);
   email.setTo(user.getEmail());
   email.setFrom(env.getProperty("support.email"));
   return email;
 }
コード例 #7
0
ファイル: RegistrationMail.java プロジェクト: bwolf/quotes
 @Override
 public SimpleMailMessage getMailMessage() {
   final SimpleMailMessage msg = new SimpleMailMessage(this.mailTemplateMessage);
   msg.setTo(getEmail());
   msg.setSubject(getMessageSubject());
   msg.setText(getMessageBody());
   return msg;
 }
コード例 #8
0
  private boolean handleAlert(
      final User user,
      final Alert alert,
      final String subject,
      final String message,
      final Long creatorId) {
    List<UserContact> contacts = user.getContactInfo();
    if (contacts == null) {
      return false;
    }

    // get the user's preferred contact method
    UserContact contact = null;
    for (UserContact aContact : contacts) {
      if (aContact.getPriority() == null) {
        continue;
      }
      if (contact == null || (aContact.getPriority() < contact.getPriority())) {
        contact = aContact;
      }
    }
    if (contact == null) {
      log.debug(
          "User {} has no preferred contact method, not sending alert {}",
          user.getUsername(),
          alert.getAlertType());
      return false;
    }

    // send the user an alert... only email supported currently
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(contact.getContact());
    msg.setText(message);
    switch (contact.getKind()) {
      case MOBILE:
        // treat as an email to their mobile number
        // TODO: extract out mobile SMS handling to configurable service
        msg.setTo(contact.getContact().replaceAll("\\D", "") + "@isms.net.nz");
        msg.setFrom("*****@*****.**");

        break;

      case EMAIL:
        msg.setSubject(subject);
        msg.setFrom("*****@*****.**");
        break;

      default:
        log.debug(
            "User {} contact type {} not supported in alerts",
            user.getUsername(),
            contact.getKind());
        return false;
    }
    sendMailMessage(msg, creatorId);
    return true;
  }
コード例 #9
0
  private void sendUpgradeEMail(User user) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setTo(user.getEmail());
    mailMessage.setFrom("*****@*****.**");
    mailMessage.setSubject("Upgrade 안내");
    mailMessage.setText("사용자님의 등급이 " + user.getLevel().name());

    this.mailSender.send(mailMessage);
  }
コード例 #10
0
  public void sendMail(String from, String to, String subject, String msg) {

    SimpleMailMessage message = new SimpleMailMessage();
    System.out.println("inside mail sendmail");
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(msg);
    mailSender.send(message);
  }
コード例 #11
0
  @Test
  @Ignore
  public void doSendMail() {
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo("*****@*****.**");
    email.setFrom("*****@*****.**");
    email.setSubject("DTS Test");
    email.setText("Hello");

    javaMailSender.send(email);
  }
コード例 #12
0
 private final SimpleMailMessage constructConfirmationEmailMessage(
     Registration registration, String baseUrl) {
   registerMessage.setTo(registration.getEmail());
   registerMessage.setText(
       MessageFormat.format(
           registerMessageBodyTemplate,
           baseUrl,
           registration.getEmail(),
           registration.getToken()));
   return registerMessage;
 }
コード例 #13
0
  /** 发送模板邮件 */
  public void sendWithTemplate(String message) {
    SystemPropertyUtil.init(
        MailSenderService.class.getResource("/" + "system.properties").getFile());
    String subject = SystemPropertyUtil.getInstance().getProperty("email.subject");
    String from = SystemPropertyUtil.getInstance().getProperty("email.from");
    String userName = SystemPropertyUtil.getInstance().getProperty("email.system");
    String sendTo = SystemPropertyUtil.getInstance().getProperty("email.send.to");

    Map<String, String> model = new HashMap<String, String>();
    model.put("username", userName);
    model.put("from", from);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //
    model.put("Date", simpleDateFormat.format(new Date()));
    model.put("subject", subject);
    model.put("item", sendTo);
    model.put("message", message);
    JavaMailSender mailSender = (JavaMailSender) applicationContext.getBean("mailSender");
    VelocityEngine velocityEngine = (VelocityEngine) applicationContext.getBean("velocityEngine");
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(from); // 发送人,从配置文件中取得
    simpleMailMessage.setSubject(subject);
    // 设置收件人邮箱
    String[] toEmailArray = sendTo.split(";");
    List<String> toEmailList = new ArrayList<String>();
    if (null == toEmailArray || toEmailArray.length <= 0) {
      throw new RuntimeException("收件人邮箱不得为空!");
    } else {
      for (String s : toEmailArray) {
        if (!s.equals("")) {
          toEmailList.add(s);
        }
      }
      if (null == toEmailList || toEmailList.size() <= 0) {
        throw new RuntimeException("收件人邮箱不得为空!");
      } else {
        toEmailArray = new String[toEmailList.size()];
        for (int i = 0; i < toEmailList.size(); i++) {
          toEmailArray[i] = toEmailList.get(i);
        }
        simpleMailMessage.setTo(toEmailArray); // 收件人
      }
    }
    String result = null;
    try {
      result =
          VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail.vm", "UTF-8", model);
    } catch (Exception e) {
      log.error("Can't send the mail!", e);
    }
    simpleMailMessage.setText(result);
    mailSender.send(simpleMailMessage);
    log.debug("邮件发送完成");
  }
コード例 #14
0
ファイル: MailEngine.java プロジェクト: smee/elateXam
  /**
   * Send a simple message based on a Velocity template.
   *
   * @param msg
   * @param templateName
   * @param model
   */
  public void sendMessage(SimpleMailMessage msg, String templateName, Map model) {
    String result = null;

    try {
      result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, model);
    } catch (VelocityException e) {
      e.printStackTrace();
    }

    msg.setText(result);
    send(msg);
  }
コード例 #15
0
  @RequestMapping("/sendQuote.htm")
  public void sendQuote(
      @RequestParam String name, @RequestParam String email, @RequestParam String message) {
    SimpleMailMessage mail = new SimpleMailMessage();
    templateMessage.copyTo(mail);
    mail.setTo("*****@*****.**");
    mail.setSubject("Quote from Qash site [" + name + "]");
    mail.setText("From: " + name + "(" + email + ")\n\n" + mail);

    mailSender.send(mail);

    // return "redirect:/index.htm";
  }
コード例 #16
0
  public void createAction(UserModel user, String eMail) {
    VerifyMailActionData data = new VerifyMailActionData();
    ActionResult create = actionService.createAction(this, data);
    if (create.wasSuccessfull()) {
      SimpleMailMessage message = new SimpleMailMessage(template);
      message.setTo(user.getEmail());
      String body = texte.text("action.verify.mail.body");
      body = body.replace("{link}", ActionResult.ACTION_URL);
      message.setText(body.toString());

      mailer.sendMessage(create.getContentReplacer(), message);
    }
  }
コード例 #17
0
  @Override
  protected void doNotify(ClientApplicationStatusChangedEvent event) {
    EvaluationContext context = new StandardEvaluationContext(event);

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setFrom(from);
    message.setSubject(subject.getValue(context, String.class));
    message.setText(text.getValue(context, String.class));
    message.setCc(cc);

    sender.send(message);
  }
コード例 #18
0
 private final SimpleMailMessage constructEmailMessage(
     final OnRegistrationCompleteEvent event, final User user, final String token) {
   final String recipientAddress = user.getEmail();
   final String subject = "Registration Confirmation";
   final String confirmationUrl = event.getAppUrl() + "/regitrationConfirm.html?token=" + token;
   final String message = messages.getMessage("message.regSucc", null, event.getLocale());
   final SimpleMailMessage email = new SimpleMailMessage();
   email.setTo(recipientAddress);
   email.setSubject(subject);
   email.setText(message + " \r\n" + confirmationUrl);
   email.setFrom(env.getProperty("support.email"));
   return email;
 }
コード例 #19
0
  public void alertEmail(StepExecution stepExecution) {
    try {

      String jobName = stepExecution.getJobExecution().getJobInstance().getJobName();
      String jobInstanceId = "" + stepExecution.getJobExecution().getJobInstance().getId();
      String jobExecutionId = "" + stepExecution.getJobExecution().getId();
      String stepExecutionId = "" + stepExecution.getId();

      SimpleMailMessage message = new SimpleMailMessage(this.templateMessage);
      message.setTo(emailTo);
      StringBuffer messageText = new StringBuffer();
      messageText.append("\n\n");
      messageText.append("This job fail: " + jobName + "\n");
      messageText.append("\n\n");
      messageText.append("## Job");
      messageText.append("\n\n");
      messageText.append("Name: " + jobName + "");
      messageText.append("\n");
      messageText.append("Id: " + jobInstanceId + "");
      messageText.append("\n");
      messageText.append("Job instance list url: " + urlPrefix + "jobs/" + jobName);
      messageText.append("\n\n");
      messageText.append("## Job Execution");
      messageText.append("\n\n");
      messageText.append(
          "Job execution list url: " + urlPrefix + "jobs/" + jobName + "/" + jobInstanceId);
      messageText.append("\n\n");
      messageText.append("## Step Error Details");
      messageText.append("\n\n");
      messageText.append(
          "Job execution url: " + urlPrefix + "jobs/executions/" + jobExecutionId + "");
      messageText.append("\n\n");
      messageText.append(
          "Job error details url: "
              + urlPrefix
              + "jobs/executions/"
              + jobExecutionId
              + "/steps/"
              + stepExecutionId
              + "/progress");
      messageText.append("\n\n");
      messageText.append("## Step Summary");
      messageText.append("\n\n");
      messageText.append("" + stepExecution.getSummary());
      message.setText(messageText.toString());
      this.mailSender.send(message);

    } catch (MailException e) {
      logger.error("erro with the email MailSender", e);
    }
  }
コード例 #20
0
  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();
    }
  }
コード例 #21
0
ファイル: MailEngine.java プロジェクト: yesEric/ws2
  /**
   * Send a simple message based on a Velocity template.
   *
   * @param msg the message to populate
   * @param templateName the Velocity template to use (relative to classpath)
   * @param model a map containing key/value pairs
   */
  @SuppressWarnings("unchecked")
  public void sendMessage(SimpleMailMessage msg, String templateName, Map model) {
    String result = null;

    try {
      result =
          VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateName, "UTF-8", model);
    } catch (VelocityException e) {
      e.printStackTrace();
      log.error(e.getMessage());
    }

    msg.setText(result);
    send(msg);
  }
コード例 #22
0
  private void confirmRegistration(OnRegistrationCompleteEvent event) {
    User user = event.getUser();
    String token = UUID.randomUUID().toString();
    service.createVerificationToken(user, token);

    String recipientAddress = user.getEmail();
    String subject = "Registration Confirmation";
    String confirmationUrl = event.getAppUrl() + "/registrationConfirm.html?token=" + token;
    String message = messages.getMessage("message.regSucc", null, event.getLocale());
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(recipientAddress);
    email.setSubject(subject);
    email.setText(message + " \r\n" + "http://localhost:8080" + confirmationUrl);
    mailSender.send(email);
  }
コード例 #23
0
ファイル: MailServiceImpl.java プロジェクト: dematey/ephesoft
 @Override
 public void sendTextMail(final MailMetaData mailMetaData, final String text) {
   if (suppressMail) {
     return;
   }
   final SimpleMailMessage mailMessage = new SimpleMailMessage();
   mailMessage.setFrom(
       new StringBuilder()
           .append(mailMetaData.getFromName())
           .append(" <")
           .append(mailMetaData.getFromAddress())
           .append(">")
           .toString());
   mailMessage.setSubject(mailMetaData.getSubject());
   mailMessage.setReplyTo(mailMetaData.getReplyTo());
   if (mailMetaData.getCcAddresses() != null && mailMetaData.getCcAddresses().size() > 0) {
     mailMessage.setCc(
         (String[])
             mailMetaData
                 .getCcAddresses()
                 .toArray(new String[mailMetaData.getCcAddresses().size()]));
   }
   if (mailMetaData.getBccAddresses() != null && mailMetaData.getBccAddresses().size() > 0) {
     mailMessage.setBcc(
         (String[])
             mailMetaData
                 .getBccAddresses()
                 .toArray(new String[mailMetaData.getBccAddresses().size()]));
   }
   if (mailMetaData.getToAddresses() != null && mailMetaData.getToAddresses().size() > 0) {
     mailMessage.setTo(
         (String[])
             mailMetaData
                 .getToAddresses()
                 .toArray(new String[mailMetaData.getToAddresses().size()]));
   }
   mailMessage.setText(text);
   try {
     mailSender.send(mailMessage);
   } catch (MailException e) {
     throw new SendMailException(
         new StringBuilder()
             .append("Error sending mail: ")
             .append(mailMetaData.toString())
             .toString(),
         e);
   }
 }
コード例 #24
0
 public void sendEmailNotification(String from, String to) {
   try {
     logger.info("Sending email to " + to);
     SimpleMailMessage message = new SimpleMailMessage();
     message.setFrom("OnionSquare Registration <*****@*****.**>");
     message.setTo(to);
     message.setSubject("Onionsquare | No Sales Activity Email Notification");
     message.setText(
         "We have noticed no sales activity of your store since 5 months. We suggest you to take appropriate actions to continue your store. Your store will be deactivated after one months of this email if we notice no sales of your store during this period. Thank you.");
     logger.info("Sending no sales activity email notification to " + to);
     mailSender.send(message);
     logger.info("Email sent to" + to);
   } catch (Exception e) {
     logger.info("Mail cannot be send due to internal error");
   }
 }
コード例 #25
0
  @RequestMapping(
      value = "/sendmessage",
      method = RequestMethod.POST,
      produces = "application/json")
  @ResponseBody
  public Map<String, Object> sendMessages(
      Principal principal, @RequestBody Map<String, Object> data) {

    String text = (String) data.get("text");
    String name = (String) data.get("name");
    String email = (String) data.get("email");
    // String username= (String)data.get("username");
    User msgSender = usersService.getUserByEmail(email);
    String username = msgSender.getUsername();

    //	Integer target=	(Integer)data.get("target");

    Message message = new Message();
    message.setName(principal.getName()); // siuntejo
    message.setUsername(username); // Gavejo
    message.setEmail(email);
    message.setContent(text);
    message.setSubject("Reply from: " + name);

    System.out.println(name + " " + email + " " + text);

    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setFrom("*****@*****.**");
    mail.setTo(email);
    mail.setSubject("Reply from: " + name);
    mail.setText(text);

    usersService.sendMessage(message);

    try {
      mailSender.send(mail);
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Cant send");
    }

    Map<String, Object> reply = new HashMap<String, Object>();
    reply.put("success", true);
    //	reply.put("target", target);

    return reply;
  }
コード例 #26
0
  @Override
  public void sendMail(
      final String _fromAddr, final String _toAddr, final String _subject, final String _body) {

    LOG.info("Sending mail from: " + _fromAddr);
    LOG.info("Sending mail to: " + _toAddr);
    LOG.info("Sending mail with subject: " + _subject);
    LOG.info("Sending body with length: " + (_body == null ? 0 : _body.length()));

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(_toAddr);
    message.setFrom(_fromAddr);
    message.setText(_body);
    message.setSubject(_subject);

    send(message);
  }
コード例 #27
0
  @Scheduled(cron = "${cron.choice.scheduler}")
  public void run() {
    Restaurant restaurant = restaurantService.makeChoiceToday();

    if (restaurant == null) {
      return;
    }

    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setSubject(message.get("mail.subject"));
    mailMessage.setText(message.get("mail.body", restaurant.getName()));

    for (Person person : personService.findAll()) {
      mailMessage.setTo(person.getEmail());
      mail.send(mailMessage);
    }
  }
コード例 #28
0
  public void createNewUserToken(
      String user, String mail, String forceBody, String subject, String provider) {
    UserModel foundMail = userRepo.findByEmail(mail);
    if (foundMail != null) {
      throw new ValidationException("eMail allready inuse");
    }
    UserModel foundName = userRepo.findByName(user);
    if (foundName != null) {
      throw new ValidationException("Username allready inuse");
    }
    AuthMapping foundLogin = authRepo.findByAuthIdAndAuthType(user, LocalIdp.IDP_NAME);
    if (foundLogin != null) {
      throw new ValidationException("Login Name allready inuse");
    }
    String body = forceBody;
    if (body == null || !body.contains("${link}")) {
      body = texte.text("action.subscribe.mail.body");
      if (body == null) {
        throw new ValidationException("Missing Mail Body : key='action.subscribe.mail.body' ");
      }
    }
    if (subject != null) {
      template.setSubject(subject);
    } else {
      template.setSubject(texte.text("action.subscribe.mail.subject"));
    }
    ActionCreateUser newUser = new ActionCreateUser();
    newUser.setLoginName(user);
    newUser.setMail(mail);
    if (provider == null
        || (provider.equals(CrowdIdp.IDP_NAME) && provider.equals(LocalIdp.IDP_NAME))) {
      newUser.setProvider(CrowdIdp.IDP_NAME);
    } else {
      newUser.setProvider(provider);
    }

    ActionResult result = actionService.createAction(this, newUser);
    if (result.wasSuccessfull()) {
      SimpleMailMessage message = new SimpleMailMessage(template);
      message.setTo(mail);
      body = body.replace("${link}", ActionResult.ACTION_URL);
      message.setText(body.toString());
      mailer.sendMessage(result.getContentReplacer(), message);
    }
  }
コード例 #29
0
  void doExecute(ActionCreateUser data) {
    UserModel foundMail = userRepo.findByEmail(data.getEMail());
    if (foundMail != null) {
      throw new ValidationException("eMail allready inuse");
    }
    UserModel foundName = userRepo.findByName(data.getUserName());
    if (foundName != null) {
      throw new ValidationException("Username allready inuse");
    }
    AuthMapping foundLogin =
        authRepo.findByAuthIdAndAuthType(data.getLoginName(), LocalIdp.IDP_NAME);
    if (foundLogin != null) {
      throw new ValidationException("Login Name allready inuse");
    }
    String body = texte.text("action.subscribe.confirm.mail.body");
    if (body == null) {
      throw new ValidationException(
          "Missing Mail Body : key='action.subscribe.confirm.mail.body' ");
    }

    Collection<UserRoles> newRoles = new ArrayList<UserRoles>();
    newRoles.add(UserRoles.USER);

    UserModel user =
        userService.createIdentity(
            data.getProvider(),
            data.getLoginName(),
            data.getUserName(),
            data.getPassword(),
            data.getEMail(),
            newRoles);

    // actionVerify.createAction(user, data.getEMail());

    // Send confirmation mail
    String baseUrl = config.getStringValue("baseUrl");
    body = body.replace("${username}", data.getUserName());
    body = body.replace("${loginname}", data.getLoginName());
    body = body.replace("${email}", data.getEMail());
    body = body.replace("${baseUrl}", baseUrl);
    SimpleMailMessage message = new SimpleMailMessage(template);
    message.setTo(data.getEMail());
    message.setText(body.toString());
    mailer.sendMessage(message);
  }
コード例 #30
0
  @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()));
  }