Example usage for org.springframework.mail SimpleMailMessage setSubject

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

Introduction

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

Prototype

@Override
    public void setSubject(String subject) 

Source Link

Usage

From source file:com.traffitruck.web.HtmlController.java

@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
ModelAndView forgotPassword(@RequestParam("username") String username) {
    if (username != null) {
        LoadsUser loadsUser = dao.getUser(username);
        if (loadsUser != null) {
            Random random = new Random();
            StringBuilder newPassword = new StringBuilder();
            for (int i = 0; i < 8; ++i)
                newPassword.append(random.nextInt(10));
            Map<String, Object> model = new HashMap<>();
            model.put("email", loadsUser.getEmail());
            ResetPassword rp = new ResetPassword();
            rp.setCreationDate(new Date());
            rp.setUsername(username);/*from ww w.j a  va  2s.co  m*/
            rp.setUuid(String.valueOf(newPassword));
            dao.newResetPassword(rp);
            SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(loadsUser.getEmail());
            msg.setSubject("forgot password");
            msg.setFrom("no-reply@traffitruck.com");
            String message = "   ?   ?-\n"
                    + "?? ?  ? ?  ? ?  \n"
                    + "   ?- ? " + newPassword + "\n"
                    + "   15 \n"
                    + " ?     \n";

            msg.setText(message);
            mailSender.send(msg);
            return new ModelAndView("forgot_password_explain", model);
        }
    }
    Map<String, Object> model = new HashMap<>();
    model.put("error", "notfound");
    return new ModelAndView("forgot_password", model);
}

From source file:org.jasig.schedassist.impl.events.EmailNotificationApplicationListener.java

/**
 * //  ww  w.j  av  a  2 s  . c  o  m
 * @param owner
 * @param visitor
 * @param event
 */
protected void sendEmail(final IScheduleOwner owner, final IScheduleVisitor visitor, final VEvent event,
        final String messageBody) {
    if (null != mailSender) {
        SimpleMailMessage message = new SimpleMailMessage();
        if (!isEmailAddressValid(owner.getCalendarAccount().getEmailAddress())) {
            message.setFrom(noReplyFromAddress);
            message.setTo(new String[] { visitor.getCalendarAccount().getEmailAddress() });
        } else {
            message.setFrom(owner.getCalendarAccount().getEmailAddress());
            message.setTo(new String[] { owner.getCalendarAccount().getEmailAddress(),
                    visitor.getCalendarAccount().getEmailAddress() });
        }
        Summary summary = event.getSummary();
        if (summary != null) {
            message.setSubject(summary.getValue());
        } else {
            LOG.warn("event missing summary" + event);
            message.setSubject("Appointment");
        }
        message.setText(messageBody);

        LOG.debug("sending message: " + message.toString());
        mailSender.send(message);
        LOG.debug("message successfully sent");
    } else {
        LOG.debug("no mailSender set, ignoring sendEmail call");
    }
}

From source file:net.triptech.metahive.service.OpenIdAuthenticationFailureHandler.java

/**
 * Send a notification email./*from w ww.  j ava2s  .c  o  m*/
 *
 * @param newPerson the new person
 */
private void sendNotificationEmail(final Person newPerson) {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo("paintbuoy@gmail.com");
    message.setFrom("david.harrison@stress-free.co.nz");

    StringBuilder subject = new StringBuilder();
    subject.append("Metahive: New user '");
    subject.append(newPerson.getFormattedName());
    subject.append("' (");
    subject.append(newPerson.getEmailAddress());
    subject.append(") registered");

    StringBuilder body = new StringBuilder();
    body.append(newPerson.getFormattedName());
    body.append(" (");
    body.append(newPerson.getEmailAddress());
    body.append(") just registered at the Metahive.\n\n");
    body.append("Have a nice day.\n");

    message.setSubject(subject.toString());
    message.setText(body.toString());

    try {
        emailSenderService.send(message, null);
    } catch (ServiceException se) {
        logger.error("Error sending notification email: " + se.getMessage());
    }
}

From source file:fi.koku.pyh.controller.EditFamilyInformationController.java

/**
 * Action method for adding new family members.
 * /*from  w w  w .j  ava  2s. co  m*/
 * @param request - portlet action request
 * @param response - portlet action response
 * @throws FamilyNotFoundException
 * @throws TooManyFamiliesException
 * @throws fi.koku.services.entity.customer.v1.ServiceFault
 * @throws fi.koku.services.entity.community.v1.ServiceFault
 */
@ActionMapping(params = "action=addUsersToFamily")
public void addUsersToFamily(ActionRequest request, ActionResponse response)
        throws FamilyNotFoundException, TooManyFamiliesException,
        fi.koku.services.entity.customer.v1.ServiceFault, fi.koku.services.entity.community.v1.ServiceFault {

    String userPic = UserInfoUtils.getPicFromSession(request);
    HashMap<String, String> personMap = new HashMap<String, String>();

    String familyCommunityId = request.getParameter("familyCommunityId");
    String personPicFromJsp = request.getParameter("userPic");
    String personRoleFromJsp = request.getParameter("userRole");

    personMap.put(personPicFromJsp, personRoleFromJsp);

    boolean childsGuardianshipInformationNotFound = false;
    try {

        if (logger.isDebugEnabled()) {
            logger.debug("addUsersToFamily(): adding persons:");
            Set<String> set = personMap.keySet();
            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String personPic = it.next();
                logger.debug("person pic: " + personPic);
            }
        }

        if (familyCommunityId == null) {
            throw new FamilyNotFoundException(
                    "EditFamilyInformationController.addUsersToFamily: cannot add family members because family community does not exist!");
        }

        Set<String> keys = personMap.keySet();
        Iterator<String> si = keys.iterator();

        while (si.hasNext()) {
            String memberToAddPic = si.next();
            String role = personMap.get(memberToAddPic);

            CommunityRole communityRole = CommunityRole.create(role);
            List<String> recipients = generateRecipients(memberToAddPic, communityRole,
                    userPic/*current user's pic*/);

            if (CommunityRole.PARENT.equals(communityRole) || CommunityRole.FATHER.equals(communityRole)
                    || CommunityRole.MOTHER.equals(communityRole)) {
                Log.getInstance().send(userPic, "", "pyh.membership.request",
                        "Sending membership request to add person " + memberToAddPic + " into family");
                messageHelper.sendParentAdditionMessage(familyCommunityId, memberToAddPic, userPic,
                        communityRole);
            } else if (CommunityRole.CHILD.equals(communityRole) && recipients.size() == 0) {
                // we don't have guardian information for the child so we can't send the request
                Log.getInstance().send(userPic, "", "pyh.membership.request",
                        "Cannot send approval request because guardian for child " + memberToAddPic
                                + " is not found");

                String messageSubject = messageSource.getMessage("ui.pyh.mail.missing.information.subject",
                        null, "", Locale.getDefault());
                String messageText = messageSource.getMessage("ui.pyh.mail.missing.information.text",
                        new Object[] { memberToAddPic }, "", Locale.getDefault());

                // send mail notification to KoKu support
                SimpleMailMessage mailMessage = new SimpleMailMessage(this.templateMessage);
                mailMessage.setFrom(PyhConstants.KOKU_FROM_EMAIL_ADDRESS);
                mailMessage.setTo(PyhConstants.KOKU_SUPPORT_EMAIL_ADDRESS);
                mailMessage.setSubject(messageSubject);
                mailMessage.setText(messageText);

                try {
                    this.mailSender.send(mailMessage);
                } catch (MailException me) {
                    // if mail sending fails, PYH operation continues normally
                    logger.error(
                            "EditFamilyInformationController.addUsersToFamily: sending mail to KoKu support failed!",
                            me);
                }

                // notify end user that family membership request cannot be sent
                throw new GuardianForChildNotFoundException(
                        "Guardian for child (pic: " + memberToAddPic + ") not found!");

            } else if (recipients.size() == 0) {
                insertInto(userPic, memberToAddPic, communityRole);
            } else {
                Log.getInstance().send(userPic, "", "pyh.membership.request",
                        "Sending membership request to add person " + memberToAddPic + " into family");
                messageHelper.sendFamilyAdditionMessage(familyCommunityId, recipients, userPic, memberToAddPic,
                        communityRole);
            }
        }

    } catch (GuardianForChildNotFoundException gnfe) {
        logger.error(
                "EditFamilyInformationController.addUsersToFamily() caught GuardianForChildNotFoundException: cannot send membership "
                        + "request because guardian for the child was not found. The child was not added into the family.");
        // show error message in JSP view
        childsGuardianshipInformationNotFound = true;
    }

    response.setRenderParameter("childsGuardianshipInformationNotFound",
            String.valueOf(childsGuardianshipInformationNotFound));
    response.setRenderParameter("action", "editFamilyInformation");
}

From source file:hu.unideb.studentSupportInterface.backing.Registration.java

public void addUser() {
    if (userDao.loadUserByUsername(newUser.getEmail()) != null) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Ez az e-mail cm mr szerepel az adatbzisban.",
                        "Ez az e-mail cm mr szerepel az adatbzisban..."));
        return;/*from w ww .j  av a2s .  c o m*/
    }

    if (!newUser.getPassword().equals(pwdCheck)) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "A kt jelsz nem egyezik.", "A kt jelsz nem egyezik."));
        return;
    }

    if (!selectedRoles.contains(Role.TUTOR)) {
        newUser.setActive(true);
    }

    newUser = userDao.createUser(newUser, newUser.getPassword());

    for (Role r : selectedRoles) {
        roleDao.addRoleToUser(newUser, r);
    }

    for (Language l : selectedLanguages) {
        languageDao.addLanguageToUser(l, newUser);
    }

    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setFrom("SSI");
    msg.setTo(newUser.getEmail());

    String text;
    if (selectedRoles.contains(Role.TUTOR)) {
        text = "Kedves " + newUser.getFirstName()
                + "!\r\n\r\nSikeresen regisztrltl a Student Support Interface alkalmazsba!\r\nMivel oktatknt regisztrltl, felhasznli fikod csak adminisztrtori jvhagys utn lesz hasznlhat. Errl egy jabb zenetben fogsz rteslni.\r\n\r\ndvzlettel:\r\nStudent Support Interface";
    } else {
        text = "Kedves " + newUser.getFirstName()
                + "!\r\n\r\nSikeresen regisztrltl a Student Support Interface alkalmazsba!\r\n\r\ndvzlettel:\r\nStudent Support Interface";
    }

    msg.setSubject("Sikeres regisztrci");
    msg.setText(text);
    mailSender.send(msg);

    FacesContext facesContext = FacesContext.getCurrentInstance();
    String outcome = "existingSolutions?faces-redirect=true";// Do your thing?
    facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);

}

From source file:org.jasig.schedassist.impl.events.AutomaticAppointmentCancellationApplicationListener.java

@Async
@Override//w ww  .j a v a 2  s  .c  o  m
public void onApplicationEvent(AutomaticAppointmentCancellationEvent event) {
    ICalendarAccount owner = event.getOwner();
    VEvent vevent = event.getEvent();

    deleteEventReminder(owner, vevent);

    PropertyList attendeeList = vevent.getProperties(Attendee.ATTENDEE);

    SimpleMailMessage message = new SimpleMailMessage();
    List<String> recipients = new ArrayList<String>();
    for (Object o : attendeeList) {
        Property attendee = (Property) o;
        String value = attendee.getValue();
        String email = value.substring(EmailNotificationApplicationListener.MAILTO_PREFIX.length());
        if (EmailNotificationApplicationListener.isEmailAddressValid(email)) {
            recipients.add(email);
        } else {
            LOG.debug("skipping invalid email: " + email);
        }
    }
    message.setTo(recipients.toArray(new String[] {}));

    if (!EmailNotificationApplicationListener.isEmailAddressValid(owner.getEmailAddress())) {
        message.setFrom(noReplyFromAddress);
    } else {
        message.setFrom(owner.getEmailAddress());
    }
    message.setSubject(vevent.getSummary().getValue() + " has been cancelled");
    message.setText(constructMessageBody(vevent, event.getReason(), owner.getDisplayName()));

    LOG.debug("sending message: " + message.toString());
    mailSender.send(message);
    LOG.debug("message successfully sent");
}

From source file:org.jasig.schedassist.impl.reminder.DefaultReminderServiceImpl.java

/**
 * Send an email message for this {@link IReminder}.
 * //from  ww  w. j  a v a 2  s.co m
 * @param reminder
 */
protected void sendEmail(IReminder reminder) {
    if (shouldSend(reminder)) {
        final IScheduleOwner owner = reminder.getScheduleOwner();
        final ICalendarAccount recipient = reminder.getRecipient();
        final VEvent event = reminder.getEvent();
        Reminders reminderPrefs = owner.getRemindersPreference();
        final boolean includeOwner = reminderPrefs.isIncludeOwner();

        SimpleMailMessage message = new SimpleMailMessage();
        final boolean canSendToOwner = emailAddressValidator.canSendToEmailAddress(owner.getCalendarAccount());
        if (canSendToOwner) {
            message.setFrom(owner.getCalendarAccount().getEmailAddress());
        } else {
            message.setFrom(noReplyFromAddress);
        }

        if (includeOwner && canSendToOwner) {
            message.setTo(
                    new String[] { owner.getCalendarAccount().getEmailAddress(), recipient.getEmailAddress() });
        } else {
            message.setTo(new String[] { recipient.getEmailAddress() });
        }

        message.setSubject("Reminder: " + event.getSummary().getValue());
        final String messageBody = createMessageBody(event, owner);
        message.setText(messageBody);

        LOG.debug("sending message: " + message.toString());
        try {
            mailSender.send(message);
            LOG.debug("message successfully sent");
        } catch (MailSendException e) {
            LOG.error("caught MailSendException for " + owner + ", " + recipient + ", " + reminder, e);
        }

    } else {
        LOG.debug("skipping sendEmail for reminder that should not be sent: " + reminder);
    }
}

From source file:nz.net.orcon.kanban.automation.actions.EmailSenderAction.java

public void sendSecureEmail(String subject, String emailBody, String to, String bcc, String from,
        String replyTo, String host, String password) {

    SimpleMailMessage mailMessage = new SimpleMailMessage();
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

    mailSender.setHost(host);//from w  w  w .j av a2 s.c  om
    mailSender.setPort(587);
    mailSender.setProtocol("smtp");

    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");

    mailSender.setJavaMailProperties(props);

    if (StringUtils.isNotBlank(to)) {
        mailMessage.setTo(to);
    }
    if (StringUtils.isNotBlank(bcc)) {
        mailMessage.setBcc(bcc);
    }

    if (StringUtils.isNotBlank(from)) {
        mailMessage.setFrom(from);
        mailSender.setUsername(from);
    }

    if (StringUtils.isNotBlank(password)) {
        mailSender.setPassword(password);
    }

    if (StringUtils.isNotBlank(replyTo)) {
        mailMessage.setReplyTo(replyTo);
    }

    if (StringUtils.isNotBlank(subject)) {
        mailMessage.setSubject(subject);
    }

    mailMessage.setText(emailBody);
    mailSender.send(mailMessage);
    logger.info("Secure Email Message has been sent..");
}

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 {//  w ww .  ja v a 2  s  .co 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:edu.washington.iam.registry.ws.RelyingPartyController.java

@RequestMapping(value = "/rp/attr", method = RequestMethod.PUT)
public ModelAndView putRelyingPartyAttributes(@RequestParam(value = "id", required = true) String id,
        @RequestParam(value = "policyId", required = true) String policyId,
        @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 attrs for " + id + " in " + policyId);
    int status = 200;

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

    ModelAndView mv = emptyMV("OK dokey");

    if (!session.isAdmin) {
        status = 401;
        mv.addObject("alert", "You are not permitted to update attriubtes.");
        response.setStatus(status);
        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) {
        try {
            filterPolicyManager.updateRelyingParty(policyId, doc);
            status = 200;
        } catch (FilterPolicyException e) {
            status = 400;
            mv.addObject("alert", "Update of the entity failed:" + e);
        }
    }

    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setTo(mailTo);
    String act = "updated";
    if (status == 201)
        act = "created";
    msg.setSubject("Service provider attributes " + act + " by " + session.remoteUser);
    msg.setText("User '" + session.remoteUser + "' " + act + " attributes for '" + id + "'.\nRequest status: "
            + status + "\n");
    try {
        this.mailSender.send(msg);
    } catch (MailException ex) {
        log.error("sending mail: " + ex.getMessage());
    }

    response.setStatus(status);
    return mv;
}