Example usage for org.springframework.mail SimpleMailMessage SimpleMailMessage

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

Introduction

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

Prototype

public SimpleMailMessage() 

Source Link

Document

Create a new SimpleMailMessage .

Usage

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

public void sendUserEmail(String userName, String subject, String text) {
    try {/*from w  ww.j a  va  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/*from   www.j a  v  a  2 s .  c om*/
 * @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 ww  .j  a  v a  2  s .  c  om*/
    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. //  www .  j a va2 s.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   ww  w .j  ava2  s. c o  m
            }

            //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:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * /*from  ww  w  .  ja va  2  s.  c o m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendActivationMail(ActivationUser activationUser) {
    try {
        if (!StringUtils.isBlank(activationUser.getUser().getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(activationUser.getUser().getMail());
            message.setSubject(
                    ApplicationPropertyManager.getApplicationProperty("mail.activationUser.subject"));
            message.setText(ApplicationPropertyManager.getApplicationProperty("mail.activationUser.text",
                    new String[] { activationUser.getUser().getFirstName(),
                            activationUser.getUser().getAccount(),
                            URLEncoder.encode(activationUser.getUuid().toString(), "UTF-8"),
                            ApplicationPropertyManager.getApplicationProperty("website.protocol"),
                            ApplicationPropertyManager.getApplicationProperty("website.domain"),
                            ApplicationPropertyManager.getApplicationProperty("website.contextPath") },
                    "{", "}"));
            getJavaMailSender().send(message);

            activationUser.setMailSended(Boolean.TRUE);
            activationUser.setMailSendedDate(new Date());
            getActivationUserDAO().merge(activationUser);
        } else {
            logger.error("Mail activation user not sended for user " + activationUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + activationUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/*  w  ww  . j  a  v  a 2  s .  com*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendApprovedMail(ApprovationUser approvationUser) {
    try {
        if (!StringUtils.isBlank(approvationUser.getUser().getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(approvationUser.getUser().getMail());
            message.setSubject(ApplicationPropertyManager.getApplicationProperty("mail.approvedUser.subject"));
            message.setText(ApplicationPropertyManager.getApplicationProperty("mail.approvedUser.text",
                    new String[] { approvationUser.getUser().getFirstName(),
                            ApplicationPropertyManager.getApplicationProperty("website.protocol"),
                            ApplicationPropertyManager.getApplicationProperty("website.domain"),
                            ApplicationPropertyManager.getApplicationProperty("website.contextPath"),
                            approvationUser.getUser().getAccount() },
                    "{", "}"));
            getJavaMailSender().send(message);

            approvationUser.setMailSended(Boolean.TRUE);
            approvationUser.setMailSendedDate(new Date());
            getApprovationUserDAO().merge(approvationUser);
        } else {
            logger.error("Mail approved not sended for user " + approvationUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + approvationUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/*  ww  w  .j  av  a 2  s.  c o m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendForumPostReplyNotificationMail(ForumPostNotified forumPostReplied, ForumPost forumPost,
        User currentUser) {
    try {
        if (!StringUtils.isBlank(currentUser.getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(currentUser.getMail());
            if (!Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) {
                // message for a reply post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.forumPostReplyNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(),
                                        forumPost.getParentPost().getSubject() },
                                "{", "}"));
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.forumPostReplyNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getParentPost().getSubject(),
                                getForumTopicUrl(forumPost.getTopic(),
                                        Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) },
                        "{", "}"));
            } else {
                // message for a course transcription post or a course question post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.courseTranscriptionNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(), forumPost.getTopic().getSubject() },
                                "{", "}"));
                CourseTopicOption courseTopicOption = getCourseTopicOptionDAO()
                        .getOption(forumPost.getTopic().getTopicId());
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.courseTranscriptionNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getTopic().getSubject(), getCourseTopicUrl(courseTopicOption) },
                        "{", "}"));
            }
            getJavaMailSender().send(message);

        } else {
            logger.error("Mail for ForumPost reply not sended for user " + currentUser.getAccount()
                    + ". Check mail field on tblUser for account " + currentUser.getAccount());
        }

        forumPostReplied.setMailSended(Boolean.TRUE);
        forumPostReplied.setMailSendedDate(new Date());

        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}/*from w w w  .  j av  a2 s .c o  m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendForumPostReplyNotificationMessage(ForumPostNotified forumPostReplied, ForumPost forumPost,
        User currentUser) {
    try {
        if (!StringUtils.isBlank(currentUser.getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(currentUser.getMail());
            if (!Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) {
                // message for a reply post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.forumPostReplyNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(),
                                        forumPost.getParentPost().getSubject() },
                                "{", "}"));
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.forumPostReplyNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getParentPost().getSubject(),
                                getForumTopicUrl(forumPost.getTopic(),
                                        Forum.SubType.COURSE.equals(forumPost.getForum().getSubType())) },
                        "{", "}"));
            } else {
                // message for a course transcription post or a course question post
                message.setSubject(ApplicationPropertyManager
                        .getApplicationProperty("mail.courseTranscriptionNotification.subject",
                                new String[] { forumPost.getUser().getFirstName(),
                                        forumPost.getUser().getLastName(), forumPost.getTopic().getSubject() },
                                "{", "}"));

                CourseTopicOption courseTopicOption = getCourseTopicOptionDAO()
                        .getOption(forumPost.getTopic().getTopicId());
                message.setText(ApplicationPropertyManager.getApplicationProperty(
                        "mail.courseTranscriptionNotification.text",
                        new String[] { forumPost.getUser().getFirstName(), forumPost.getUser().getLastName(),
                                forumPost.getTopic().getSubject(), getCourseTopicUrl(courseTopicOption) },
                        "{", "}"));
            }

            //getJavaMailSender().send(message);
            //instead of sending the message by email sending it by internal message

            // Composing Message
            UserMessage userMessage = new UserMessage();
            userMessage.setSender("Staff");
            User tempUser = currentUser;
            userMessage.setRecipient(tempUser.getAccount());
            userMessage.setSubject(message.getSubject());
            userMessage.setBody(message.getText());
            userMessage.setMessageId(null);
            userMessage.setRecipientStatus(RecipientStatus.NOT_READ);
            userMessage.setSendedDate(new Date());

            //Sending Message
            getCommunityService().createNewMessage(userMessage);

        } else {
            logger.error("Mail for ForumPost reply not sended for user " + currentUser.getAccount()
                    + ". Check mail field on tblUser for account " + currentUser.getAccount());
        }

        forumPostReplied.setMailSended(Boolean.TRUE);
        forumPostReplied.setMailSendedDate(new Date());

        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}

From source file:org.medici.bia.service.mail.MailServiceImpl.java

/**
 * {@inheritDoc}// ww w .  ja  va 2 s  .com
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public Boolean sendMailLockedUser(LockedUser lockedUser) {
    try {
        if (!StringUtils.isBlank(lockedUser.getUser().getMail())) {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(getMailFrom());
            message.setTo(lockedUser.getUser().getMail());
            message.setSubject(ApplicationPropertyManager.getApplicationProperty("mail.lockedUser.subject"));
            message.setText(
                    ApplicationPropertyManager.getApplicationProperty("mail.lockedUser.text",
                            new String[] { lockedUser.getUser().getAccount(),
                                    ApplicationPropertyManager.getApplicationProperty("mail.admin.to"), },
                            "{", "}"));
            getJavaMailSender().send(message);
            SimpleMailMessage messageToAdmin = new SimpleMailMessage();
            messageToAdmin.setFrom(getMailFrom());
            messageToAdmin.setTo(ApplicationPropertyManager.getApplicationProperty("mail.admin.to"));
            messageToAdmin.setSubject(
                    ApplicationPropertyManager.getApplicationProperty("mail.lockedUserToAdmin.subject"));
            messageToAdmin
                    .setText(ApplicationPropertyManager.getApplicationProperty("mail.lockedUserToAdmin.text",
                            new String[] { lockedUser.getUser().getAccount() }, "{", "}"));
            getJavaMailSender().send(messageToAdmin);
            lockedUser.setMailSended(Boolean.TRUE);
            lockedUser.setMailSendedDate(new Date());
            getLockedUserDAO().merge(lockedUser);
        } else {
            logger.error("Mail locked not sended for user " + lockedUser.getUser().getAccount()
                    + ". Check mail field on tblUser for account " + lockedUser.getUser().getAccount());
        }
        return Boolean.TRUE;
    } catch (Throwable throwable) {
        logger.error(throwable);
        return Boolean.FALSE;
    }
}