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:edu.washington.iam.registry.ws.RelyingPartyController.java

@RequestMapping(value = "/rp", method = RequestMethod.PUT)
public ModelAndView putRelyingParty(@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("PUT update 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 w w. j  ava  2 s  .c o m*/

    ModelAndView mv = emptyMV("OK dokey");

    try {
        if (!userCanEdit(session, id)) {
            status = 401;
            mv.addObject("alert", "You are not an owner of that entity.");
            response.setStatus(status);
            return mv;
        }
    } catch (DNSVerifyException e) {
        mv.addObject("alert", "Could not verify ownership:\n" + e.getCause());
        response.setStatus(500);
        return mv;
    }

    RelyingParty relyingParty = null;
    try {
        Document doc = null;
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        doc = builder.parse(in);
        relyingParty = new RelyingParty(doc.getDocumentElement(), mdid, rpManager.isMetadataEditable(mdid));
    } catch (Exception e) {
        log.info("parse error: " + e);
        status = 400;
        mv.addObject("alert", "The posted document was not valid:\n" + e);
        response.setStatus(status);
        return mv;
    }

    try {
        status = rpManager.updateRelyingParty(relyingParty, mdid);
    } catch (RelyingPartyException e) {
        status = 400;
        mv.addObject("alert", "Update failed:\n" + e.getMessage());
        response.setStatus(status);
        return mv;
    }

    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setTo(mailTo);
    String act = "updated";
    if (status == 201)
        act = "created";
    else if (status >= 400)
        act = "attempted edit of";
    msg.setSubject("Service provider metadata " + act + " by " + session.remoteUser);
    msg.setText("User '" + session.remoteUser + "' " + act + " metadata for '" + id + "'.\nRequest status: "
            + status + "\n\nThis message is advisory.  No response is indicated.");
    try {
        this.mailSender.send(msg);
    } catch (MailException ex) {
        log.error("sending mail: " + ex.getMessage());
    }

    response.setStatus(status);
    return mv;
}

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

@RequestMapping(value = "/rp/attrReq", method = RequestMethod.PUT)
public ModelAndView putRelyingPartyAttrReq(@RequestParam(value = "id", required = true) String id,
        InputStream in, HttpServletRequest request, HttpServletResponse response) {

    RPSession session = processRequestInfo(request, response, false);
    if (session == null)
        return (emptyMV());
    log.info("PUT request for: " + id);
    int status = 200;

    ModelAndView mv = emptyMV("OK dokey");

    try {//  www  . j  a v a 2 s  . c  o  m
        if (!userCanEdit(session, id)) {
            status = 401;
            mv.addObject("alert", "You are not an owner of that entity.");
        }
    } catch (DNSVerifyException e) {
        mv.addObject("alert", "Could not verify ownership:\n" + e.getCause());
        response.setStatus(500);
        return mv;
    }

    Document doc = null;
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        doc = builder.parse(in);
    } catch (Exception e) {
        log.info("parse error: " + e);
        status = 400;
        mv.addObject("alert", "The posted document was not valid:\n" + e);
    }
    if (doc != null) {
        StringBuffer txt = new StringBuffer(
                "[ Assign to Identity and Access Management. ]\n\nEntity Id: " + id + "\n");
        txt.append("User:      " + session.remoteUser + "\n\nRequesting:\n");
        List<Element> attrs = XMLHelper.getElementsByName(doc.getDocumentElement(), "Add");
        log.debug(attrs.size() + " adds");
        for (int i = 0; i < attrs.size(); i++)
            txt.append("  Add new attribute: " + attrs.get(i).getAttribute("id") + "\n\n");
        attrs = XMLHelper.getElementsByName(doc.getDocumentElement(), "Drop");
        log.debug(attrs.size() + " drops");
        for (int i = 0; i < attrs.size(); i++)
            txt.append("  Drop existing attribute: " + attrs.get(i).getAttribute("id") + "\n\n");
        Element mele = XMLHelper.getElementByName(doc.getDocumentElement(), "Comments");
        if (mele != null)
            txt.append("\nComment:\n\n" + mele.getTextContent() + "\n\n");
        txt.append("Quick link:\n\n   " + spRegistryUrl + "#a" + id + "\n");

        SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
        /* production to RT system */
        msg.setTo(requestMailTo);
        msg.setSubject("IdP attribute request for " + id);
        msg.setFrom(session.remoteUser + "@uw.edu");
        msg.setText(txt.toString());
        try {
            this.mailSender.send(msg);
        } catch (MailException ex) {
            log.error("sending mail: " + ex.getMessage());
            status = 500;
        }

    }
    response.setStatus(status);
    return mv;
}

From source file:com.jrzmq.core.email.SimpleMailService.java

/**
 * ??//from   w  ww .java  2  s .  co  m
 * @param emailTo 
 * @param project 
 * @param ???
 * @param map     ?
 */
public void sendMail(String emailTo, String subject, String templateName, Map<String, Object> map) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setSentDate(new Date());
    msg.setTo(emailTo);
    msg.setSubject(subject);

    try {
        msg.setText(generateContent(templateName, map));
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
    } catch (Exception e) {
        logger.error("??{},:{},", new Object[] { emailTo, subject }, e);
    }
}

From source file:com.netflix.genie.web.services.impl.MailServiceImpl.java

@Override
public void sendEmail(@NotBlank(message = "Cannot send email to blank address.") @Nonnull final String toEmail,
        @NotBlank(message = "Subject cannot be empty") @Nonnull final String subject,
        @Nullable final String body) throws GenieException {
    final SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

    simpleMailMessage.setTo(toEmail);
    simpleMailMessage.setFrom(this.fromAddress);
    simpleMailMessage.setSubject(subject);

    // check if body is not empty
    if (StringUtils.isNotBlank(body)) {
        simpleMailMessage.setText(body);
    }//w w  w .  j a v a2  s.com

    try {
        this.javaMailSender.send(simpleMailMessage);
    } catch (final MailException me) {
        throw new GenieServerException("Failure to send email", me);
    }
}

From source file:com.springsource.insight.plugin.mail.MessageSendOperationCollectionAspectTest.java

private void testSendMessage(int port) {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(NetworkAddressUtil.LOOPBACK_ADDRESS);
    sender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
    sender.setPort(port);// w  w w .j  a v  a  2 s  . c o m

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("from@com.springsource.insight.plugin.mail");
    message.setTo("to@com.springsource.insight.plugin.mail");
    message.setCc("cc@com.springsource.insight.plugin.mail");
    message.setBcc("bcc@com.springsource.insight.plugin.mail");

    Date now = new Date(System.currentTimeMillis());
    message.setSentDate(now);
    message.setSubject(now.toString());
    message.setText("Test at " + now.toString());
    sender.send(message);

    Operation op = getLastEntered();
    assertNotNull("No operation extracted", op);
    assertEquals("Mismatched operation type", MailDefinitions.SEND_OPERATION, op.getType());
    assertEquals("Mismatched protocol", sender.getProtocol(),
            op.get(MailDefinitions.SEND_PROTOCOL, String.class));
    assertEquals("Mismatched host", sender.getHost(), op.get(MailDefinitions.SEND_HOST, String.class));
    if (port == -1) {
        assertEquals("Mismatched default port", 25, op.getInt(MailDefinitions.SEND_PORT, (-1)));
    } else {
        assertEquals("Mismatched send port", sender.getPort(), op.getInt(MailDefinitions.SEND_PORT, (-1)));
    }

    if (getAspect().collectExtraInformation()) {
        assertAddresses(op, MailDefinitions.SEND_SENDERS, 1);
        assertAddresses(op, MailDefinitions.SEND_RECIPS, 3);

        OperationMap details = op.get(MailDefinitions.SEND_DETAILS, OperationMap.class);
        assertNotNull("No details extracted", details);
        assertEquals("Mismatched subject", message.getSubject(),
                details.get(MailDefinitions.SEND_SUBJECT, String.class));
    }
}

From source file:com.springstudy.utils.email.SimpleMailService.java

/**
 * ??./* w ww  .ja va 2s .c  om*/
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setFrom(Global.getConfig("mailFrom"));
    msg.setTo(email.getAddress());
    if (StringUtils.isNotEmpty(email.getCc())) {
        String cc[] = email.getCc().split(";");
        msg.setCc(cc);//?
    }
    msg.setSubject(email.getSubject());

    // ????
    //      String content = String.format(textTemplate, userName, new Date());
    String content = email.getContent();
    msg.setText(content);
    try {
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
        return true;
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.myaccount.ApplyForWritingPermissionController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    log.debug("Processing the form");
    ApplyForWritingPermissionCommand afwpc = (ApplyForWritingPermissionCommand) command;

    log.debug("Loading Person object of actual logged user from database");
    Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());

    log.debug("Composing e-mail message");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);
    mail.setFrom(user.getEmail());//  w  w w . j a v a 2s  .  c om

    log.debug("Loading list of supervisors");
    List<Person> supervisors = personDao.getSupervisors();
    String[] emails = new String[supervisors.size()];
    int i = 0;
    for (Person supervisor : supervisors) {
        emails[i++] = supervisor.getEmail();
    }
    mail.setTo(emails);

    log.debug("Setting subject to e-mail message");
    mail.setSubject(mail.getSubject() + " - Write permission request from user " + user.getUsername());

    String messageBody = "User " + user.getUsername()
            + " has requested permission for adding data into EEGbase system.\n" + "Reason is: "
            + afwpc.getReason() + "\n" + "Use the address below to grant the write permission.\n";
    String linkAddress = "http://" + request.getLocalAddr() + ":" + request.getLocalPort()
            + request.getContextPath() + "/system/grant-permission.html?id=" + user.getPersonId();
    log.debug("Address is: " + linkAddress);
    messageBody += linkAddress;
    mail.setText(messageBody);

    String mavName = "";
    try {
        log.debug("Sending message");
        mailSender.send(mail);
        log.debug("Mail was sent");
        mavName = getSuccessView();
    } catch (MailException e) {
        log.debug("Mail was not sent");
        mavName = getFailView();
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(mavName);
    return mav;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.ForgottenPasswordController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    ForgottenPasswordCommand fpc = (ForgottenPasswordCommand) command;

    Person user = personDao.getPerson(fpc.getUsername());

    log.debug("Creating new mail object");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);

    String recipient = user.getEmail();
    log.debug("Composing e-mail - TO: " + recipient);
    mail.setTo(recipient);

    String subject = mail.getSubject() + " - Password reset";
    log.debug("Composing e-mail - SUBJECT: " + subject);
    mail.setSubject(subject);/*from  ww  w . ja  v a  2  s  .  c o m*/

    String password = ControllerUtils.getRandomPassword();
    String text = "Your password for EEGbase portal was reset. Your new password (within brackets) is ["
            + password + "]\n\n" + "Please change the password after logging into system.";
    log.debug("Composing e-mail - TEXT: " + text);
    mail.setText(text);

    String mavName = getSuccessView();
    try {
        log.debug("Sending e-mail message");
        mailSender.send(mail);
        log.debug("E-mail message sent successfully");

        log.debug("Updating new password into database");
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        personDao.update(user);
        log.debug("Password updated");
    } catch (MailException e) {
        log.debug("E-mail message was NOT sent");
        log.debug("Password was NOT changed");
        mavName = getFailedView();
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(mavName);
    return mav;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.root.WriteRequestsListController.java

/**
 * Sends e-mail with granting message or rejecting message to the recipient
 *
 * @param recipient E-mail address of the recipient
 * @param grant     If <code>true</code>, granting message will be sent,
 *                  if <code>false</code>, rejecting message will be sent
 *//*from   w ww  .j a  v a2 s  .  c o  m*/
private boolean sendEmail(String recipient, boolean grant) {
    log.debug("Sending e-mail");
    SimpleMailMessage mail = new SimpleMailMessage(mailMessage);
    mail.setTo(recipient);

    log.debug("Setting the parameters of the e-mail message");
    String subject = "";
    String text = "";
    if (grant) {
        subject = mail.getSubject() + " - Write permission granted";
        text = "Congratulation, the write permission for the EEGbase portal was granted. You can now submit your data. Thank you for your interest.";
    } else {
        subject = mail.getSubject() + " - Write permission rejected";
        text = "We are sorry, but the write permission for the EEGbase portal was rejected. You can apply again, try to better explain your reasons. Thank you.";
    }
    mail.setSubject(subject);
    mail.setText(text);

    try {
        log.debug("Sending the e-mail");
        mailSender.send(mail);
        log.debug("E-mail was sent");
        return true;
    } catch (MailException e) {
        log.debug("E-mail was NOT sent");
        return false;
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.notifications.NotificationServiceImpl.java

/** {@inheritDoc} */
public void sendEmail(Collection<User> users, String key, Map<User, EmailModel> emailModels) {
    if (sender == null || users == null) {
        return;/*from  ww w.  j  ava2  s .c om*/
    }

    if (StringUtils.isBlank(emailFrom)) {
        LOGGER.error("No outgoing email specified");
        throw new IteraplanTechnicalException(IteraplanErrorMessages.NOTIFICATION_CONFIGURATION_INCOMPLETE);
    }

    for (User user : users) {
        String emailTo = user.getEmail();

        if (StringUtils.isBlank(emailTo)) {
            LOGGER.error("Missing email address for user " + user.getLoginName());
            continue;
        }

        EmailModel model = emailModels.get(user);

        if (key.endsWith(".updated") && model.getChanges().isEmpty()) {
            continue;
        }

        Email email = null;
        try {
            email = emailFactory.createEmail(key, model);
        } catch (MailException e) {
            LOGGER.error("Error generating the email content: ", e);
            continue;
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(emailTo);
        message.setFrom(emailFrom);
        message.setSubject(email.getSubject());
        message.setText(email.getText());
        try {
            this.sender.send(message);
        } catch (MailException e) {
            LOGGER.error("Mail cannot be sent: ", e);
            continue;
        }
    }
}