Example usage for org.springframework.mail SimpleMailMessage setSentDate

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

Introduction

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

Prototype

@Override
    public void setSentDate(Date sentDate) 

Source Link

Usage

From source file:com.mulodo.survey.batch.processor.ReportMailItemProcessor.java

/**
 * @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object)
 */// w ww.  ja v  a  2 s. c  o m
@Override
public SimpleMailMessage process(Report report) throws Exception {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("repost_survey@yahoo.com.vn");
    message.setTo(report.getEmail());
    message.setSubject("Daily report");
    message.setSentDate(new Date());
    // Set content
    message.setText(report.createReport());

    System.out.println(message.getText());

    return message;
}

From source file:org.benassi.bookeshop.web.interceptors.ConfirmationEmailInterceptor.java

@Override
public String intercept(ActionInvocation invocation) throws Exception {

    invocation.invoke();/*from   w ww .  ja  va  2s . c om*/

    Map<String, Object> session = ActionContext.getContext().getSession();
    loggedCustomer = (Customer) session.get(BookeshopConstants.SESSION_USER);

    Order order = ((CheckoutAction) invocation.getAction()).getOrder();
    order.setFormattedDate(orderUtil.formatDate(order.getDate()));
    order.setFormattedTotal(orderUtil.formatTotal(order.getTotal()));
    Map model = new HashMap();
    model.put("customer", loggedCustomer);
    model.put("order", order);

    String result = null;
    try {
        result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/orderConfirmation.vm",
                model);
    } catch (VelocityException e) {
        logger.error("Error in generating confirmation email from velocity template.", e);
        return Action.ERROR;
    }

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(messageProvider.getMessage("web.checkout.mail.from", null, null, null));
    message.setSentDate(new Date());
    message.setTo(loggedCustomer.getEmail());
    message.setSubject(messageProvider.getMessage("web.checkout.mail.object",
            new Object[] { order.getOrderId() }, null, null));
    message.setText(result);
    mailSender.send(message);
    return Action.SUCCESS;
}

From source file:com.mycompany.spring.batch.mail.demo.batch.SampleBatchApplication.java

@Bean
public ItemProcessor processor() {
    ItemProcessor processor = new ItemProcessor() {

        @Override/*from   w  ww  .j av a2s  . co m*/
        public SimpleMailMessage process(Object item) throws Exception {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("root@localhost.localdomain");
            message.setTo("c7@localhost.localdomain");
            message.setSubject(item.toString());
            message.setSentDate(new Date());
            message.setText("Hello " + item.toString());
            System.out.println("Sending message with subject: " + item);
            return message;
        }
    };
    return processor;
}

From source file:org.osiam.addons.administration.mail.EmailSender.java

private SimpleMailMessage getMessage(String fromAddress, String toAddress, String subject, String mailContent) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(fromAddress);//from  www.  j a va  2  s.  c  om
    message.setTo(toAddress);
    message.setSubject(subject);
    message.setText(mailContent);
    message.setSentDate(new Date());
    return message;
}

From source file:com.jrzmq.core.email.SimpleMailService.java

/**
 * ??//from  www .j  a v  a 2s  .  c o m
 * @param emailTo 
 * @param project 
 * @param ???
 * @param map     ?
 */
public void sendMail(String emailTo, String subject, String templateName, Map<String, Object> map) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setSentDate(new Date());
    msg.setTo(emailTo);
    msg.setSubject(subject);

    try {
        msg.setText(generateContent(templateName, map));
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
    } catch (Exception e) {
        logger.error("??{},:{},", new Object[] { emailTo, subject }, e);
    }
}

From source file:com.springsource.insight.plugin.mail.MessageSendOperationCollectionAspectTest.java

private void testSendMessage(int port) {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    sender.setHost(NetworkAddressUtil.LOOPBACK_ADDRESS);
    sender.setProtocol(JavaMailSenderImpl.DEFAULT_PROTOCOL);
    sender.setPort(port);/* w ww  . jav  a2 s  . co m*/

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("from@com.springsource.insight.plugin.mail");
    message.setTo("to@com.springsource.insight.plugin.mail");
    message.setCc("cc@com.springsource.insight.plugin.mail");
    message.setBcc("bcc@com.springsource.insight.plugin.mail");

    Date now = new Date(System.currentTimeMillis());
    message.setSentDate(now);
    message.setSubject(now.toString());
    message.setText("Test at " + now.toString());
    sender.send(message);

    Operation op = getLastEntered();
    assertNotNull("No operation extracted", op);
    assertEquals("Mismatched operation type", MailDefinitions.SEND_OPERATION, op.getType());
    assertEquals("Mismatched protocol", sender.getProtocol(),
            op.get(MailDefinitions.SEND_PROTOCOL, String.class));
    assertEquals("Mismatched host", sender.getHost(), op.get(MailDefinitions.SEND_HOST, String.class));
    if (port == -1) {
        assertEquals("Mismatched default port", 25, op.getInt(MailDefinitions.SEND_PORT, (-1)));
    } else {
        assertEquals("Mismatched send port", sender.getPort(), op.getInt(MailDefinitions.SEND_PORT, (-1)));
    }

    if (getAspect().collectExtraInformation()) {
        assertAddresses(op, MailDefinitions.SEND_SENDERS, 1);
        assertAddresses(op, MailDefinitions.SEND_RECIPS, 3);

        OperationMap details = op.get(MailDefinitions.SEND_DETAILS, OperationMap.class);
        assertNotNull("No details extracted", details);
        assertEquals("Mismatched subject", message.getSubject(),
                details.get(MailDefinitions.SEND_SUBJECT, String.class));
    }
}

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

/**
 * This method will process and sends notifications associated to a
 * scheduled notification. //ww  w.jav  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   www .j  a va2s  .com*/
            }

            //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.sipfoundry.sipxconfig.admin.mail.MailSenderContextImpl.java

public void sendMail(String to, String from, String subject, String body) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(getFullAddress(from));//w w w.  j  a  va  2  s  .  co  m
    msg.setFrom(getFullAddress(from));
    msg.setSubject(subject);
    msg.setText(body);
    msg.setSentDate(new Date());
    try {
        m_mailSender.send(msg);
    } catch (MailException e) {
        LOG.error(e);
    }

}

From source file:org.sipfoundry.sipxconfig.mail.MailSenderContextImpl.java

public void sendMail(String to, String from, String subject, String body) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(getFullAddress(to));/*from w w  w  .j a  v a 2 s  .c o  m*/
    msg.setFrom(getFullAddress(from));
    msg.setSubject(subject);
    msg.setText(body);
    msg.setSentDate(new Date());
    try {
        m_mailSender.send(msg);
    } catch (MailException e) {
        LOG.error(e);
    }

}