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.duke.cabig.c3pr.domain.repository.impl.CSMUserRepositoryImpl.java

public void sendUserEmail(String userName, String subject, String text) {
    try {// w  w w  .  j  a  va2s.co m
        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//from  w  ww  . j  a va  2  s .  co 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);
    message.setSubject(subject);/*from  ww w. jav  a  2  s .co m*/
    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  va2 s. com
 * 
 *  - 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 ww 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());
    msg.setText("Dear " + e.getFirstName() + " " + e.getLastName() + " (" + e.getOmeName() + ")"
            + " your new password is: " + newPassword);
    try {/* ww w .j a  va 2 s  . com*/
        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  w w. j  a  v  a2s  .co 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 .  j a v a  2s.c om
    msg.setTo(to);
    // msg.setCc();
    msg.setText(text);
    msg.setSubject(buildSubject(subject));
    mailSender.send(msg);
    //log.debug("mail.succesful");
}

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

/**
 * Send invitation./*from w  ww. j  av a2  s  . c  o  m*/
 * @param to email to send
 * @param code code of password
 * @throws MailSendException mail exception.
 */
public void sendInvitation(final String to, final String code) throws MailSendException {
    final SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setFrom(getNoEmailResponse());
    msg.setTo(to);
    msg.setText("<h1>Invitation to Encuestame</h1><p>Please confirm"
            + " this invitation <a>http://www.encuesta.me/cod/" + code + "</a>");
    msg.setSubject(buildSubject("test"));
    try {
        mailSender.send(msg);
    } catch (Exception e) {
        log.error("Error on send email " + e.getMessage());
    }
}

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

/**
 * Delete notification./* ww  w. j  av a  2s .c o  m*/
 * @param to mail to send
 * @param body body of message
 * @throws MailSendException exception
 */
public void sendDeleteNotification(final String to, final String body) throws MailSendException {
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setFrom(getNoEmailResponse());
    msg.setTo(to);
    msg.setText(body);
    msg.setSubject(
            buildSubject(getMessageProperties("email.message.delete.invitation", buildCurrentLocale(), null)));
    mailSender.send(msg);
}