Example usage for org.springframework.mail SimpleMailMessage setText

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

Introduction

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

Prototype

@Override
    public void setText(String text) 

Source Link

Usage

From source file:csns.web.controller.SubmissionController.java

private void emailGrade(Submission submission) {
    if (!StringUtils.hasText(submission.getGrade()) || submission.isGradeMailed())
        return;//from   w w  w  .j  a  va 2s .c o  m

    User instructor = SecurityUtils.getUser();
    User student = submission.getStudent();

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(instructor.getEmail());
    message.setTo(student.getEmail());

    String subject = submission.getAssignment().getSection().getCourse().getCode() + " "
            + submission.getAssignment().getName() + " Grade";
    message.setSubject(subject);

    Map<String, Object> vModels = new HashMap<String, Object>();
    vModels.put("grade", submission.getGrade());
    String comments = submission.getComments();
    vModels.put("comments", comments != null ? comments : "");
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email.submission.grade.vm",
            appEncoding, vModels);
    message.setText(text);

    try {
        mailSender.send(message);
        submission.setGradeMailed(true);
        submissionDao.saveSubmission(submission);
        logger.info(instructor.getUsername() + " sent grade to " + student.getEmail());
    } catch (MailException e) {
        logger.warn(instructor.getUsername() + " failed to send grade to " + student.getEmail());
        logger.debug(e.getMessage());
    }
}

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 w w w  . j ava 2s.  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:org.jasig.schedassist.impl.events.EmailNotificationApplicationListener.java

/**
 * //from w  ww  . ja v  a  2 s .  co  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:org.jasig.schedassist.impl.events.AutomaticAppointmentCancellationApplicationListener.java

@Async
@Override//  w w  w .  j  av 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: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 a  v a2  s . c o m*/
    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:com.gnizr.web.action.user.RegisterUser.java

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

    if (getVerifyEmailTemplate() == null) {
        logger.error("RegisterUser: templateMessge bean is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_CONFIG));
        return false;
    }/*w  w w  .  j a v  a 2 s.c o m*/
    String toEmail = user.getEmail();
    if (toEmail == null) {
        logger.error("RegisterUser: the email of user " + user.getUsername() + " is not defined");
        addActionError(String.valueOf(ActionErrorCode.ERROR_EMAIL_UNDEF));
        return false;
    }
    SimpleMailMessage msg = new SimpleMailMessage(getVerifyEmailTemplate());
    msg.setTo(toEmail);

    if (msg.getFrom() == null) {
        String contactEmail = getGnizrConfiguration().getSiteContactEmail();
        if (contactEmail != null) {
            msg.setFrom(contactEmail);
        } else {
            msg.setFrom("help@localhost");
        }
    }

    Template fmTemplate = null;
    String text = null;
    try {
        fmTemplate = freemarkerEngine.getTemplate("login/verifyemail-template.ftl");
        text = FreeMarkerTemplateUtils.processTemplateIntoString(fmTemplate, model);
    } catch (Exception e) {
        logger.error("RegisterUser: error creating message template from Freemarker engine");
    }

    msg.setText(text);

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

From source file:edu.wisc.my.portlets.feedback.dao.SimpleFeedbackMessageFormatterImpl.java

public SimpleMailMessage format(Feedback feedback) {

    SimpleMailMessage message = new SimpleMailMessage();

    message.setTo(targetEmail);/*from w  ww  . j  a  v  a2s  .  c o  m*/
    message.setFrom(fromAddress);

    message.setSubject("[Feedback] " + feedback.getSubject());

    StringBuffer details = new StringBuffer();
    details.append("NAME: ");
    details.append(null == feedback.getName() ? "<empty>" : feedback.getName());
    details.append("\n");
    details.append("\n");

    details.append("NETID: ");
    details.append(null == feedback.getNetid() ? "<empty>" : feedback.getNetid());
    details.append("\n");
    details.append("\n");

    details.append("EMAIL: ");
    details.append(null == feedback.getEmailAddress() ? "<empty>" : feedback.getEmailAddress());
    details.append("\n");
    details.append("\n");

    details.append("PHONE: ");
    details.append(null == feedback.getPhoneNumber() ? "<empty>" : feedback.getPhoneNumber());
    details.append("\n");
    details.append("\n");

    details.append("DETAILS: ");
    details.append(feedback.getDetails());

    message.setText(details.toString());

    return message;
}

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

/**
 * Creates a mail message which is ready to be sent.
 * //from w  ww.jav a2s .co m
 * @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:org.jasig.schedassist.impl.reminder.DefaultReminderServiceImpl.java

/**
 * Send an email message for this {@link IReminder}.
 * /*from  w  w  w . j  a v  a2 s  .  c  om*/
 * @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:org.jasig.portlets.FeedbackPortlet.service.EmailForwardingListener.java

public void performAction(FeedbackItem item) {

    // only forward on email with comments
    if (item.getFeedback() == null || item.getFeedback().equals(""))
        return;//from w  w  w  . ja  v  a 2s  .c  om

    SimpleMailMessage message = new SimpleMailMessage(mailMessage);

    // set the user's email address as the from and reply to
    if (item.getUseremail() != null && !item.getUseremail().equals("")) {
        message.setFrom(item.getUseremail());
        message.setReplyTo(item.getUseremail());
    }

    // construct the message text
    String text = message.getText();
    if (item.getUsername() != null && !item.getUsername().equals(""))
        text = StringUtils.replace(text, "%USERNAME%", item.getUsername());
    else
        text = StringUtils.replace(text, "%USERNAME%", "Anonymous");

    if (item.getUserrole() != null && !item.getUserrole().equals(""))
        text = StringUtils.replace(text, "%USERROLE%", item.getUserrole());
    else
        text = StringUtils.replace(text, "%USERROLE%", "unknown");

    text = StringUtils.replace(text, "%USERAGENT%", item.getUseragent());

    if (item.getTabname() != null && !item.getTabname().equals(""))
        text = StringUtils.replace(text, "%TABNAME%", item.getTabname());
    else
        text = StringUtils.replace(text, "%TABNAME%", "none");

    text = StringUtils.replace(text, "%FEEDBACKTYPE%", item.getFeedbacktype());
    text = StringUtils.replace(text, "%FEEDBACK%", item.getFeedback());
    message.setText(text);

    // send the message
    mailSender.send(message);

}