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: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  ww w .j  a  v a  2 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;/*  w  ww .j  a va2  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;
        }
    }
}

From source file:edu.duke.cabig.c3pr.domain.repository.impl.CSMUserRepositoryImpl.java

public void sendUserEmail(String userName, String subject, String text) {
    try {//from ww  w . j a  v  a 2  s. c  om
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(getUserByName(userName).getEmail());
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    } catch (MailException e) {
        throw new C3PRBaseRuntimeException("Could not send email to user.", e);
    }
}

From source file:edu.unc.lib.dl.services.MailNotifier.java

/**
 * Sends a plain text email to the repository administrator.
 *
 * @param subject//  www  .  ja  va  2  s  . c  o  m
 * @param text
 */
public void sendAdministratorMessage(String subject, String text) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(this.getRepositoryFromAddress());
    message.setTo(this.administratorAddress);
    message.setSubject("[" + this.irBaseUrl + "]" + subject);
    message.setText(text);
    this.mailSender.send(message);
}

From source file:gov.nih.nci.cabig.caaers.domain.repository.UserRepositoryImpl.java

public void sendUserEmail(String emailAddress, String subject, String text) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(emailAddress);//from  w w  w  .  ja va2s .  c  o m
    message.setSubject(subject);
    message.setText(text);
    mailSender.send(message);

}

From source file:gov.nih.nci.cabig.caaers.service.ScheduledNotificationProcessService.java

/**
 * This method will process and sends notifications associated to a
 * scheduled notification. /*w w  w.j a v  a 2s  .c  o  m*/
 * 
 *  - Will find the recipients, and their email addresses. 
 *  - Will generate the subject/body of email
 *  - Will send notification
 *  - Will update notification status. 
 * 
 * @param reportId - A valid {@link Report#id}
 * @param scheduledNotificationId - A valid {@link ScheduledNotification#id}
 */
@Transactional
public void process(Integer reportId, Integer scheduledNotificationId) {

    Report report = reportDao.getById(reportId);
    ScheduledEmailNotification scheduledNotification = (ScheduledEmailNotification) report
            .fetchScheduledNotification(scheduledNotificationId);
    DeliveryStatus newDeliveryStatus = DeliveryStatus.RECALLED;

    if (report.isActive()) {

        newDeliveryStatus = DeliveryStatus.DELIVERED;

        PlannedEmailNotification plannedNotification = (PlannedEmailNotification) scheduledNotification
                .getPlanedNotificaiton();
        ExpeditedAdverseEventReport aeReport = report.getAeReport();
        StudySite studySite = aeReport.getStudySite();
        Study study = aeReport.getStudy();

        Set<String> emailAddresses = new HashSet<String>();
        //find emails of direct recipients
        List<ContactMechanismBasedRecipient> contactRecipients = plannedNotification
                .getContactMechanismBasedRecipients();
        if (CollectionUtils.isNotEmpty(contactRecipients)) {
            for (ContactMechanismBasedRecipient recipient : contactRecipients) {
                String contact = recipient.getContact();
                if (GenericValidator.isEmail(contact))
                    emailAddresses.add(contact);
            }
        }

        //find emails of role recipients
        List<RoleBasedRecipient> roleRecipients = plannedNotification.getRoleBasedRecipients();
        if (CollectionUtils.isNotEmpty(roleRecipients)) {
            List<String> emails = null;
            for (RoleBasedRecipient recipient : roleRecipients) {
                if (ArrayUtils.contains(RoleUtils.reportSpecificRoles, recipient.getRoleName())) {
                    emails = report.findEmailAddressByRole(recipient.getRoleName());
                } else if (ArrayUtils.contains(RoleUtils.sponsorAndCoordinatingCenterSpecificRoles,
                        recipient.getRoleName())) {
                    emails = study.getStudyCoordinatingCenter().findEmailAddressByRole(recipient.getRoleName());
                    emails.addAll(study.getStudyFundingSponsors().get(0)
                            .findEmailAddressByRole(recipient.getRoleName()));
                } else if (ArrayUtils.contains(RoleUtils.studySiteSpecificRoles, recipient.getRoleName())) {
                    emails = studySite.findEmailAddressByRole(recipient.getRoleName());
                } else {
                    emails = study.findEmailAddressByRole(recipient.getRoleName());
                }

                //now add the valid email addresses obtained
                if (CollectionUtils.isNotEmpty(emails)) {
                    for (String email : emails) {
                        if (GenericValidator.isEmail(email))
                            emailAddresses.add(email);
                    }
                }

            }

        }

        if (CollectionUtils.isNotEmpty(emailAddresses)) {
            //now process the notifications. 
            String rawSubjectLine = plannedNotification.getSubjectLine();
            String rawBody = plannedNotification.getNotificationBodyContent().getBody();

            Map<Object, Object> contextVariableMap = report.getContextVariables();
            //change the reportURL
            String reportURL = String.valueOf(contextVariableMap.get("reportURL"));
            contextVariableMap.put("reportURL", configuration.get(Configuration.CAAERS_BASE_URL) + reportURL);

            //apply the replacements. 
            String subjectLine = freeMarkerService.applyRuntimeReplacementsForReport(rawSubjectLine,
                    contextVariableMap);
            String body = freeMarkerService.applyRuntimeReplacementsForReport(rawBody, contextVariableMap);

            //create the message
            SimpleMailMessage mailMsg = new SimpleMailMessage();
            mailMsg.setSentDate(scheduledNotification.getScheduledOn());
            mailMsg.setSubject(subjectLine);
            mailMsg.setText(body);

            //send email to each recipient
            for (String email : emailAddresses) {
                mailMsg.setTo(email);

                try {
                    caaersJavaMailSender.send(mailMsg);
                } catch (Exception e) {
                    //no need to throw and rollback
                    logger.warn("Error while emailing to [" + email + "]", e);
                }
            }

        }
    }

    scheduledNotificationDao.updateDeliveryStatus(scheduledNotification,
            scheduledNotification.getDeliveryStatus(), newDeliveryStatus);

}

From source file:gov.nih.nci.cabig.caaers.service.UnreportedSAENotificationProcessService.java

@Transactional
public void process() {

    // get all the distinct report definitions
    List<ReportDefinition> rds = adverseEventRecommendedReportDao.getAllRecommendedReportsNotReported();

    // get planned notifications associated with the report definitions
    for (ReportDefinition rd1 : rds) {
        for (PlannedNotification plannedNotification : rd1.getUnreportedAePlannedNotification()) {
            Set<String> contactBasedEmailAddresses = new HashSet<String>();
            //find emails of direct recipients
            if (CollectionUtils.isNotEmpty(plannedNotification.getContactMechanismBasedRecipients())) {
                for (ContactMechanismBasedRecipient recipient : plannedNotification
                        .getContactMechanismBasedRecipients()) {
                    String contact = recipient.getContact();
                    if (GenericValidator.isEmail(contact))
                        contactBasedEmailAddresses.add(contact);
                }//from  w  w  w.  j  a v a  2 s  .  c  om
            }

            //now process the notifications. 
            PlannedEmailNotification plannedemailNotification = (PlannedEmailNotification) plannedNotification;
            String rawSubjectLine = plannedemailNotification.getSubjectLine();
            String rawBody = plannedNotification.getNotificationBodyContent().getBody();
            Integer dayOfNotification = plannedemailNotification.getIndexOnTimeScale();
            List<AdverseEventRecommendedReport> aeRecomReports = adverseEventRecommendedReportDao
                    .getAllAdverseEventsGivenReportDefinition(rd1);

            for (AdverseEventRecommendedReport aeRecomReport : aeRecomReports) {

                Set<String> roleBasedEmailAddresses = new HashSet<String>();

                Study study = aeRecomReport.getAdverseEvent().getReportingPeriod().getStudy();
                StudySite studySite = aeRecomReport.getAdverseEvent().getReportingPeriod().getStudySite();

                //find emails of role recipients
                List<RoleBasedRecipient> roleRecipients = plannedNotification.getRoleBasedRecipients();
                if (CollectionUtils.isNotEmpty(roleRecipients)) {
                    List<String> emails = null;
                    for (RoleBasedRecipient recipient : roleRecipients) {
                        if ("SAE Reporter".equals(recipient.getRoleName())
                                && aeRecomReport.getAdverseEvent().getReporterEmail() != null) {
                            // add adverse event reporter email for email notification
                            roleBasedEmailAddresses.add(aeRecomReport.getAdverseEvent().getReporterEmail());
                        } else if (ArrayUtils.contains(RoleUtils.reportSpecificRoles,
                                recipient.getRoleName())) {
                            // since there is no report yet, skip if the role is report specific
                            continue;
                        } else if (ArrayUtils.contains(RoleUtils.sponsorAndCoordinatingCenterSpecificRoles,
                                recipient.getRoleName())) {
                            emails = study.getStudyCoordinatingCenter()
                                    .findEmailAddressByRole(recipient.getRoleName());
                            emails.addAll(study.getStudyFundingSponsors().get(0)
                                    .findEmailAddressByRole(recipient.getRoleName()));
                        } else if (ArrayUtils.contains(RoleUtils.studySiteSpecificRoles,
                                recipient.getRoleName())) {
                            emails = studySite.findEmailAddressByRole(recipient.getRoleName());
                        } else {
                            emails = study.findEmailAddressByRole(recipient.getRoleName());
                        }

                        //now add the valid email addresses obtained
                        if (CollectionUtils.isNotEmpty(emails)) {
                            for (String email : emails) {
                                if (GenericValidator.isEmail(email))
                                    roleBasedEmailAddresses.add(email);
                            }
                        }

                    }

                }

                if (aeRecomReport.getAdverseEvent().getGradedDate() != null) {
                    long daysPassedSinceGradedDate = DateUtils.differenceInDays(new Date(),
                            aeRecomReport.getAdverseEvent().getGradedDate());
                    if (daysPassedSinceGradedDate != dayOfNotification) {
                        continue;
                    }
                }

                // get the graded date and compare with the day of notification to check if notification is configured on this day

                Map<Object, Object> contextVariableMap = aeRecomReport.getAdverseEvent().getContextVariables();
                //get the AE reporting deadline
                contextVariableMap.put("aeReportingDeadline", aeRecomReport.getDueDate().toString());

                //apply the replacements. 
                String subjectLine = freeMarkerService.applyRuntimeReplacementsForReport(rawSubjectLine,
                        contextVariableMap);
                String body = freeMarkerService.applyRuntimeReplacementsForReport(rawBody, contextVariableMap);

                //create the message
                SimpleMailMessage mailMsg = new SimpleMailMessage();
                mailMsg.setSentDate(new Date());
                mailMsg.setSubject(subjectLine);
                mailMsg.setText(body);

                // collect emails of both contact based and role based recipients
                Set<String> allEmailAddresses = new HashSet<String>();
                allEmailAddresses.addAll(roleBasedEmailAddresses);
                allEmailAddresses.addAll(contactBasedEmailAddresses);

                //send email to each contact based recipient
                for (String email : allEmailAddresses) {
                    mailMsg.setTo(email);

                    try {
                        caaersJavaMailSender.send(mailMsg);
                    } catch (Exception e) {
                        //no need to throw and rollback
                        logger.warn("Error while emailing to [" + email + "]", e);
                    }
                }

            }

        }

    }

}

From source file:ome.logic.AdminImpl.java

private boolean sendEmail(Experimenter e, String newPassword) {
    // Create a thread safe "copy" of the template message and customize it
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setSubject("OMERO - Reset password");
    msg.setTo(e.getEmail());//w  w w  . j a  va2 s  . c o m
    msg.setText("Dear " + e.getFirstName() + " " + e.getLastName() + " (" + e.getOmeName() + ")"
            + " your new password is: " + newPassword);
    try {
        this.mailSender.send(msg);
    } catch (Exception ex) {
        throw new RuntimeException("Exception: " + ex.getMessage() + ". "
                + "Password was not changed because email could not be sent " + "to the " + e.getOmeName()
                + ". Please turn on the debuge "
                + "mode in omero.properties by the: omero.resetpassword.mail.debug=true");
    }
    return true;
}

From source file:org.beangle.emsapp.security.action.MyAction.java

/**
 * ???//from   w  ww.j  ava  2  s  .  c o m
 */
public String sendPassword() {
    String name = get("name");
    String email = get("mail");
    if (StringUtils.isEmpty(name) || StringUtils.isEmpty(email)) {
        addActionError("error.parameters.needed");
        return (ERROR);
    }
    List<User> userList = entityDao.get(User.class, "name", name);
    User user = null;
    if (userList.isEmpty()) {
        return goErrorWithMessage("error.user.notExist");
    } else {
        user = userList.get(0);
    }
    if (!StringUtils.equals(email, user.getMail())) {
        return goErrorWithMessage("error.email.notEqualToOrign");
    } else {
        String longinName = user.getName();
        String password = RandomStringUtils.randomNumeric(6);
        user.setRemark(password);
        user.setPassword(EncryptUtil.encode(password));
        String title = getText("user.password.sendmail.title");

        List<Object> values = CollectUtils.newArrayList();
        values.add(longinName);
        values.add(password);
        String body = getText("user.password.sendmail.body", values);
        try {
            SimpleMailMessage msg = new SimpleMailMessage(message);
            msg.setTo(user.getMail());
            msg.setSubject(title);
            msg.setText(body.toString());
            mailSender.send(msg);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("reset password error for user:" + user.getName() + " with email :" + user.getMail());
            return goErrorWithMessage("error.email.sendError");
        }
    }
    entityDao.saveOrUpdate(user);
    return forward("sendResult");
}

From source file:org.encuestame.business.service.MailService.java

@Deprecated
public void send(final String to, final String subject, final String text) throws MailSendException {
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setFrom(getNoEmailResponse());//from  w  w  w .  jav a2  s . co m
    msg.setTo(to);
    // msg.setCc();
    msg.setText(text);
    msg.setSubject(buildSubject(subject));
    mailSender.send(msg);
    //log.debug("mail.succesful");
}