Example usage for org.springframework.mail SimpleMailMessage setTo

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

Introduction

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

Prototype

@Override
    public void setTo(String... to) 

Source Link

Usage

From source file:org.runway.users.service.UserManagerServiceImpl.java

private void sendMail(User user) {

    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);

    msg.setTo(user.getEmail());
    msg.setSubject("Re: your peoplebees account ");

    StringBuilder sb = new StringBuilder();
    // sb.append("Dear "+ user.getFirstName() + "\n");
    sb.append("your peoplebees account is created successfully.\n ");

    // the following format is correct. please don't change
    sb.append("    login id: " + user.getId() + "\n");

    sb.append("http://peoplebees.com\n");

    msg.setText(sb.toString());/*w  w w.  ja  v  a  2  s  .  c o  m*/

    logger.info("sending message : \n" + msg.toString());
    this.mailSender.sendMail(msg);
}

From source file:com.gnizr.web.action.user.ApproveUserAccount.java

private boolean sendNotificationEmail(User user) {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("token", token);
    model.put("username", user.getUsername());
    model.put("email", user.getEmail());
    model.put("createdOn", user.getCreatedOn());
    model.put("gnizrConfiguration", getGnizrConfiguration());

    if (getWelcomeEmailTemplate() == null) {
        logger.error("ApproveUserAccount: welcomeEmailTemplate bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }//from  www. j av a2s.  c o m

    String toUserEmail = user.getEmail();
    if (toUserEmail == null) {
        logger.error("ApproveUserAccount: the email of user " + user.getUsername() + " is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_EMAIL_UNDEF));
        return false;
    }

    SimpleMailMessage notifyMsg = new SimpleMailMessage(getWelcomeEmailTemplate());
    notifyMsg.setTo(toUserEmail);

    if (notifyMsg.getFrom() == null) {
        String contactEmail = getGnizrConfiguration().getSiteContactEmail();
        if (contactEmail != null) {
            notifyMsg.setFrom(contactEmail);
        } else {
            notifyMsg.setFrom("no-reply@localhost");
        }
    }

    Template fmTemplate1 = null;
    String text1 = null;
    try {
        fmTemplate1 = freemarkerEngine.getTemplate("login/welcome-template.ftl");
        text1 = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate1, model);
    } catch (Exception e) {
        logger.error("ApproveUserAccount: error creating message template from Freemarker engine");
    }
    notifyMsg.setText(text1);

    if (getMailSender() == null) {
        logger.error("ApproveUserAccount: mailSender bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }
    try {
        getMailSender().send(notifyMsg);
        return true;
    } catch (Exception e) {
        logger.error("ApproveUserAccount: send mail error. " + e);
        addActionError(String.valueOf(ActionErrorCode.ERROR_INTERNAL));
    }

    return false;
}

From source file:jp.xet.uncommons.wicket.utils.ErrorReportRequestCycleListener.java

@Override
public IRequestHandler onException(RequestCycle cycle, Exception ex) {
    if (ex instanceof PageExpiredException || ex instanceof StalePageException) {
        return null;
    }//w  w  w  .ja  v  a2 s .  co  m

    if (ex instanceof WicketRuntimeException) {
        Throwable rootCause = getRootCause(ex);
        if (rootCause == null) {
            rootCause = ex;
        }

        String environment = loadEnvironment();
        if (enabledEnvironments == null || environment == null
                || ObjectUtils.containsElement(enabledEnvironments, environment)) {
            String type = rootCause.getClass().getSimpleName();
            String message = rootCause.getMessage();
            String subject = MessageFormat.format(subjectPattern, environment, type, message);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(from);
            mailMessage.setTo(to);
            mailMessage.setSubject(subject);
            mailMessage.setText(getStackTrace(ex));
            try {
                logger.debug("sending exception report mail...");
                mailSender.send(mailMessage);
                logger.debug("success to send exception report mail");
            } catch (MailException e) {
                logger.error("failed to send exception report mail", e);
            }
        } else {
            logger.debug(
                    "exception report mail was not sent, "
                            + "because enabledEnvironments{} does not contain environment[{}]",
                    new Object[] { Arrays.toString(enabledEnvironments), environment });
        }
    }
    return null;
}

From source file:fm.last.citrine.notification.EMailNotifier.java

/**
 * Creates a mail message which is ready to be sent.
 * /*from   ww  w  .  j a  va 2 s .com*/
 * @param recipients Message recipients.
 * @param taskRun Task run containing various values which will be put into message.
 * @param taskName The task name.
 * @return A prepared mail message.
 */
private SimpleMailMessage createMessage(String recipients, TaskRun taskRun, String taskName) {
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    if (!StringUtils.isEmpty(recipients)) {
        // override default recipients set in application context
        String[] recipientArray = recipients.split(",");
        msg.setTo(recipientArray);
    }
    msg.setSubject("[citrine] '" + taskName + "' finished with Status " + taskRun.getStatus() + " for TaskRun "
            + taskRun.getId());
    StringBuilder messageText = new StringBuilder();

    String logUrl = getDisplayLogUrl(taskRun);
    if (logUrl != null) {
        messageText.append("\nSee: ").append(logUrl).append("\n");
    }

    if (!StringUtils.isEmpty(taskRun.getStackTrace())) {
        messageText.append("\nStackTrace:\n").append(taskRun.getStackTrace()).append("\n");
    }
    if (!StringUtils.isEmpty(taskRun.getSysErr())) {
        messageText.append("\nSysErr:\n").append(taskRun.getSysErr()).append("\n");
    }
    if (!StringUtils.isEmpty(taskRun.getSysOut())) {
        messageText.append("\nSysOut:\n").append(taskRun.getSysOut()).append("\n");
    }
    msg.setText(messageText.toString());

    log.warn(messageText.toString());

    return msg;
}

From source file:net.bafeimao.umbrella.web.test.MailTests.java

/**
 * SpringMailSender???/*w ww  .ja v a 2s  .c o m*/
 */
@Test
public void testSendMail() {
    // ?
    SimpleMailMessage mailMessage = new SimpleMailMessage();

    //  ??
    // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};
    // mailMessage.setTo(array);
    mailMessage.setTo(" 29283212@qq.com");
    mailMessage.setFrom("29283212@qq.com");
    mailMessage.setSubject("???!");
    mailMessage.setText(" ????");

    // ??
    senderImpl.send(mailMessage);

    System.out.println(" ???.. ");
}

From source file:net.solarnetwork.central.dras.biz.alert.SimpleAlertBiz.java

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;
    }/*from  w  w w .j av a  2 s  .  c o  m*/

    // 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("escalation@econz.co.nz");

        break;

    case EMAIL:
        msg.setSubject(subject);
        msg.setFrom("solar-adr@solarnetwork.net");
        break;

    default:
        log.debug("User {} contact type {} not supported in alerts", user.getUsername(), contact.getKind());
        return false;
    }
    sendMailMessage(msg, creatorId);
    return true;
}

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  ww .  j a  v  a 2s  . co 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:com.admob.rocksteady.reactor.Alerting.java

/**
 * Handle the triggered event/*from w w w  . j a v  a 2  s. c o m*/
 *
 * @param newEvents the new events in the window
 * @param oldEvents the old events in the window
 */
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
    if (newEvents == null) {
        return;
    }
    Integer i = 0;
    Date sqlDate = new Date();
    for (EventBean newEvent : newEvents) {
        i++;
        try {
            String msg = "";
            String _subject = "";
            // This is how string comparison is done in JAVA, not ==
            if (type.equals("log")) {
                String name = newEvent.get("name").toString();
                // String value = newEvent.get("value").toString();
                String error = newEvent.get("error").toString();
                String count = newEvent.get("count").toString();

                msg = name + " - " + error + " - " + count + " errors.";

            } else if (type.equals("latency_single")) {
                String hostname = newEvent.get("hostname").toString();
                String name = newEvent.get("name").toString();
                String value = newEvent.get("value").toString();
                String colo = newEvent.get("colo").toString();
                String app = newEvent.get("app").toString();

                String graphiteTs = newEvent.get("timestamp").toString();

                msg = colo + " - " + hostname + " - " + app + " - " + name + " - " + value;

                Threshold threshold = new Threshold();
                threshold.setName(name);
                threshold.setHostname(hostname);
                threshold.setColo(colo);
                threshold.setApp(app);
                threshold.setGraphiteTs(graphiteTs);
                threshold.setGraphiteValue(value);
                threshold.setCreateOn(sqlDate);
                threshold.persist();

                msg = msg + "\n" + "http://" + rsweb + "/rsweb/threshold.php?id="
                        + String.valueOf(threshold.getId());
                _subject = this.subject + " - " + colo + " - " + hostname;

            } else if (type.equals("latency_multi")) {
                Metric l = (Metric) newEvent.get("latency");
                String l_hostname = l.getHostname();
                String l_value = l.getValue().toString();
                String l_name = l.getName();
                Metric w = (Metric) newEvent.get("win");
                String name = w.getName();
                String value = w.getValue().toString();
                String ts = w.getTimestamp().toString();
                String colo = w.getColo();
                String hostname = w.getHostname();
                String app = w.getApp();

                msg = l_hostname + " - " + l_name + " - " + l_value + " - " + app + " - " + name + " - " + value
                        + " - " + ts;

                // Persistent the threshold cross event
                Threshold threshold = new Threshold();
                threshold.setName(name);
                threshold.setHostname(hostname);
                threshold.setColo(colo);
                threshold.setApp(app);
                threshold.setGraphiteTs(ts);
                threshold.setGraphiteValue(value);
                threshold.setCreateOn(sqlDate);
                threshold.persist();

            } else if (type.equals("deploy")) {
                String new_revision = newEvent.get("revision").toString();

                String colo = newEvent.get("colo").toString();
                String hostname = newEvent.get("hostname").toString();
                String app = newEvent.get("app").toString();

                Revision revision = new Revision();
                revision.setHostname(hostname);
                revision.setColo(colo);
                revision.setApp(app);
                revision.setCreateOn(sqlDate);
                revision.setRevision(new_revision);
                revision.persist();

                msg = "Revision changed on " + colo + " " + hostname + " to " + new_revision;
            } else if (type.equals("test")) {
                // String hostname = newEvent.get("hostname").toString();
                String colo = newEvent.get("colo").toString();
                // String app = newEvent.get("app").toString();
                // String timestamp = newEvent.get("timestamp").toString();
                // String revision = newEvent.get("revision").toString();
                // String diff = newEvent.get("diff").toString();
                String value = newEvent.get("value").toString();
                String name = newEvent.get("name").toString();

                msg = colo + " - " + name + " - " + value;

            } else if (type.equals("averagedThreshold")) {
                DecimalFormat df = new DecimalFormat("#.##");
                String colo = newEvent.get("colo").toString();
                String app = newEvent.get("app").toString();
                String value = df.format(newEvent.get("value"));
                String name = newEvent.get("name").toString();

                msg = app + " - " + colo + " - " + name + " - " + value;
                _subject = this.subject + " - " + msg;

            } else if (type.equals("count")) {
                String count = newEvent.get("count").toString();
                msg = i + " count: " + count;

            } else {
                String name = newEvent.get("name").toString();
                String value = newEvent.get("value").toString();
                String colo = newEvent.get("colo").toString();

                msg = " event triggered - type " + type + " - " + colo + " - " + name + " - " + value;

            }
            logger.debug(msg);

            // This email recipient iisn't empty, we send email out.
            if (recipients != null & recipients.length > 0) {
                logger.debug("Email sent");
                SimpleMailMessage mail = new SimpleMailMessage(this.templateMessage);

                mail.setTo(this.recipients);
                mail.setSubject(_subject);
                mail.setText(msg);
                this.mailSender.send(mail);

            }

        } catch (Exception e) {
            logger.error("Trouble. Alert type: " + type + " " + newEvent.toString() + " - " + 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 .j  a va  2s. 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:burstcoin.observer.service.NetworkService.java

private void sendMessage(String subject, String message) {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setTo(ObserverProperties.getMailReceiver());
    mailMessage.setReplyTo(ObserverProperties.getMailReplyTo());
    mailMessage.setFrom(ObserverProperties.getMailSender());
    mailMessage.setSubject(subject);/*from w  ww .ja  v a2  s.  com*/
    mailMessage.setText(message);
    mailSender.send(mailMessage);
}